Setting attributes of image stored in byte array in servlet

Hi,
I am using a servlet to stream image (GIF) to the browser.
Image is accessed by browser using the img tag. src attribute points to the servlet which send the image stream.
Servlet has the image as the array of bytes. It simply write these bytes on the response object's output stream. It does not use any encoder.
I get the image on the browser. But when I try to see the properties of the image I don't see the type of image. I also don't see the created time, modified time and size of the image. When I do Save As on this image it tries to save it as BMP instead of GIF. Also when I do the print preview I don't see the image in the preview window. When I try to print the web page, it prints everything except this image. I get small cross(image missing) on the printed page.
I would like to know why the image attributes on browser go missing and why can't I print the image?
I would like to add that I am getting the image as the array of bytes from a different application on which I do not have control.
Thanks.

Hi,
I am using a servlet to stream image (GIF) to the browser.
Image is accessed by browser using the img tag. src attribute points to the servlet which send the image stream.
Servlet has the image as the array of bytes. It simply write these bytes on the response object's output stream. It does not use any encoder.
I get the image on the browser. But when I try to see the properties of the image I don't see the type of image. I also don't see the created time, modified time and size of the image. When I do Save As on this image it tries to save it as BMP instead of GIF. Also when I do the print preview I don't see the image in the preview window. When I try to print the web page, it prints everything except this image. I get small cross(image missing) on the printed page.
I would like to know why the image attributes on browser go missing and why can't I print the image?
I would like to add that I am getting the image as the array of bytes from a different application on which I do not have control.
Thanks.

Similar Messages

  • How to convert a Image object to byte Array?

    Who can tell me, how to convert Image object to byte Array?
    Example:
    public byte[] convertImage(Image img) {
    byte[] b = new byte...........
    return b;

    Hello,
    any way would suit me, I just need a way to convert Image or BufferedImage to a byte[], so that I can save them. Actually I need to save both jpg and gif files without using any 3rd party classes. Please help me out.
    thanx and best wishes

  • How do I display a GIF image stored in byte[ ]

    I have a bit of sticky problem and am now stuck. I will post a little code in the hopes someone more clever than I can give me a hand
    I am using a servlet to grab some data from a user, a web service (still within the servlet) is then called that generates a GIF of the user location as
    specified by the address data grabbed from the user input (GET via the url parameters). The byte data is stored in a bean as a byte [ ] and added to the request as an attribute
    via request.setAttribute().
    I then forward to a jsp page that looks like this:
         <html>
         <head>
         <title>Learn Fast or Perish</title>
         </head>
         <body>
         <center>
         <hr>
         </center>
         <h1>Hello World.</h1>
         <jsp:include page="/display" flush="true"/>
         </body>
         </html>.../display maps to another servlet. The doGet portion of the servlet looks like this:
                //response and request are the HTTPServletResponse/Request doGet parameters
                //ImageByteInformation is my bean holding image info in byte [] format
                ImageByteInformation imageByteInfo = (ImageByteInformation) request.getAttribute("imageByteInformation");
                ImageIcon imageIcon = new ImageIcon(imageByteInfo.getByteData());
                Image image = imageIcon.getImage();
                //create a BufferedImage from the image
                BufferedImage bufferedImage = new BufferedImageCreator().createBufferedImage(image);
                System.out.println("BufferedImage length: " + bufferedImage.getHeight() + "BufferedImage width: " + bufferedImage.getWidth());//400 by 600
                System.out.println("BufferedImage string: " + bufferedImage.toString());
                //prints out: BufferedImage@93afae: type = 2 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=ff000000 IntegerInterleavedRaster: width=600 yada yada
                response.setContentType("/image/gif");
                OutputStream stream = response.getOutputStream();
                ImageIO.write(bufferedImage, "gif", stream);
                stream.close();... i found the code above on line and this is supposed to display a GIF to a web page.
    For a while the code was actually prompting if I wanted to download a file of type "/image/gif"?!?
    I did download and save it as temp.gif and the image was there when I opened it on my desktop.
    Something is in the byte array but I cannot get it to display on the page. So what am I doing wrong.
    So my question is this...
    How can I display the gif info stored as a byte [] (byte array) in a bean with a jsp page. I thought including a servlet that
    writes the bytes to the reponse would but no such luck. Is what I am trying possible? This newbie would greatly appreciate
    any advice :)

    First of all the following line is a little off:
    response.setContentType("/image/gif");should be
    response.setContentType("image/gif");What you should do is rather than do an include, try something like the following:
    <img src="/display" />If you're telling me that /display is mapped to the servlet that has the doGet you reference, this would be the proper way to do it.
    HTH.

  • Display an object of Image type or Byte Array

    Hi, lets say i got an image stored in the Image format or byte[]. How can i make it display the image on the screen by taking the values in byte array or Image field?

    Thanks rahul,
    The thing is, i am generating a chart in a servlet
    and setting the image in the form of a byte [] to the
    view bean ( which is binded to the jsp, springs
    framework ). The servlet would return the view bean
    to the jsp and in the jsp, i am suppose to print this
    byte array so as to give me the image..
    I hope this makes sense.. pls help me ou!Well letme see if i got tht right or not,
    you are trying to call Your MODEL (Business layer / Spring Container) from a servlet and you are expressing that logic in form of chart (Image) and trying to save it as a byte array in a view bean and you want to print /display that as an image in a jsp (After Servlet fwd / redirect action) which includes other data using a ViewBean.
    If this is the case...
    As the forwaded JSP can include both image and Textual (hypertext too)..we can try a work around hear...Lets dedicate a Servlet which retreives byte [] from a view bean and gives us an image output. hear is an example and this could be a way.
    Prior to that i'm trying to make few assumptions here....
    1).The chart image which we are trying to express would of format JPEG.
    2).we are trying to take help of<img> tag to display the image from the image generating servlet.
    here is my approach....
    ViewBean.java:
    ============
    public class ViewBean implements serializable{
    byte piechart[];
    byte barchart[];
    byte chart3D[];
    public ViewBean(){
    public byte[] getPieChart(){
    return(this.piechart);
    public byte[] getBarChart(){
    return(this.barchart);
    public byte[] get3DChart(){
    return(this.chart3D);
    public void setPieChart(byte piechart[]){
    this.piechart = piechart;
    public void setBarChart(byte barchart[]){
    this.barchart = barchart;
    public void set3DChart(byte chart3D[]){
    this.chart3D = chart3D;
    }ControllerServlet.java:
    =================
    (This could also be an ActionClass(Ref Struts) a Backing Bean(Ref JSF) or anything which stays at the Controller Layer)
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
    /* There are few different implementations of getting   BeanFactory Resource
    In,the below example i have used XmlBeanFactory Object to create an instance of (Spring) BeanFactory */
    BeanFactory factory =
    new XmlBeanFactory(new FileInputStream("SpringResource.xml"));
    //write a Util Logic in your Implementation class using JFreeChart (or some open source chart library) and express the images by returning a  byte[]
    ChartService chartService =
    (GreetingService) factory.getBean("chartService");
    ViewBean vb = new ViewBean();
    vb.setPieChart(chartService.generatePieChart(request.getParameter("<someparam>"));
    vb.setBarChart(chartService.generateBarChart(request.getParameter("<someparam1>"));
    vb.set3DChart(chartService.generate3DChart(request.getParameter("<someparam2>"));
    chartService = null;
    HttpSession session = request.getSession(false);
    session.setAttribute("ViewBean",vb);
    response.sendRedirect("jsp/DisplayReports.jsp");
    }DisplayReports.jsp :
    ================
    <%@ page language="java" %>
    <html>
    <head>
    <title>reports</title>
    </head>
    <body>
    <h1 align="center">Pie Chart </h1>
    <center><img src="ImageServlet?req=1" /></center>
    <h1 align="center">Bar Chart </h1>
    <center><img src="ImageServlet?req=2" /></center>
    <h1 align="center">3D Chart</h1>
    <center><img src="ImageServlet?req=3" /></center>
    </body>
    </html>ImageServlet.java
    ==============
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
           byte buffer[];
            HttpSession session = request.getSession(false);
            ViewBean vb = (ViewBean) session.getAttribute("ViewBean");
            String req = request.getParameter("req");
            if(req.equals("1") == true)       
                buffer = vb.getPieChart();
            else if(req.equals("2") == true)
                 buffer = vb.getBarChart();
            else if(req.equals("3") == true)
                 buffer = vb.get3DChart();
            JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new ByteArrayInputStream(buffer));
            BufferedImage image =decoder.decodeAsBufferedImage() ;
            response.setContentType("image/jpeg");
            // Send back image
            ServletOutputStream sos = response.getOutputStream();
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
            encoder.encode(image);
        }Note: Through ImageServlet is a Servlet i would categorise it under presentation layer rather to be a part of Controller and added to it all this could be easily relaced by a reporting(BI) server like JasperServer,Pentaho,Actuate................
    Hope the stated implementation had given some idea to you....
    However,If you want to further look into similar implementations take a look at
    http://www.swiftchart.com/exampleapp.htm#e5
    which i believe to be a wonderful tutor for such implementations...
    However, there are many simple (Open) solutions to the stated problem.. if you are Using MyFaces along with spring... i would recommend usage of JSF Chart Tag which is very simple to use all it requires need is to write a chart Object generating methos inside our backing bean.
    For further reference have a look at the below links
    http://www.jroller.com/page/cagataycivici?entry=acegi_jsf_components_hit_the
    http://jsf-comp.sourceforge.net/components/chartcreator/index.html
    NOTE:I've tried it personally using MyFaces it was working gr8 but i had a hardtime on deploying my appln on a Portal Server(Liferay).If you find a workaround i'd be glad to know about it.
    & there are many BI Open Source Server Appls that can take care of this work too.(Maintainace wud be a tough ask when we go for this)
    For, the design perspective had i've been ur PM i wud have choose BI Server if it was corporate web appln on which we work on.
    Hope this might be of some help :)
    REGARDS,
    RaHuL

  • How to convert an Image to a byte array?

    I want to make a screenshot and then convert the image to a byte of arrays so I can send it through a BufferedOutputStream.
    try
                   robot = new Robot();
                   screenshot = robot.createScreenCapture(new Rectangle(500,500));
                   imageFile = new File("image.png");
                   ImageInputStream iis = ImageIO.createImageInputStream(screenshot);
                   byte[] data = new byte[1024];
                   byte[] tmp = new byte[0];
                   byte[] myArrayImage = new byte[0];
                   int len = 0;
                   int total = 0;
                   while((len = iis.read(data)) != -1 ) // LINE 52 --- EXCEPTION CATCHED HERE
                        total += len;
                        tmp = myArrayImage;
                        myArrayImage = new byte[total];
                        System.arraycopy(tmp,0,myArrayImage,0,tmp.length);
                        System.arraycopy(data,0,myArrayImage,tmp.length,len);
                   ios.close();I get this exception while running:
    Exception in thread "Thread-0" java.lang.NullPointerException
    at Server.run(Server.java:52)
    at java.lang.Thread.run(Unknown Source)

    Fixed that. I got a new problem.
    When I connect to my simple server application that reads the image file, converts it to an array of bytes and sends it back, the file is created on the client side and it containts data, but I am not able to open the image. I have checked that the image that the server is sending is working. So where is the problem?
    The client application recieves the image as following:
    public void run()
            try
                socket = new Socket("127.0.0.1", 2000);
                BufferedOutputStream out_file = new BufferedOutputStream(new FileOutputStream("recieved_img.png"));
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                int inputLine;
                while((inputLine = in.read()) != -1)
                    char c = (char)inputLine;
                    System.out.println(c);
                    out_file.write(inputLine);
            catch(IOException err){ err.printStackTrace(); }
        }And the server sends the image like this;
    try
              socket = server.accept();
              in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
              out = new BufferedOutputStream(socket.getOutputStream());
              out.write(25);
              while((inputLine = in.readLine()) != null)
                   System.out.println(myArrayImage.length);
              System.out.println(inputLine);
                        out.write(myArrayImage);     // Send the array of bytes
         }

  • Converting Image.jpg to byte array

    Hi,
    How do i convert a image (in any format like .jpeg, .bmp, gif) into a byte array
    And also vice versa, converting byte array to image format
    Thank you

    how about Class.getResourceAsStream(String name).read(byte[] b)?

  • How to convert the record stored iin byte array to integers

    im making a simple game in j2me and i want to get the max scores and show it for each player , what i face right now that i cant convert the records which i stored in bytes to integers when i read it from file to get the max.
    thanks

    have a look at java.io.DataInputStream

  • Image Conversion with Byte Arrays

    I'm trying to read in a byte[] for JPG, PNG, BMP, and GIF files which will then be converted to a .TIFF file so it can be printed on Post Script printers.
    Technically I have it working BUT the catch is that it physically needs to create the file. I'd like to have it all done in memmory and not have to actaully have a physical file created.
    I have been trying many different things with the JAI.create function. Near as I can see so far that only creates a RenderedImage which then creats a file even if I use "stream" inscreat off "filename".
    Any suggestions would be appreciated.
    Thanks.

    I got it figured out. It does make the TIFF a little bit larger but that's ok.
    RenderedOp src = JAI.create("stream", new com.sun.media.jai.codec.ByteArraySeekableStream(image));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JAI.create("encode", src, out, "TIFF", null);
    return out.toByteArray();

  • Deriving color space of an image from a byte array input stream.

    I was wondering, is it possible to derive the color space of an image, i.e. RGB, YCC, GRAY by calculating its bytes?

    Calculate bytes just means doing operations on the
    byte values. That's how I got the height and width of
    the image. Now, I'm wondering if it is possible for
    the color space.Look at the format specifications...
    By the way, do all image file types have different
    color space or could they all have the same color
    space, for example, RGB?They can have different color spaces. RGB, ARGB, CMYK, some Adobe format...

  • Displaying the .png image stored in an byte array

    Hi,
    I have to download an .png image from a server and i have to store it in a byte array and i have to display this byte array in another servlet. I have written the code to get the image from the remote server in a java class. The java class returns the byte array of the image and i have to display that in an servlet.
    If anybody has the code or any refrence to refer please help me..
    Thanks & Regards
    -Sandeep

    I have pasted code for servlet's doGet method which writes image data...
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws
    ServletException, IOException
    HttpSession session = request.getSession(); //taking httpsession
    response.setContentType("image/jpeg");
    ServletOutputStream out = response.getOutputStream(); //taking outputstream of response
    if (rtn.getErrorCode() == 0)
    //this will actually write image file data from where it is being called
    //byte array will contain image data, please load your image into below byte array variable
    byte[] b = new byte[100];
    out.write(b);
    out = null; //making null
    session = null; //making null
    In other servlet, write <img> tag and specify its src attribute to the "name of servlet where u have pasted above code" ..
    Regards,
    Nikhil

  • Working with ExtensionData attribute (byte arrays)

    Hello all,
    I am working with the ExtensionData attribute in PowerShell, which is in byte array form. What I am wanting to do is change a part of this ExtensionData attribute, but still keep the byte array form. What I am currently trying makes the change successfully,
    but I lose the byte array form. For example, before changing the ExtensionData attribute, Group1's ExtensionData attribute is populated on several lines within the attribute. After changing the attribute, Group1's ExtensionData attribute has all the same values,
    but is now contained on a single line. Here is the code used:
    #Finding Group1's ExtensionData attribute, in string form
    $ExtensionData = Get-ADGroup "Group1" -Properties extensiondata | select -ExpandProperty extensiondata | ForEach-Object {
    [System.Text.Encoding]::ASCII.GetString($_)
    #Let's assume Group1's ExtensionData attribute looks like this (multiple lines):
    #OldLine1
    #OldLine2
    #OldLine3
    $StringOld = "OldLine1"
    $StringNew = "NewLine1"
    #making sure line I want to change is present in string form of ExtensionData attribute, then we change the part we want
    If($ExtensionData -match $StringOld){
    $ExtensionData -replace "$StringOld","$StringNew"
    #Now we convert our new ExtensionData string form back to ASCII form
    $change = [System.Text.Encoding]::ASCII
    $NewExtensionData = $change.GetBytes($ExtensionData)
    #Now, we can replace Group1's ExtensionData attribute with our new ExtensionData attribute
    Set-ADGroup Group1 -Replace @{extensiondata=$NewExtensionData}
    #However, now Group1's ExtensionData attribute looks like this (no multiple lines):
    #NewLine1OldLine2OldLine3
    How can I replace a line in the ExtensionData attribute and still keep the multiple lines within the attribute?

    David,
    Thanks again for taking time to help me out with this problem! I've solved my problem, but had to perform a few steps along the way. Long story short, I slightly modified the code you provided using -match and -replace for the strings, and then
    when I tried to use -replace on the set-adgroup cmdlet, PowerShell griped and said value already present.
    However, I was able to get it to work by clearing the extensiondata attribute first and then using -add. This put the bytes into the extensiondata attribute as expected, but there were 2 problems with this. First, it looked like each byte was it's own array
    within the attribute. Second, the original ExtensionData attribute had strings in it, not bytes. I have since realized that bytes is how PowerShell reads the array, but not how ADUC displays it.
    What I did was use the following code:
    cls
    $ExtensionData = @(
    Get-ADGroup "Group1" -Properties extensiondata |
    Select-Object -ExpandProperty extensiondata |
    ForEach-Object {
    [System.Text.Encoding]::ASCII.GetString($_)
    $StringOld = "OldString"
    $StringNew = "NewString"
    for ($i = 0; $i -lt $ExtensionData.Count; $i++)
    if ($ExtensionData[$i] -match $StringOld)
    $ExtensionData[$i] = $ExtensionData[$i] -replace "$Stringold","$StringNew"
    Set-ADGroup SmartDL-test -replace @{extensiondata=$ExtensionData}
    As you can see, I still use -match and -replace to swap out the part of ExtensionData that I want. But it turns out I didn't need to convert the strings into bytes before using the set-adgroup command. I was able to just replace the part of the extensiondata
    collection I wanted, and then just paste the entire new collection into the attribute, and for my purposes it appeared to work.
    Anyway, I really appreciate your help on this, and it must be difficult helping someone troubleshoot when you can't see specifically what they're trying to do. Your post was extremely helpful however, and it led to the solution that worked for me. Thanks
    again!

  • How do i covert an image in J2ME into an byte array ?

    Can anyone help to show me the way to convert an image into a byte array ?
    Thanks early reply appreciated.

    Hi! I�m developing an application to be installed in two devices. My problem is that i want to send an image: I can receive it with createImage(InputStream ip), but how can i send it with OutputStream? it needs a byte array (method write), how can i convert an image into a byte array?is there any other solution? like send it as a string...
    Thanks

  • To create images continuously using a byte array  while streaming video

    Can someone please help me in creating images from a byte array continuously which is required while streaming video on implementation of RTP?

    seems like this could be the class you want to look at
    Package javax.imageio

  • Converting image into byte array

    Hi all,
    How to convert an integer array image into byte array ?
    here i have a image like this :
    private static int pixelArray[] = {
    0xff000000, 0xff000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
    0xff000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000
    From this one i create image like this one :
    Image image = Image.createRGBImage(pixelArray, width, height, true);
    Now i want to convert that pixelArray into byte array ? how to do this
    additionally i want to send this byte array to servlet .
    thanks in advance.

    Hi,
    If you want to convert your int array to a byte array you should
    split each integer into 4 bytes to avoid losing information. You can
    rebuild your integer array later if you need to. I think this code
    will work (i havent tested it):
    byte[] pixel= new byte[pixelArray.length<< 2];
    for (int i= pixelArray.length- 1; i>= 0; i--) {
      int aux= i<< 2;  // i* 4 = i<< 2
      pixel[aux]=    (byte) (pixelArray>> 32);
    pixel[aux+ 1]= (byte) (pixelArray[i]>>> 16);
    pixel[aux+ 2]= (byte) (pixelArray[i]>>> 8);
    pixel[aux+ 3]= (byte) pixelArray[i];
    Greets.

  • Displaying Byte Array images in coldfusion

    This has been driving me crazy for a couple of days now.I
    have a Java class that returns pictures stored in a DB as a Byte
    Array.
    I am able to display the image but that is all i am able to
    do - I want to display the image name, description etc in a HTML
    before i display the actual image but i can't seem to find a way to
    do that.
    I tried using CFcontent as well and that did not help
    either.This is what i am currently doing - and all that displays on
    the screen is the picture and all content before the picture is
    nowhere to be seen.
    Picture Name: #variables.picName#
    Picture Description:#variables.picDescription#
    <cfscript>
    context = getPageContext();
    response = context.getResponse().getResponse();
    out = response.getOutputStream();
    response.setContentType("image/jpeg");
    response.setContentLength(arrayLen(session.picture));
    out.write(session.picture);
    out.flush();
    out.close();
    </cfscript>
    Any help will be greatly appreciated.

    Mark,
    Note that the portal sets the content type (e.g, text/html) and encoding
    as the portal page starts rendering. In your case, the
    setContentType() would be useless since the servlet container won't let
    you change it. You can either use a popup browser window for the pdf as
    Kunal suggested, or use an iframe if you want to render the pdf inside
    the portlet window.
    Subbu
    Mark Gilleece wrote:
    Hi,
    i need to display a PDF file. The PDF is stored in a byte array. This works fine when i run my code (see below) from the .jpf via the debugger/browser, but when i use it as a portlet, in the portal, it does not work ?
    Any help is much appreciated.
    Thanks
    Mark
    byte[] pdfDocument = docStore.getPDF();
    ServletOutputStream outPdf = response.getOutputStream();
    response.setContentType("application/pdf");
    outPdf.write(pdfDocument);
    outPdf.flush();
    outPdf.close();

Maybe you are looking for