BufferedImage, drawImage and ImageIO

Hey. This is kind of driving me nuts, i have been reading previous post, and do what they say but still no luck.
I have merged two images next to each other, and tried to write the BufferedImage to a file as a jpg.
All i get is a black background of the size of my BufferedImage.
Can someone please tell me what i am doing wrong?
public class Counter {
     public Counter() {
          BufferedImage dest = new BufferedImage(34, 28, BufferedImage.TYPE_INT_RGB);
          Graphics2D destG = dest.createGraphics();
          destG.drawImage(Toolkit.getDefaultToolkit().getImage("2.gif"), 0, 0, null);
          destG.drawImage(Toolkit.getDefaultToolkit().getImage("1.gif"), 17, 0, null);
          try {
               createImageFile("my_new_image.jpg", "jpg", dest);
          } catch (IOException io) {
               io.printStackTrace();
     private void createImageFile(String filename, String ext, RenderedImage image) throws IOException {
          OutputStream out = new FileOutputStream(filename);
          ImageIO.write(image, ext, out);
          out.flush();
          out.close();
     public static void main(String[] args) {
          new Counter();
Thank you anyone that answers!!!

Hi,,, thanx for the reply,,,, the gif encoder creates the new gif file that is supposed to be a combined image for the 2 bufferedimages.... I already tried ur suggestion b4 but the result was a blank image...
anyways thanks again for the response... already found a cool gif encoder :
to.mumble.GIFCodec.*;
before i used acme....
InputStream is = new BufferedInputStream(new FileInputStream(head));
InputStream is2 = new BufferedInputStream(new FileInputStream(body));
InputStream is3 = new BufferedInputStream(new FileInputStream(legs));
InputStream is4 = new BufferedInputStream(new FileInputStream(feet));
AnimGifDecoder     ade     = new AnimGifDecoder(is);     
AnimGifDecoder     ade2     = new AnimGifDecoder(is2);     
AnimGifDecoder     ade3     = new AnimGifDecoder(is3);     
AnimGifDecoder     ade4     = new AnimGifDecoder(is4);     
BufferedImage     bi     = ade.read(BufferedImage.TYPE_BYTE_INDEXED);
BufferedImage     bi2     = ade2.read(BufferedImage.TYPE_BYTE_INDEXED);
BufferedImage     bi3     = ade3.read(BufferedImage.TYPE_BYTE_INDEXED);
BufferedImage     bi4     = ade4.read(BufferedImage.TYPE_BYTE_INDEXED);
BufferedImage ima2 = new BufferedImage(200, 200, BufferedImage.TYPE_USHORT_555_RGB);
Graphics2D g = (Graphics2D) ima2.getGraphics();
//g.setColor(Color.orange);
//Font fnt = new Font("Arial", Font.BOLD, 10);
//g.setFont(fnt);
//g.drawString("TESTING", 0, 0);
g.drawImage(bi, 0, 0, null);
g.drawImage(bi2, 0,53,null);
g.drawImage(bi3, 0,99,null);
g.drawImage(bi4, 0,168,null);
g.dispose();
OutputStream     os     = new FileOutputStream(savepath);
     try
          AnimGifEncoder     age     = new AnimGifEncoder(os);
          age.add(ima2);
          age.encode();
     finally
} catch(Exception x) {}
     }

Similar Messages

  • 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 :)

  • Having a problem with drawImage() and dont know why...

    OK, I'm having some problems drawing my image onto the frame.. It will let me draw string, add components, etc.. but as soon as it come to trying to draw an image it just doesn't wanna..
    Here is my code:
    import java.awt.*;
    public class Messenger extends Frame {
         private boolean laidOut = false;
         private TextField words;
        private TextArea messages;
        private Button ip, port, nickname;
        public Messenger() {
             super();
             setLayout(null);
             //set layout font
             setFont(new Font("Helvetica", Font.PLAIN, 14));
             //set application icon
             Image icon =  Toolkit.getDefaultToolkit().getImage("data/dh002.uM");
             setIconImage((icon));
            //add components
            words = new TextField(30);
            add(words);
            messages = new TextArea("", 5, 20, TextArea.SCROLLBARS_VERTICAL_ONLY);
            add(messages);
            ip = new Button("IP Address");
            add(ip);
            port = new Button("Port");
            add(port);
            nickname = new Button("Nickname");
            add(nickname);
        public void paint(Graphics g) {
            if (!laidOut) {
                Insets insets = insets();
                //draw layout
                g.drawImage("data/dh003.uM", 0 + insets.left, 0 + insets.top);
                ip.reshape(5 + insets.left, 80 + insets.top, 100, 20);
                port.reshape(105 + insets.left, 80 + insets.top, 100, 20);
                nickname.reshape(205 + insets.left, 80 + insets.top, 100, 20);
                messages.reshape(5 + insets.left, 100 + insets.top, 485, 300);
                g.drawString("Type your message below:", 5 + insets.left, 425 + insets.top) ;
                words.reshape(5 + insets.left, 440 + insets.top, 485, 20);
                laidOut = true;
        public boolean handleEvent(Event e) {
            if (e.id == Event.WINDOW_DESTROY) {
                System.exit(0);
            return super.handleEvent(e);
        public static void main(String args[]) {
            Messenger window = new Messenger();
            Insets insets = window.insets();
              //init window..
            window.setTitle("Unrivaled Messenger");
            window.resize(500 + insets.left + insets.right,
                          500 + insets.top + insets.bottom);
            window.setBackground(SystemColor.control);
            window.show();
    }Im only new to Java, maybe I've left something out ? Any help will be much appreciated, thanks :)

    Thanks! Got the image to display now... but, next problem.. its a strange one, whenever the application is minimized or has something dragged/popup over the top of it, those sections of text/images disappear... anyone know a reason for this? im using the d.drawImage() like displayed in my code above.. this is the final code for my image..
    Image banner = null;
    try {
         banner = ImageIO.read(new File("data/dh003.uM"));
    } catch(IOException e) { }
    g.drawImage(banner,0 + insets.left, 0 + insets.top, this);and as for my text...
    g.setFont(new Font("Arial",1,14));
    g.drawString("Type your message below:", 5 + insets.left, 425 + insets.top);Thanks in advance!

  • BufferedImage 'null' with ImageIO.read(url)

    Hi,
    I am trying to display a JSP as an image which can be used in another JSP's img tags.
    Here is how I coded image.jsp.
    I observed that for 'bmp' image type, image object is 'null'. When I directly open 'bmp' image url in browser, it opens correctly.
    <%@ page import = "java.io.*" %>
    <%@ page import = "java.awt.image.BufferedImage"%>
    <%@ page import = "javax.imageio.ImageIO"%>
    <%@ page import = "javax.imageio.spi.IIORegistry"%>
    <%@ page import = "java.net.URL"%>
    <%@ page import = "java.net.URLEncoder"%>
    <%
         try{ 
              String imgUrl = URLEncoder.encode(request.getParameter("imgUrl"));
              imgUrl = imgUrl.replaceAll("%3A",":");
              imgUrl = imgUrl.replaceAll("%2F","/");     
              imgUrl = imgUrl.replaceAll("\\+","%20");     
              String[] urlSplit = imgUrl.split("\\.");          
              String imgTyp = urlSplit[urlSplit.length-1];
              URL url = new URL(imgUrl);
              BufferedImage image = null;
              image = ImageIO.read(url);
              ByteArrayOutputStream bas = new ByteArrayOutputStream();
              ImageIO.write(image,imgTyp, bas);
              byte[] imgData = bas.toByteArray();
              response.setContentType("image/"+imgTyp);
              OutputStream o = response.getOutputStream();
              o.write(imgData);
              o.flush();
              o.close();
        catch (Exception e)
           e.printStackTrace();
        finally{
    %>Any idea, why is this happening?
    With regards,
    Amey

    Hi EJP,
    Thanks for reply.
    I now changed my code to this: -
    <%@ page import = "java.io.*" %>
    <%@ page import = "java.awt.image.BufferedImage"%>
    <%@ page import = "javax.imageio.ImageIO"%>
    <%@ page import = "javax.imageio.spi.IIORegistry"%>
    <%@ page import = "java.net.URL"%>
    <%@ page import = "java.net.URLEncoder"%>
    <%@ page import = "com.sap.tc.logging.Location"%>
    <%
         Location location = Location.getLocation("AmeyTestPar.imageJSP");
         try{
              String imgUrl = request.getParameter("imgUrl");
              location.fatalT("imgUrl = " + imgUrl);
              String[] urlSplit = imgUrl.split("\\.");          
              String imgTyp = urlSplit[urlSplit.length-1];
              URL url = new URL(imgUrl);
              BufferedImage bufferedImage = ImageIO.read(url);
              OutputStream outputStream = response.getOutputStream();
              response.setContentType("image/"+imgTyp);
              ImageIO.write(bufferedImage,imgTyp, outputStream);
              outputStream.flush();
              outputStream.close();
       }catch (Exception e){  
              location.fatalT("Exception in image.jsp : " + e.getMessage());
             e.printStackTrace();
    %>But this is running into 'java.lang.IllegalArgumentException: im == null!" at
    jvax.imageio.ImageIO.write(ImageIO.java:1413)
    and
    jvax.imageio.ImageIO.write(ImageIO.java:1508)
    Also, I heard about use of image type plugins in package 'javax.imageio.plugins'.
    I added 'jai_imageio-1.1.jar' in build path and inserted 'ImageIO.scanForPlugins()' line in code.
    But this didn't help either.
    With regards,
    Amey

  • DrawImage and ImageObserver

    I'm trying to implement Servlet to render images from my local drive to Web-clients.
    I faced the strange problem I can't solve by myself.
    I'm creating BufferedImage of certain size (not very big one).
    Then I'm filling it's background and drawing the oval on it.
    After that I'm rendering the image loaded from the file by doing drawImage(img,0,0,width,height,null);
    After that I'm encoding it into JPEG and sending back to client.
    The strange thing that on clients side I see the result of filling background and drawing the oval for some of Servlet instances. I mean that if I have just one of my servlets on page or I'm calling this servlet right from Browsers address string - I see my picture. But having two servlets on page I'm getting only one of them fully rendered, other one is just showing me the oval.
    It looks like drawImage() can not complete drawing of second image because it is busy with drawing the first one.
    I tried to use ImageObserver as mentioned in may articles. It doesn't seem to make any big difference. I tried to implement ImageObserver.UpdateImage inside my Applet with checking infoflags. I tried to use instance of Frame to do this job for me. Neither of these approaches made any better to results I'm getting.
    So the question is - how is it supposed to work?
    Where is that wise article which would tell me HOW to deal with this thig properly ?
    Any ideas will be appriciated!

    I've been doing some more experiments around this issue since I started this topic.
    I've discovered that my Servlet is existing as just one SINGLE instance for all the request it processes. So far my udateImage() implemeted within Servlet has no chance to recognize which image is it called for. As result I see only the very last picture on my page (as I discribed before).
    So far my new question is - HOW to say Tomcat (or whoever is in charge of that) to instatinate new Servlet object each time it's requred ?
    Meanwhile I tried to avoid this issue by implemeting other class whic is being instantinated BY Servlet for each picture requested. First problem with it was Garbage Collector. It obviously didn't know that new instantinated object is still waiting for news from someone else being ImageObserver so Garbage Collector simply dropped it when the scope "}" created it was over.
    I scratched my head for a minute and said - "Not a problem!". I was thinking that I can actualy wait until my new object have all its job done. So I placed while(blah-blah-blah) {wait(10)} before the end of processing my request.
    Here was my next revelation!
    It appears that for just three pictures I have on my page, each one supposed to be provided by the same Servlet... for ONE of THREE request it NEVER reaches updateImage() with infoflags==ImageObserver.ALLBITS !!!
    WHY WHY WHY WHY WOULD IT BE THAT WEIRD ?!!!
    I've started to damn the moment when I first time decided to provide resized images by my own Servlet! It seemed to be so simpl to drawImage() into offscreen buffer and send it back jpeg-encoded... Now I've already constructed a THREE-PAGES-LONG PIECE-OF-SHIT-CODE with is already more complicated then windows-messages processor for regular dialog box, BUT it still doesn't flipping work!
    WHERE IS THE LIGHT IN THIS JAVA-MAD-DARKNESS ?!

  • DrawImage() and multiple classes

    First I should start by saying I am VERY new to Java. I have written a program that uses multiple classes, and i would like to place      boolean b = g.drawImage(cardPics,x2,yPos,50,75),this); in my class. I have passed Graphics g from paint. I am able to use g.drawString, etc, but when I try to drawImage, it will not even compile. I CAN use
    boolean b = g.drawImage(cardPics[i],x2,yPos,50,75),this); in paint outside of the classes, so I believe I have the image array set up right.
    This is what the compilers reads:
    cannot resolve symbol
         boolean b =g.drawImage(cardPics[i],x2,yPos,50,75),this);
    (The symbol that it is referring to is the period between g and drawImage)
    Any help is greatly appreciated.
    Thankyou
    Apryl

    Actually, I did fiigure it out. The problem was that drawImage was being handed an ImageObserver, when infact it didn't need one. But drawImage needs an imageObserver as a parameter, so instead using 'this' you replace it with null.
    Thanks for all of the help

  • Image format and ImageIO

    Hi, there,
    I have some questions as follows:
    does Java recognize only 'gif' and 'jpg' images?
    Are ImageIO APIs available and are they supposed to be able to process any type of image?
    Any help will be highly appreciated.
    Edward

    Java can read JPEG and GIF images. Startig with JDK 1.3, it can also read PNG images. Java 2D (available in JDK 1.2 or later versions) has the capability to write JPEG images. The JPEG codec is in the com.sun.image.codec.jpeg package.
    The Image IO API is available only in JDK 1.4 (currently in beta).
    The Image IO framework allows third party vendors to write coder/decoders for any image format. For this purpose, the Image IO API provides the SPI (Service Provider Interface). This framwork allows you to use codecs of your choice. I think JDK 1.4 comes with the JPEG codec, but not GIF.
    Java Advanced Imaging (JAI), which is an extension to Java, has coder/decoders for several image formats, including JPEG, GIF, BMP, and TIFF. To use JAI, you need to download it from the Sun's Java site.
    According to Sun, because the Image IO API has been developed to replace Java 2D and JAI codecs,they won't be supported in future releases.

  • ImageIO, BufferedImage and PNG

    Hello,
    I have a BufferedImage object, and I would like to copied it to the clipboard as a PNG image. What I have now is a code that copy the BufferedImage to the clipboard.
    What's the best way to convert the BufferedImage to PNG? There is ImageIO.write() but I would prefer to not create a file on the disk for this task.
    Is it possible to create file in memory? or is it possible to convert the image in memory?
    Thanks in advance for your help.

    Thanks all for your answers.
    I found one possibility : an array of byte can be converted to an Image with a call to Toolkit.getDefaultToolkit().createImage()
    So the code looks like this:
    BufferedImage img = /* some code to get the img */;
    ByteArrayOutputStream byteoutarray = new ByteArrayOutputStream();
    ImageIO.write(img, "png", byteoutarray);
    PngSelection trans = new PngSelection(byteoutarray.toByteArray());
    Clipboard clipboard = getToolkit().getSystemClipboard();
    clipboard.setContents(trans, null);where PngSelection is defined like this:
    public static class PngSelection
       implements Transferable
       private byte[] data;
       public PngSelection(byte[] data) {
         this.data = data;
       public DataFlavor[] getTransferDataFlavors()
         return new DataFlavor[] {DataFlavor.imageFlavor};
       public boolean isDataFlavorSupported(DataFlavor flavor)
         return DataFlavor.imageFlavor.equals(flavor);
       public Object getTransferData(DataFlavor flavor)
         throws UnsupportedFlavorException,IOException
         if (!DataFlavor.imageFlavor.equals(flavor))
           throw new UnsupportedFlavorException(flavor);
         return Toolkit.getDefaultToolkit().createImage(data);
      }I need to test all this but it seems to works. Thanks again.

  • Problem with ImageIO.read and ImageReader JPG colors are distorted/wrong

    (Using JDK 1.5)
    ImageIO incorrectly reads some jpg images.
    I have a jpg image that, when read by the ImageIO api, all the colors become reddish.
            try
                java.awt.image.BufferedImage bi = javax.imageio.ImageIO.read( new java.io.File("javabug.jpg") );
                javax.imageio.ImageIO.write( bi, "jpg", new java.io.File("badcolors.jpg") );
                javax.imageio.ImageIO.write( bi, "png", new java.io.File("badcolors.png") );
            catch ( java.io.IOException ioe )
                ioe.printStackTrace();
            }Why is this happening??? My guess is there is a problem with the ImageIO.read ?
    the jpg can be downloaded at http://www.alwaysvip.com/javabug.jpg
    <BufferedImage@11faace: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@1ebbfde transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 1691 height = 1269 #numDataElements 3 dataOff[0] = 2>
    I have even tried creating a new buffered image but still have the same problem:
    (suggested by http://forum.java.sun.com/thread.jspa?forumID=20&threadID=665585) "Java Forums - ImageIO: scaling and then saving to JPEG yields wrong colors"
            try
                java.awt.image.BufferedImage bi = javax.imageio.ImageIO.read( new java.io.File("javabug.jpg") );
                java.awt.image.BufferedImage out = new java.awt.image.BufferedImage( bi.getWidth(), bi.getHeight(), java.awt.image.BufferedImage.TYPE_INT_RGB );
                java.awt.Graphics2D g = out.createGraphics();
                g.drawRenderedImage(bi, null);
                g.dispose();
                javax.imageio.ImageIO.write( out, "jpg", new java.io.File("badcolors.jpg") );
            catch ( java.io.IOException ioe )
                ioe.printStackTrace();
            }I have used the following which works but does not use the ImageIO api. However, I tried using the ImageIO to write and it worked for writing which leads me to believe there is a problem with the reader.
    (suggested by http://developers.sun.com/solaris/tech_topics/java/articles/awt.html "Server-Side AWT")
            try
                java.awt.Image image = new javax.swing.ImageIcon(java.awt.Toolkit.getDefaultToolkit().getImage("javabug.jpg")).getImage();
                java.awt.image.BufferedImage bufferedImage = new java.awt.image.BufferedImage( image.getWidth( null ), image.getHeight( null ), java.awt.image.BufferedImage.TYPE_INT_RGB );
                java.awt.Graphics g = bufferedImage.createGraphics();
                g.setColor( java.awt.Color.white );
                g.fillRect( 0, 0, image.getWidth( null ), image.getHeight( null ) );
                g.drawImage( image, 0, 0, null );
                g.dispose();
                com.sun.image.codec.jpeg.JPEGImageEncoder encoder = com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder( new java.io.FileOutputStream( "goodcolors.jpg" ) );
                encoder.encode( bufferedImage );
                javax.imageio.ImageIO.write( bufferedImage, "jpg", new java.io.File("goodiocolors.jpg") );
                javax.imageio.ImageIO.write( bufferedImage, "png", new java.io.File("goodiocolors.png") );
            catch ( java.io.IOException ioe )
                ioe.printStackTrace();
            }BTW, the following does not work either:
                java.util.Iterator readers = javax.imageio.ImageIO.getImageReadersByFormatName( "jpg" );
                javax.imageio.ImageReader reader = ( javax.imageio.ImageReader ) readers.next();
                javax.imageio.stream.ImageInputStream iis = javax.imageio.ImageIO.createImageInputStream( new java.io.File("javabug.jpg") );
                reader.setInput( iis, true );
                java.awt.image.BufferedImage bufferedImage = reader.read( 0 );

    I figured out the problem. It was an actual BUG in the JDK!
    The code failed with the following JDKs:
    java version "1.5.0_01"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_01-b08)
    Java HotSpot(TM) Client VM (build 1.5.0_01-b08, mixed mode, sharing)
    java version "1.5.0_03"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_03-b07)
    Java HotSpot(TM) Client VM (build 1.5.0_03-b07, mixed mode)
    The code ran sucessful with this JDK:
    java version "1.5.0_06"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05)
    Java HotSpot(TM) Client VM (build 1.5.0_06-b05, mixed mode, sharing)
    If you are using the ImageIO classes, I highly suggest you upgrade to the latest JDK.
    Best,
    Scott

  • BufferedImage and InternetExplorer 6

    hi,
    I wrote an animation applet which uses BufferedImages to store the single slides.
    (The animation must be realized as java-applet because the images are encoded
    bit-wise and compressed on server side thus have to be decoded and inflated locally...)
    Now I had to recognize that the IE 6.0 -JVM doesn't know the BufferedImage class....
    I tried to write an own imagebuffer class but it is by far too slow. :o(
    Is it possible to make the InternetExplorer load the BufferedImage class (and linked classes)
    dynamically from the Sun-server or can I get these classes to place them on my own server?
    Or has anyone written an imagebuffer class which can be displayed by a Graphics object
    efficiently...?
    any help would be great ... (for a non-profit project), martin

    Why don't you put the BufferedImage.class in your jar file ?
    You could also ask clients to install the java plugin:
    http://java.sun.com/docs/books/tutorial/information/examples.html#plugin

  • ImageIO PNG Writing Slow With Alpha Channel

    I'm writing a project that generates images with alpha channels, which I want to save in PNG format. Currently I'm using javax.ImageIO to do this, using statements such as:
    ImageIO.write(image, "png", file);
    I'm using JDK 1.5.0_06, on Windows XP.
    The problem is that writing PNG files is very slow. It can take 9 or 10 seconds to write a 640x512 pixel image, ending up at around 300kb! I have read endless documentation and forum threads today, some of which detail similar problems. This would be an example:
    [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6215304|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6215304]
    This surely must be resolvable, but after much searching I've yet to find a solution. If it makes any difference, I ONLY want to write png image, and ONLY with an alpha channel (not ever without), in case there are optimisations that that makes possible.
    If anyone can tell me how to address this problem, I'd be very grateful.
    Many thanks, Robert Redwood.

    This isn't a solution, but rather a refinement of the issue.
    Some of the sources I was reading were implying that the long save time might be due to a CPU heavy conversion process that had to take place before the BufferedImage could be saved. I decided to investigate:
    I loaded back in one of the (slowly) saved PNG images using ImageIO.read(file). Sure enough, the BufferedImage returned differed from the BufferedImage I had created. The biggest difference was the color model, which was DirectColorModel on the image I was generating, and was ComponentColorModel on the image I was loading back in.
    So I decided to manually convert the image to be the same as how it seemed to end up anyway. I wrote the following code:
          * Takes a BufferedImage object, and if the color model is DirectColorModel,
          * converts it to be a ComponentColorModel suitable for fast PNG writing. If
          * the color model is any other color model than DirectColorModel, a
          * reference to the original image is simply returned.
          * @param source The source image.
          * @return The converted image.
         public static BufferedImage convertColorModelPNG(BufferedImage source)
              if (!(source.getColorModel() instanceof DirectColorModel))
                   return source;
              ICC_Profile newProfile = ICC_Profile.getInstance(ColorSpace.CS_sRGB);
              ICC_ColorSpace newSpace = new ICC_ColorSpace(newProfile);
              ComponentColorModel newModel = new ComponentColorModel(newSpace, true, false, ComponentColorModel.TRANSLUCENT, DataBuffer.TYPE_BYTE);
              PixelInterleavedSampleModel newSampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, source.getWidth(), source.getHeight(), 4, source.getWidth() * 4, new int[] { 0, 1, 2, 3 });
              DataBufferByte newDataBuffer = new DataBufferByte(source.getWidth() * source.getHeight() * 4);
              ByteInterleavedRaster newRaster = new ByteInterleavedRaster(newSampleModel, newDataBuffer, new Point(0, 0));
              BufferedImage dest = new BufferedImage(newModel, newRaster, false, new Hashtable());
              int[] srcData = ((DataBufferInt)source.getRaster().getDataBuffer()).getData();
              byte[] destData = newDataBuffer.getData();
              int j = 0;
              byte argb = 0;
              for (int i = 0; i < srcData.length; i++)
                   j = i * 4;
                   argb = (byte)(srcData[i] >> 24);
                   destData[j] = argb;
                   destData[j + 1] = 0;
                   destData[j + 2] = 0;
                   destData[j + 3] = 0;
              //Graphics2D g2 = dest.createGraphics();
              //g2.drawImage(source, 0, 0, null);
              //g2.dispose();
              return dest;
         }My apologies if that doesn't display correctly in the post.
    Basically, I create a BufferedImage the hard way, matching all the parameters of the image I get when I load in a PNG with alpha channel.
    The last bit, (for simplicity), just makes sure I copy over the alpha channel of old image to the new image, and assumes the color was black. This doesn't make any real speed difference.
    Now that runs lightning quick, but interestingly, see the bit I've commented out? The alternative to setting the ARGB values was to just draw the old image onto the new image. For a 640x512 image, this command (drawImage) took a whopping 36 SECONDS to complete! This may hint that the problem is to do with conversion.
    Anyhow, I got rather excited. The conversion went quickly. Here's the rub though, the image took 9 seconds to save using ImageIO.write, just the same as if I had never converted it. :(
    SOOOOOOOOOOOO... Why have I told you all this?
    Well, I guess I think it narrows dow the problem, but eliminates some solutions (to save people suggesting them).
    Bottom line, I still need to know why saving PNGs using ImageIO is so slow. Is there any other way to fix this, short of writing my own PNG writer, and indeed would THAT fix the issue?
    For the record, I have a piece of C code that does this in well under a second, so it can't JUST be a case of 'too much number-crunching'.
    I really would appreciate any help you can give on this. It's very frustrating.
    Thanks again. Robert Redwood.

  • Draw image in a indexed bufferedimage

    When i draw a image in a indexed bufferedimage the destination image is distorted. As source image i use a 256 color gif image. But when i use a TYPE_INT_RGB bufferedimage it's all good. I don't get it. Here's a is the simple code i'm using.
    Image image = new ImageIcon("E:/Java/MapEdJava/MapEditor/pics/"+ImageName).getImage());
    BufferedImage bi = new BufferedImage(image.getWidth(this),image.getHeight(this) , BufferedImage.TYPE_BYTE_INDEXED);
    Graphics2D g2d = bi.createGraphics();
    g2d.drawImage(image, 0, 0, this);

    First, a plea to all posters: if you write "why does my code do this..." either include a brief program that recreates the problem, or give the url to such code. On one hand, posting a long listing doesn't encourage assistence from the forum -- you should be motivated enough to recreate your problem "in the small". On the other hand, not posting enough information doesn't help either: for example, if a particular image is giving you grief, include its url, or find an image with a publicly-reachable url. [Getting off soapbox :-]
    Here's some quick&dirty code that, perhaps, demonstrates the poster's problem. It features a certain bald, chunky guy (no, not me!)
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class ImageTest extends JComponent {
         public static void main(String[] args) throws java.io.IOException {
              java.net.URL url = new java.net.URL(
    "http://java.sun.com/people/jag/JagWithDukeSmall.gif");
              JFrame frame = new JFrame(url.toString());
              Image image1 = new ImageIcon(url).getImage();
              BufferedImage image2 = javax.imageio.ImageIO.read(url);
              BufferedImage image3 = new BufferedImage(image2.getWidth(),image2.getHeight() ,
                   BufferedImage.TYPE_BYTE_INDEXED);
              System.out.println("image2 colormodel="+image2.getColorModel().getClass().getName());
              System.out.println("image3 colormodel="+image3.getColorModel().getClass().getName());
              Graphics2D g2 = image3.createGraphics();
              g2.drawImage(image1, 0, 0, null);
              frame.getContentPane().add(new ImageTest(image1, image2, image3));
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.show();
         Image im1, im2, im3;
         ImageTest(Image im1, Image im2, Image im3) { //assume loaded into memory
              this.im1 = im1; this.im2 = im2; this.im3 = im3;
         public Dimension getPreferredSize() {
              return new Dimension(3*im1.getWidth(null), im1.getHeight(null));
         protected void paintComponent(Graphics g) {
              g.drawImage(im1, 0, 0, null);
              g.drawImage(im2, im1.getWidth(null), 0, null);
              g.drawImage(im3, 2*im1.getWidth(null), 0, null);
    }Why is the third image grainy? I tried adjusting g2's rendering hints, specifically KEY_COLOR_RENDERING and KEY_DITHERING, but I couldn't see any difference. Perhaps the graininess is because image3 is constructed with (I assume) a generic half-tone(?) IndexColorModel. If you know your image has lots of blues, you could construct an ICM with more blue-tones and pass it to constructor:
    BufferedImage(int width, int height, int imageType, IndexColorModel cm)On the other hand, image2 has an ICM and it looks OK -- why not load images using java.imageio.ImageIO.read()?
    --Paul                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • ImageObserver, Printing, and saving as GIF

    My application has a page containing photos (images). Not all of these can be seen without paging down.
    When rendering on the screen, I use graphics.drawImage( ... ), which returns immediately and uses the ImageObserver interface to update the screen as more of the image arrives.
    When printing to paper, by some 'magic', the whole image is rendered, even if it was not previously shown on the screen. I suspect that drawImage( ) somehow waits until the whole image is available, before it returns. I may be completely wrong here.
    My problem is that I also want to save the images as GIFs. I create an off screen bufferedImage, and render them to that. The trouble is, if they have not yet been shown on screen, graphics.drawImage( ) is returning immediately, and I end up saving a GIF with no picture in it. This all takes place on a background thread.
    Does anyone know any 'magic' that I can use, to tell drawImage that it is ok to wait until the whole image arrives?

    You need to implement your own ImageObserver that will wait till it infoflags will have ALLBITS set and then draw ImageContent to BufferedImage (and print it).
    Use Toolkit.getImage() and Toolkit.preprateImage() to trigger image load.
    Some subtle things:
    1) Do not use Toolkit.createImage() because it will not use cahced copy of image and will trigger new download
    2) prepareImage may return true if image is already prepared. Then observer will be never called.
    Check for return code and call it explicitly.
    Alternatively you may simply use ImageIO to load image for printing. This is very straightforward and ImageIO has generally better support for images. However, there is no way to reuse copy of image that was loaded for display, it will always load it again.

  • Looking for a way to write a BufferedImage to a file

    i am currently working with images and transforming them. the image is stored as a BufferedImage object and i was wondering if anybody knows how to write the image back as a new file after its been modified.
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.ImageIcon;
    import javax.swing.JSlider;
    import javax.swing.event.ChangeListener;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.BorderLayout;
    import java.awt.image.BufferedImage;
    public class ExampleFramework extends JPanel {
    private BufferedImage originalImage;
    private BufferedImage filteredImage;
    private JSlider slide = new JSlider(1, 50, 25);
    private int height, width;
    ExampleFramework(String titlebar) {
    createBufferedImages();
    setUpJFrame(titlebar);
    private void createBufferedImages() {
    Image image =
    new ImageIcon("test.jpg").getImage();
    height = image.getHeight(null);
    width = image.getWidth(null);
    originalImage =
    new BufferedImage(width, height,
    BufferedImage.TYPE_INT_RGB);
    filteredImage = new BufferedImage(width, height,
    BufferedImage.TYPE_INT_RGB);
    Graphics g = originalImage.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    this class is not complete but it should give you an idea of the problem am having. there are 2 buffered images and all am looking for is a way to write the contents of the bufferedimage to a file

    First, I get rid of Image:
    private void createBufferedImages() {
        BufferedImage image = ImageIO.read(new File("test.jpg"));
        int targetType = BufferedImage.TYPE_INT_RGB;
        originalImage = convertType(image, targetType);
        filteredImage = new BufferedImage(image.getWidth(), image.getHeight(), targetType);
    static BufferedImage convertType(BufferedImage src, int targetType) {
        if (src.getType() == targetType)
            return src;
        BufferedImage tgt = new BufferedImage(src.getWidth(), src.getHeight(), targetType);
        Graphics2D g = tgt.creategraphics();
        g.drawRenderedImage(src, null);
        g.dispose();
        return tgt;
    }(I don't know how important type RGB is to you, so I put in a convert routine.
    If these images are primarily for viewing, I would make them compatible
    with the screen by using method createCompatibleImage.
    As for writing an image, it can be one line of code:
    imageIO.write(bufferedImage, "jpeg", file);See ImageIO[url].

  • How do I change the background color of a BufferedImage?

    I have a program and basically what I am doing is drawing on a BufferedImage object and then painting that BufferedImage object onto the panel. By default, the background is black and it draws in white. I am easily able to change the colour for drawing by doing g2.setColor(Color.RED) for example where g2 is the Graphics2D object created by image.createGraphics(). I tried g2.setBackground(Color.WHITE) and that did not work.
    If more information is needed, just ask.
    Any help in changing the background colour of the BufferedImage would be greatly appreciated!
    Thanks in advance!

    Here is a mini-code with comments explaining my trouble:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class TestBuff extends JPanel
        Graphics2D g2;
        BufferedImage image;
        public TestBuff()
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setSize(800,800);
            frame.add(this);
            frame.setVisible(true);
            image = new BufferedImage(800,800,BufferedImage.TYPE_INT_RGB);
            g2 = image.createGraphics();
            g2.setBackground(Color.RED); // I am setting the background colour here
        protected void paintComponent(Graphics g)
            g.drawImage(image, 0, 0, g2.getBackground(), this); // Why is this black instead of red?
        public static void main(String[] args)
            new TestBuff();
    }

Maybe you are looking for

  • Delivery schedule dates are coming in Past dates

    Hi Friends, In the Scheduling Agreements the delivery schedule dates are coming in the past dates even tough the scheduling agreements are having new schedules. There is also open quantities there for the scheduling agreements. please kindly explain

  • JFileChooser not returning files with their extensions intact?

    I have now come across a very annoying problem: when I use a JFileChooser on Mac OS X, any files whose extensions are hidden are returned without the extension at all. For example, using a JFileChooser and selecting a TIFF image at /Users/me/image.ti

  • Iphone is stuck on boot screen after new IOS6 update

    Hi everybody. I have yet, another problem. When the new IOS (6) was released, i of course recived a notification on my phone about it. It said that the new operating system was out and my phone was ready to upgrade. My situation at the time was that

  • Bought a used 4S from a business, employee has it locked???

    I bought a used 4s from a home health agency that has since switched the employees to tablets. The employee they have issued this phone to had activated the "Find My Phone" feature on this phone and has since forgotten the password for her Icloud acc

  • Zxp's will not install-Dreamweaver CC (2014.1)

    Adobe has screwed things up AGAIN. After updating to this latest piece of crap, NONE of my extensions will install. Error Message from Extension Manager CC version (7.1.1.32) : This extension cannot be installed, it requires Dreamweaver version 6 or