BufferedImage - byte[] ??

I want to send an Image from my applet to my servlet via an HTTP connection. I want to do the encoding of the image to gif/jpeg on the server side and not in the applet, therefor I have to transfer
the Image object via http as binary data. Because the BufferedImage is not serializable I have to send it as byte[] or something else. How can I get my BufferedImage as a byte[] to send it over my Http connection?
regards,
Fredrik Forsberg

Earlier I tried out a solution where I sent the image data as a byte array over a raw socket and that worked out fine. But that only worked because I got a ByteOutputStream by encoding the BufferedImage. Without encoding the picure I have to get the data elseway. Now Im sending over an int array that I got by calling getRGB() on the Image object.
Recently I got problems. The server refuses to react to my
http connection from the applet. When I load the url from a browser
the server reacts in a normal way though. Why?
Here I make the connection in the applet to the webserver
location = "http://localhost:8080/portal/saveImageFromApplet.do";
servletUrl = new URL(location);
servletConnection = servletUrl.openConnection();
servletConnection.setDoOutput(true);
servletConnection.setDoInput(true);
servletConnection.setUseCaches (false);
servletConnection.setDefaultUseCaches (false);
servletConnection.setRequestProperty ("Content-Type", "application/octet-stream");
outputToServlet = new ObjectOutputStream (servletConnection.getOutputStream());
outputToServlet.writeObject(pixels); // pixels is a int[]
outputToServlet.flush();
outputToServlet.close();
Nothing happens. Not even an exception in the applet. The servlet actually is an Action class called by the controller servlet in the Struts framework.
Have anybody had the same problem with this Applet-servlet communication via Http?

Similar Messages

  • Image to jpeg

    From an object java.awt.Image I must obtain an object byte[] type that have to
    contain an jpeg imaging type. For doing that I am using the attached code but it
    is very slow when it is in execution and it use a lot of energy from the
    system. How can i do in order to obtain the same result most quickly?
    Thank for you help.
    javax.media.Buffer buffergrabber= frameGrabber.grabFrame();
    java.awt.Image image= (new javax.media.util.BufferToImage((javax.media.format.VideoFormat)buffergrabber.getFormat()).createImage(buffergrabber));
    int pix[]= new int[image.getWidth(null) * image.getHeight(null)];
    java.awt.image.PixelGrabber pg= new java.awt.image.PixelGrabber(image, 0, 0, image.getWidth(null), image.getHeight(null), pix, 0, image.getWidth(null));
    pg.grabPixels();
    java.awt.image.BufferedImage bufferedimage= new java.awt.image.BufferedImage(image.getWidth(null), image.getHeight(null), java.awt.image.BufferedImage.TYPE_INT_RGB);
    for (int count= 0; count< image.getHeight(null); count++) {
        for (int count_2= 0; count_2< image.getWidth(null); count_2++) {
            bufferedimage.setRGB(count_2, count, pix[count * image.getWidth(null)+ count_2]);
    try {
        java.io.ByteArrayOutputStream bytearrayoutputstream= new java.io.ByteArrayOutputStream();
        com.sun.image.codec.jpeg.JPEGImageEncoder imageencoder= com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder(bytearrayoutputstream);
        com.sun.image.codec.jpeg.JPEGEncodeParam encoderparam= imageencoder.getDefaultJPEGEncodeParam(bufferedimage);
        imageencoder.setJPEGEncodeParam(encoderparam);
        encoderparam.setQuality(1.0F, true);
        imageencoder.encode(bufferedimage);
        byte MyJPEGImage[]= bytearrayoutputstream.toByteArray();
    catch(java.io.IOException e) {
        System.out.println(e);
    }

    Best to use the original.
    If youv lost it, remove any other objects over the image and size the image to fill the slide, then use export.

  • Can you get the original bytes/format from a BufferedImage

    Applications allows users to select file and then the contents of the files are embedded into an mp3 file, but also allow images to be dragged or copy and pasted and in vertainn cases I only recieve the image as an Image DataFlavor (new DataFlavor("image/x-java-image;class=java.awt.Image");), so I have the bufferedImage but I need to convert into a stream of bytes and I don't have the bytes or even the the orginal format of the image, or are they hidden in the BufferedImage somewhere. At the moment I'm always writing the Bufferedimage as a jpeg whereas Id prefer to write the original format if supported, not least because sometimes ImageIO actually renders the file incorrectly (#4881314 , #6444933).
    thanks Paul

    Not possible. No.

  • How to get a string or byte array representation of an Image/BufferedImage?

    I have a java.awt.Image object that I want to transfer to a server application (.NET) through a http post request.
    To do that I would like to encode the Image to jpeg format and convert it to a string or byte array to be able to send it in a way that the receiver application (.NET) could handle. So, I've tried to do like this.
    private void send(Image image) {
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        try {
            BufferedImage buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            ImageIcon imageIcon = new ImageIcon(image);
            ImageObserver observer = imageIcon.getImageObserver();
            buffImage.getGraphics().setColor(new Color(255, 255, 255));
            buffImage.getGraphics().fillRect(0, 0, width, height);
            buffImage.getGraphics().drawImage(imageIcon.getImage(), 0, 0, observer);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(stream);
            jpeg.encode(buffImage);
            URL url = new URL(/* my url... */);
            URLConnection connection = url.openConnection();
            String boundary = "--------" + Long.toHexString(System.currentTimeMillis());
            connection.setRequestProperty("method", "POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            String output = "--" + boundary + "\r\n"
                          + "Content-Disposition: form-data; name=\"myImage\"; filename=\"myFilename.jpg\"\r\n"
                          + "Content-Type: image/jpeg\r\n"
                          + "Content-Transfer-Encoding: base64\r\n\r\n"
                          + new String(stream.toByteArray())
                          + "\r\n--" + boundary + "--\r\n";
            connection.setDoOutput(true);
            connection.getOutputStream().write(output.getBytes());
            connection.connect();
        } catch {
    }This code works, but the image I get when I save it from the receiver application is distorted. The width and height is correct, but the content and colors are really weird. I tried to set different image types (first line inside the try-block), and this gave me different distorsions, but no image type gave me the correct image.
    Maybe I should say that I can display the original Image object on screen correctly.
    I also realized that the Image object is an instance of BufferedImage, so I thought I could skip the first six lines inside the try-block, but that doesn't help. This way I don't have to set the image type in the constructor, but the result still is color distorted.
    Any ideas on how to get from an Image/BufferedImage to a string or byte array representation of the image in jpeg format?

    Here you go:
      private static void send(BufferedImage image) throws Exception
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpeg", byteArrayOutputStream);
        byte[] imageByteArray = byteArrayOutputStream.toByteArray();
        URL url = new URL("http://<host>:<port>");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(imageByteArray, 0, imageByteArray.length);
        outputStream.close();
        connection.connect();
        // alternative to connect is to get & close the input stream
        // connection.getInputStream().close();
      }

  • Error when creating BufferedImage with IndexColorModel from a byte array.

    Hi, I have a 1-dimentional byte array and an IndexColorTable, and I can't figure out how to combine the 2 into an BufferedImage without unnecessary copying/reallocating of the image buffer.
    The color model I have is:
    int [] cmap = new int [numColors];
    cmap[i++] = 0xffa0f000;  /etc.
    new IndexColorModel(8, 22, cmap, 0, true,  transparentIndex,  DataBuffer.TYPE_BYTE );Thanks for your help
    -Ben
    Ps.
    I've was looking at some example code (http://javaalmanac.com/egs/java.awt.image/Mandelbrot2.html?l=rel), and can't figure out how to go from the color model they're using to the one I have (the 8 bit one specified above). When I replace the 4bit colormodel in the code below with the 8bit color model specified above, I get the following error:
    [java] java.lang.IllegalArgumentException: Raster ByteInterleavedRaster: width = 5120 height = 3520 #numDataElements 1 dataOff[0] = 0 is incompatible with ColorModel IndexColorModel: #pixelBits = 8 numComponents = 4 color space = java.awt.color.ICC_ColorSpace@c51355 transparency = 2 transIndex = 22 has alpha = true isAlphaPre = false
    [java] at java.awt.image.BufferedImage.<init>(BufferedImage.java:613)
    Code:
    byte[] pixelArray = (byte[]) getData_CHAR();                
    int width = 5120;
    int height = 3520;
    int numbytes = width*height;
    //create DataBuffer using byte buffer of pixel data.
    DataBuffer dataBuffer = new DataBufferByte(pixelArray, numbytes, 0);
    //prepare a sample model that specifies a storage 8-bits of pixel data in an 8-bit data element
    int bitMasks[] = new int[]{0xf};
    SinglePixelPackedSampleModel sampleModel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, bitMasks);
    //create a raster using the sample model and data buffer
    WritableRaster writableRaster = Raster.createWritableRaster(sampleModel, dataBuffer, new Point(0,0));
    //generate 16-color model
    byte[] r = new byte[16];
    byte[] g = new byte[16];
    byte[] b = new byte[16];
    r[0] = 0; g[0] = 0; b[0] = 0;
    r[1] = 0; g[1] = 0; b[1] = (byte)192;
    r[2] = 0; g[2] = 0; b[2] = (byte)255;
    r[3] = 0; g[3] = (byte)192; b[3] = 0;
    r[4] = 0; g[4] = (byte)255; b[4] = 0;
    r[5] = 0; g[5] = (byte)192; b[5] = (byte)192;
    r[6] = 0; g[6] = (byte)255; b[6] = (byte)255;
    r[7] = (byte)192; g[7] = 0; b[7] = 0;
    r[8] = (byte)255; g[8] = 0; b[8] = 0;
    r[9] = (byte)192; g[9] = 0; b[9] = (byte)192;
    r[10] = (byte)255; g[10] = 0; b[10] = (byte)255;
    r[11] = (byte)192; g[11] = (byte)192; b[11] = 0;
    r[12] = (byte)255; g[12] = (byte)255; b[12] = 0;
    r[13] = (byte)80; g[13] = (byte)80; b[13] = (byte)80;
    r[14] = (byte)192; g[14] = (byte)192; b[14] = (byte)192;
    r[15] = (byte)255; g[15] = (byte)255; b[15] = (byte)255;
    //create buffered image    
    ColorModel colorModel = new IndexColorModel(4, 16, r, g, b);
    BufferedImage image = new BufferedImage(colorModel, writableRaster, false, null);Message was edited by:
    ben_weisburd
    Message was edited by:
    ben_weisburd

    I had the same problem too.
    anyone found the solution for this problem?
    thanks
    Bruno Rabino
    When I try to make a MD-form, where the base-table for the detail contains a column with a BLOB-datatype. I get following error when I finish creation of the form.
    Error: Exception from wwv_generate_component.build_procedure (WWV-01821)
    Error creating module: ORA-01403: no data found (WWV-16042)
    When I use the table with the BLOB as master or in a form, it works fine.
    Has anyone else experienced this problem? Or knows a way to fix or work around it. Thanks in advance.
    Portal version: 3.0.6.6.5
    null

  • IOImage.write showing error after byte[] to BufferedImage

    I am new to Image Manipulations in Java and I am writing some program related to Image Steganography by Mapping Pixels to Letters..
    I have successfully read the data from gray scale image to BufferedImage object and read the pixels in byte array..
    byte []data;
    DataBufferByte buffer = (DataBufferByte) image.getRaster().getDataBuffer();
    data = buffer.getData();Now for testing the working of my pixel morphing I have changed two pixels data[0] and data[1] and tried to store it in some target.jpg file.. For that I used
    image.data[0]=(byte)3;
    image.data[1]=(byte)1;
    InputStream in = new ByteArrayInputStream(image.data);
        try {
                BufferedImage img = javax.imageio.ImageIO.read(in);
                image.write(img, ref);
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    Now I am getting error because ImageIO.read is returning NULL to BufferedImage img.. hence write method is throwing IllegalArgumentException.
    I am totally lost.. please help me..
    Edited by: Neo_Cerf on Feb 22, 2010 8:01 PM

    Wrap the byte array in a DataBufferByte. Create an appropriate raster via one of the Raster#createXXXRaster methods. Then create and appropriate ColorModel and use the BufferedImage constructor that takes a raster and a color model. For a byte[] array representing gray data, this would be done like so.
    byte[] imgData = ...;
    int w = ...;
    int h = ...;
    //the DataBuffer
    DataBuffer db = new DataBufferByte(imgData,imgData.length);
    //the Raster
    WritableRaster rast =  Raster.createInterleavedRaster(
           db, w, h, w, 1, new int[]{0}, null);
    //the ColorModel
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
    ColorModel cm = new ComponentColorModel(
           cs,new int[]{8}, false, true,
           java.awt.Transparency.OPAQUE,
           DataBuffer.TYPE_BYTE);
    //the BufferedImage
    BufferedImage img = new BufferedImage(cm,rast,true,null);

  • 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.

  • How do I read directly from file into byte array

    I am reading an image from a file into a BuffertedImage then writing it out again into an array of bytes which I store and use later on in the program. Currently Im doing this in two stages is there a way to do it it one go to speed things up.
    try
                //Read File Contents into a Buffered Image
                /** BUG 4705399: There was a problem with some jpegs taking ages to load turns out to be
                 * (at least partially) a problem with non-standard colour models, which is why we set the
                 * destination colour model. The side effect should be standard colour model in subsequent reading.
                BufferedImage bi = null;
                ImageReader ir = null;
                ImageInputStream stream =  ImageIO.createImageInputStream(new File(path));
                final Iterator i = ImageIO.getImageReaders(stream);
                if (i.hasNext())
                    ir = (ImageReader) i.next();
                    ir.setInput(stream);
                    ImageReadParam param = ir.getDefaultReadParam();
                    ImageTypeSpecifier typeToUse = null;
                    for (Iterator i2 = ir.getImageTypes(0); i2.hasNext();)
                        ImageTypeSpecifier type = (ImageTypeSpecifier) i2.next();
                        if (type.getColorModel().getColorSpace().isCS_sRGB())
                            typeToUse = type;
                    if (typeToUse != null)
                        param.setDestinationType(typeToUse);
                    bi = ir.read(0, param);
                    //ir.dispose(); seem to reference this in write
                    //stream.close();
                //Write Buffered Image to Byte ArrayOutput Stream
                if (bi != null)
                    //Convert to byte array
                    final ByteArrayOutputStream output = new ByteArrayOutputStream();
                    //Try and find corresponding writer for reader but if not possible
                    //we use JPG (which is always installed) instead.
                    final ImageWriter iw = ImageIO.getImageWriter(ir);
                    if (iw != null)
                        if (ImageIO.write(bi, ir.getFormatName(), new DataOutputStream(output)) == false)
                            MainWindow.logger.warning("Unable to Write Image");
                    else
                        if (ImageIO.write(bi, "JPG", new DataOutputStream(output)) == false)
                            MainWindow.logger.warning("Warning Unable to Write Image as JPEG");
                    //Add to image list
                    final byte[] imageData = output.toByteArray();
                    Images.addImage(imageData);
                  

    If you don't need to manipulate the image in any way I would suggest you just read the image file directly into a byte array (without ImageReader) and then create the BufferedImage from that byte array.

  • BufferedImage displays as streaky; smooth image not produced

    Hi all,
    I have three classes that I'm working with. One is ImageProcessor, a Class I have to process images. Another is IMAQGUI, a GUI for my IMAQ service, and the third is IMAQIceStormService.
    In IMAQIceStormService, I am using ImageProcessor to create an image from a byte[] that gets sent to me, and I'm using IMAQGUI to display the image on my GUI.
    All this is working fine, except the image does not display properly. I am getting the proper data, as I have compared the camera image to my streaky image, and saw that they are the same. The width, height, depth, and stride should all be correct; 1000x1000 pixels, 8 bits per pixel, and a stride of 0. I recently changed my ImageProcessor code to make some methods static, and I may have broken something.
    Basically, can anyone take a look at my ImageProcessor methods, and possibly give any suggestions as to why the image is not displaying correctly?
    Here is the relevant part of IMAQIceStormService:
         public void imageAcquired(long id, IMAQTypes.ImageDesc imageDesc, byte[] imageData,
              Ice.Current current) {
              IMAQGUI.appendImage(ImageProcessor.createImage(imageData, imageDesc.width, imageDesc.height));
         }IMAQTypes.ImageDesc is simply the image description. It tells me the width, height, depth, and stride of the image. As you can see, I am telling IMAQGUI to appendImage based on what returns from ImageProcessor. First, here is the relevant code from IMAQGUI:
         private static JLabel imageViewer = new JLabel(); // this gets added to the main panel in a different method
         public static void appendImage(BufferedImage image) {
              imageViewer.setIcon(new ImageIcon(image));
              imageViewer.revalidate();
         }This just sets the icon to the new image, and revalidates the JLabel so it displays the new image.
    Finally, here is the most important part. This is the relevant code from ImageProcessor:
        public static BufferedImage toImage(byte[] data, int w, int h) {
            DataBuffer buffer = new DataBufferByte(data, data.length);
            WritableRaster raster = Raster.createInterleavedRaster(buffer, w, h, w,
            1, new int[] {
                0
            } , null);
            ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
            ColorModel cm = new ComponentColorModel(cs, false, true,
            Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
            return new BufferedImage(cm, raster, false, null);
        public static BufferedImage createImage(byte[] data, int width, int height) {
              BufferedImage im = toImage(data, width, height);
            //image = toImage(data, width, height);
            BufferedImage out = createRGBImage(im);
            return out;
        public static BufferedImage createRGBImage(BufferedImage in) {
            BufferedImage output = new BufferedImage(in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics2D g = output.createGraphics();
            g.drawRenderedImage(in, null);
            g.dispose();
            return output;
        }I am unsure of why ImageProcessor is creating a streaky image, especially because I know the image dimensions are correct. Is there something I am missing? Does anyone see any mistakes anywhere? Does anyone have any suggestions?
    I know this is a lot of information, so thanks a lot for any help you can provide.

    Hi again,
    I'm still unsure as to what the problem is here. I thought maybe it had something to do with the GUI container, but I saved the BufferedImage to the local filesystem using ImageIO.write(), and it looks the same.
    Although no one has apparently seen any obvious problems, can someone possibly let me know if the methods are correct for what I am trying to do: convert a byte[] to a BufferedImage of RGB format?

  • Loading a raw image in BufferedImage

    Hi guys,
    I'm very new to java .I have a raw image which has 32 bit pixels which has ABGR...with alpha as the most signficant byte and the red as the least significant byte. I have an array of ints and I want to load this to a BufferedImage object. I then use a JPanel and render the BufferedImage on to it. I tried doing with other file formats like jpg , gifs and so the rendering to the JPanel works fine. But I'm not able to get the array of ints to be stored in BufferedImage correctly. Could you please let me know what I did was wrong or any suggestions?
    Currently I have a class called RGBAImage that reads the raw image and stores it as an array of ints.
    So in order to create a BufferedImage I do this roughly,
    DataBufferInt buffer = new DataBufferInt(img.getPixels() , img.getPixels().length) ;
    //                                                        bits  red                   green                   blue                 alpha
    ColorModel cm = new DirectColorModel(32, (int)0x000000ff , (int)0x0000ff00 , (int)0x00ff0000 , (int)0xff000000) ;
    SampleModel sm = cm.createCompatibleSampleModel(img.getWidth , img.getHeight) ;
    WriteableRaster raster = Raster.createWritableRaster(sm , buffer , null) ;
    BufferedImage bimg = new BufferedImage(cm , raster , false , null) ;Is this how its to be done? I am not getting the image drawn on the panel. Any suggestions or links?
    Thank you
    Siddharth

    I have an array of ints and I want to load this to a BufferedImage object.In your sample code I cannot see how the int array you are talking about becomes the image data. Also, what is the img variable? Please provide a more complete code sample.

  • How can I make a BufferedImage out of packed and non-packed int pixels?

    Hi all,
    I'm trying to turn a byte array of pixels into an int array, then into a buffered Image. In addition to the pixels, I've also got the color (and alpha) masks, width, height, and bit depth of the image. My problem is that the bits per pixel can change, the individual bytes cannot contain the pixels, and many times an int is not fully utilized to store an entire pixel (16bit pixels, for example). When I attempt to create a WritableRaster with a DataBufferInt, I get errors that I don't get if I re-package the 16bit pixels in a short[], (using DataBufferUShort). I don't want to have to do this, since it means reprocessing the entire array yet another time. One last thing. I've already got a working method for "up-converting" the int[] to 32bit pixels, though I'd love to see somebody else's attempt at this if they'd like to share. Mostly, I'm just looking for a way to use the data I have to create a BufferedImage that preserves the data type of the data. Here's some of the code I'm using now. (The byte array may contain MIPmaps, so that's the reason for the imgIndex...)
    <edit> Sorry, I also don't want to have to use the switch (or if...else) statements. I'm looking for a way to use the info I have to write one piece of code that will work for all the data types...</edit>
    private static int[] get8888(byte[] pixels, int format, int width, int height, int imgIndex) {
       int[] pixels8888 = new int[width * height / (int)Math.pow(4, imgIndex)];
       int offset = 0;
       for(int i = 0; i < imgIndex; i++) {
          offset += (width * height) / (int)Math.pow(4, i);
       switch(format) {
          case TYPE_A8R8G8B8:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = (pixels[(i + offset) * 4] & 0xff) | (pixels[(i + offset) * 4 + 1] & 0xff) << 8 | (pixels[(i + offset) * 4 + 2] & 0xff) << 16 | (pixels[(i + offset) * 4 + 3] & 0xff) << 24;
             break;
          case TYPE_A1R5G5B5:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = pixels[(i + offset) * 2] & 0xff | (pixels[(i + offset) * 2 + 1] & 0xff) << 8;
                int a = ( ( (pixels8888[i] & 0x8000) >>> 15 ) == 1 ) ? 0xFF : 0;
                int r = (pixels8888[i] & 0x7c00) >>> 7;
                int g = (pixels8888[i] & 0x3e0) >>> 2;
                int b = (pixels8888[i] & 0x1f) << 3;
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_A4R4G4B4:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = pixels[(i + offset) * 2] | (pixels[(i + offset) * 2 + 1] << 8);
                int a = (pixels8888[i] & 0xf000) >>> 12;
                int r = (pixels8888[i] & 0xf00) >>> 8;
                int g = (pixels8888[i] & 0xf0) >>> 4;
                int b = (pixels8888[i] & 0xf);
                a = a | (a << 4);
                r = r | (r << 4);
                g = g | (g << 4);
                b = b | (b << 4);
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_A8R3G3B2:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = pixels[(i + offset) * 2] | (pixels[(i + offset) * 2 + 1] << 8);
                int a = (pixels8888[i] & 0xff00) >>> 8;
                int r = (pixels8888[i] & 0xe0);
                int g = (pixels8888[i] & 0x1c) << 3;
                int b = (pixels8888[i] & 0x3) << 6;
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_R8G8B8:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = (pixels[(i + offset) * 3] & 0xff) | (pixels[(i + offset) * 3 + 1] & 0xff) << 8 | (pixels[(i + offset) * 3 + 2] & 0xff) << 16 | 0xff000000;
             break;
          case TYPE_R5G6B5:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = (pixels[(i + offset) * 2] & 0xff) | (pixels[(i + offset) * 2 + 1] & 0xff) << 8;
                int a = 0xFF;
                int r = (pixels8888[i] & 0xf800) >>> 8;
                int g = (pixels8888[i] & 0x7e0) >>> 3;
                int b = (pixels8888[i] & 0x1f) << 3;
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_R3G3B2:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = pixels[(i + offset)];
                int a = 0xFF;
                int r = (pixels8888[i] & 0xe0);
                int g = (pixels8888[i] & 0x1c) << 3;
                int b = (pixels8888[i] & 0x3) << 6;
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_X8R8G8B8:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = (pixels[(i + offset) * 4]) & 0xff | (pixels[(i + offset) * 4 + 1] & 0xff) << 8 | (pixels[(i + offset) * 4 + 2] & 0xff) << 16 | 0xff000000;
             break;
          case TYPE_X1R5G5B5:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = (pixels[(i + offset) * 2] & 0xff) | (pixels[(i + offset) * 2 + 1] & 0xff) << 8;
                int a = 0xff;
                int r = (pixels8888[i] & 0x7c00) >>> 7;
                int g = (pixels8888[i] & 0x3e0) >>> 2;
                int b = (pixels8888[i] & 0x1f) << 3;
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_X4R4G4B4:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = pixels[(i + offset) * 2] | (pixels[(i + offset) * 2 + 1] << 8);
                int r = (pixels8888[i] & 0xf00) >>> 8;
                int g = (pixels8888[i] & 0xf0) >>> 4;
                int b = (pixels8888[i] & 0xf);
                r = r | (r << 4);
                g = g | (g << 4);
                b = b | (b << 4);
                pixels8888[i] = 0xff << 24 | r << 16 | g << 8 | b;  
             break;
          default:
             System.out.println("File type not recognized");
       return pixels8888;
    }After I've done this, I can just create a DataBufferInt with the returned pixel array and generate the bufferedImage. I'm doing this currently, but I'd like to be able to write code that would take the image type and return a matching BufferedImage, (of type TYPE_USHORT_565 for example). Any hints?
    Edited by: Quasi_Stomach on Jul 31, 2009 12:33 PM

    i figured it out myself !!!

  • Thumbnail images, mysql, byte[ ]  - need some help

    I'm using the tech tip found on sun's site for "Creating Image Thumbnails" at http://java.sun.com/developer/TechTips/1999/tt1021.html#tip1
    I've looked over the code, and now I'm trying to mesh some of the code from that example with the code for my servlet program.
    My servlet takes a jpeg image submitted from an html form on a web page (all of which I'm testing on my localhost Tomcat server) and uploads it into my mysql database into a column of type BLOB. I do not upload a reference to a FILE, rather, I upload the BYTES that make up that image.
    I wanted to make the images into a thumbnail size PRIOR to uploading them into the db.
    My code snippet for my servlet that just uploads the file without modifying its size is:
    boolean isPart = FileUpload.isMultipartContent(req);
         if(isPart)
    DiskFileUpload upload = new DiskFileUpload(); // upload a file from the local disk.
    List items = upload.parseRequest(req); // Create a list of all uploaded files.
         Iterator it = items.iterator(); // Create an iterator to iterate through the list.
              while(it.hasNext())
         FileItem item = (FileItem)it.next();
         File f = new File(item1.getName()); // Create a FileItem object to access the file.
    byte[] bytes = new byte[(int)f.length()];
         FileInputStream fs = new FileInputStream(f);
         BufferedInputStream bis = new BufferedInputStream(fs);
         bis.read(bytes);
    PreparedStatement stmt = conn.prepareStatement("UPDATE car SET Image1 = ? where Account=1");
         stmt.setBytes(1, bytes);
         int i = stmt1.executeUpdate();
    Here is the code from the Tech Tip:
    import java.awt.Image;
    import java.awt.Graphics2D;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.FileOutputStream;
    import javax.swing.ImageIcon;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    class Thumbnail {
    public static void main(String[] args) {
    createThumbnail(args[0], args[
    1], Integer.parseInt(args[2]));
    * Reads an image in a file and creates
    * a thumbnail in another file.
    * @param orig The name of image file.
    * @param thumb The name of thumbnail file.
    * Will be created if necessary.
    * @param maxDim The width and height of
    * the thumbnail must
    * be maxDim pixels or less.
    public static void createThumbnail(
    String orig, String thumb, int maxDim) {
    try {
    // Get the image from a file.
    Image inImage = new ImageIcon(
    orig).getImage();
    // Determine the scale.
         double scale = (double)maxDim/(
         double)inImage.getHeight(null);
    if (inImage.getWidth(
    null) > inImage.getHeight(null)) {
    scale = (double)maxDim/(
    double)inImage.getWidth(null);
    // Determine size of new image.
    //One of them
    // should equal maxDim.
    int scaledW = (int)(
    scale*inImage.getWidth(null));
    int scaledH = (int)(
    scale*inImage.getHeight(null));
    // Create an image buffer in
    //which to paint on.
    BufferedImage outImage =
    new BufferedImage(scaledW, scaledH,
    BufferedImage.TYPE_INT_RGB);
    // Set the scale.
    AffineTransform tx =
    new AffineTransform();
    // If the image is smaller than
    //the desired image size,
    // don't bother scaling.
    if (scale < 1.0d) {
    tx.scale(scale, scale);
    // Paint image.
    Graphics2D g2d =
    outImage.createGraphics();
    g2d.drawImage(inImage, tx, null);
    g2d.dispose();
    // JPEG-encode the image
    //and write to file.
    OutputStream os =
    new FileOutputStream(thumb);
    JPEGImageEncoder encoder =
    JPEGCodec.createJPEGEncoder(os);
    encoder.encode(outImage);
    os.close();
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(0);
    I will be changing the following line right off the bat:
    1 ) changing the argument passed to:
    Image inImage = new ImageIcon(bytes);
    I'm passing it my array
    bytes
    which I created in my upload servlet, it's holding the image.
    I don't want to write the newly thumbnail sized image to a JPEG stream as it is coded at the end of the program from Sun.
    Instead, I want to read the newly sized image into a
    byte[ ]
    array and then continue with my servlet program, and place the image into the db. I have a column of type BLOB waiting for it:)
    Does anyone know how to do this?

    Yes I have done this, do not have the code to hand, its in a real mess anyway, one of those things I got working and never got round to using...
    I based my code on some found here
    http://forum.java.sun.com/thread.jspa?forumID=20&threadID=505366
    Note, the above link shows how to add a watermark to an image as well.
    It does not show how to resize it (I was originally after the watermark bit) But I got it to resize by messing with the variables used to draw out the image.
    If you search the forums you will find this a common problem, but I was very impressed with the code posted in the above link, one of my favorites!

  • Memory Efficiency of BufferedImage and ImageIO

    This thread discusses the memory efficiency of BufferedImage and ImageIO. I also like to know whether if there's possible memory leak in BufferedImage / ImageIO, or just that the result matches the specifications. Any comments are welcomed.
    My project uses a servlet to create appropriate image tiles (in PNG format) that fits the specification of google map, from images stored in a database. But it only takes a few images to make the system out of heap memory. Increasing the initial heap memory just delays the problem. So it is not acceptable.
    To understand why that happens, I write a simple code to check the memory usage of BufferedImage and ImageIO. The code simply keeps making byte arrays from the same image until it is running out of the heap memory.
    Below shows how many byte arrays it can create:
    1M jpeg picture (2560*1920):
    jpeg = 123
    png = 3
    318K png picture (1000*900):
    jpeg = 1420
    png = 178
    Notice that the program runs out of memory with only 3 PNG byte arrays for the first picture!!!! Is this normal???
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    import javax.imageio.*;
    import java.io.*;
    import javax.swing.*;
    import java.util.*;
    public class Test {
         public static void main(String[] args) {
              Collection images = new ArrayList();
              for (;;) {
                   try {
                        BufferedImage img = ImageIO.read(new File("PTHNWIDE.png"));
                        img.flush();
                        ByteArrayOutputStream out =
                             new ByteArrayOutputStream();
                        ImageIO.write(img, "png", out); // change to "jpeg" for jpeg
                        images.add(out.toByteArray());
                        out.close();
                   } catch (OutOfMemoryError ome) {
                        System.err.println(images.size());
                        throw ome;
                   } catch (Exception exc) {
                        exc.printStackTrace();
                        System.err.println(images.size());
    }

    a_silent_lamb wrote:
    1. For the testing program, I just use the default VM setting, ie. 64M memory so it can run out faster. For server, the memory would be at least 256M.You might want to increase the heap size.
    2. Do you mean it's 2560*1920*24bits when loaded? Of course.
    That's pretty (too) large for my server usage, Well you have lots of image data
    because it will need to process large dimension pictures (splitting each into set of 256*256 images). Anyway to be more efficient?Sure, use less colors :)

  • Saving a BufferedImage to disk in JPEG format

    Hi,
    How do I save a BufferedImage to disk in jpeg format. I guess I will have to use a jpeg encoder for that purpose. Where do I get free jpeg encoders ?? And using the encoders how do I write the encoded image to the disk??
    Thanks in advance.
    Regards
    Jaydeep

    I use it for saving PNG images.
    You can use similar code for JPEGs.
    ByteArrayOutputStream os=new ByteArrayOutputStream();
    PNGCodec p=new PNGCodec();
    ImageEncoder pe=p.createImageEncoder("PNG",os,null);
    BufferedImage bi=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
    bi.getGraphics().drawImage(icon.getImage(),0,0,null);
    pe.encode(bi);
    byte[] ba=os.toByteArray();
    i use JAI library for this purpose.
    best regards
    Stas

  • How to Pass a BufferedImage? Client - Server

    Please Help!
    I've been trying to figure out how to send a BufferedImage from my client program to the server program. I'm using a socket to create the connection. The client draws into a BufferedImage and then it is sent to the server to be saved as a JPG file. I've been able to create the image if I do it locally but since a BufferedImage is not serializable I can't do this the same way with the server. So how do I get my BufferedImage from the client to the server in a manner that I can then save it as a JPG on the server? Code examples would be very much appreciated!!!
    Thanks!
    Ryan

    I guess I'm not understanding what your saying. I just need a way to get what the user draws into a jpg on the server. I have been using sockets and streams but nothing I try really seems to work. Right now I am doing this:
    Client:
    Socket client = new Socket( InetAddress.getByName( "localhost" ), 5000 );
    ObjectOutputStream output = new ObjectOutputStream( client.getOutputStream() );
    ObjectInputStream input = new ObjectInputStream( client.getInputStream() );
    try {
    ByteArrayOutputStream imageOut = new ByteArrayOutputStream();
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder( imageOut );
    imageOut.flush();
    encoder.encode( sig.getImage() );
    byte[] image = imageOut.toByteArray();
    output.writeObject( image );
    Server:
    public void runServer() {
    ServerSocket server;
    Socket connection;
    try
    server = new ServerSocket( 5000, 100 );
    while ( true ) {
    connection = server.accept();
    output = new ObjectOutputStream(
    connection.getOutputStream() );
    input = new ObjectInputStream(
    connection.getInputStream() );
    ObjectOutputStream toFile = new ObjectOutputStream(
    new FileOutputStream( f ) );
    ByteArrayInputStream inStream =
    new ByteArrayInputStream( (byte[]) input.readObject() );
    JPEGImageDecoder decoder =
    JPEGCodec.createJPEGDecoder( inStream );
    BufferedImage sigImage = decoder.decodeAsBufferedImage();
    JPEGImageEncoder encoder =
    JPEGCodec.createJPEGEncoder( toFile );
    encoder.encode( sigImage );
    toFile.flush();
    output.close();
    input.close();
    connection.close();
    toFile.close();
    I imagine I have very ugly looking code here but I've been trying to make something work. My code does create the file but it is not a recognizable JPG file.
    Ryan

Maybe you are looking for