Search code examples
javaimageswingjavax.imageio

Change in color while using ImageIO.read()


I am trying to read images from external directory and for that I am using

               bufferedImage image=ImageIO.read(new File(imagefile));
               jlabel.seticon(new imageicon(image));

and getting a drastic change in colors. I tried many other things like:

               bufferedImage image=ImageIO.read(new File(imagefile));
               bufferedImage img=new bufferedImage(image.getWidth(),image.getHeight(),bufferedImage.TYPE_INT_RGB);

and I tried:

               img.setData(image.getData();
               jlabel.seticon(new imageicon(image));

and I tried:

Iterator readers = ImageIO.getImageReadersByFormatName("JPEG");
ImageReader reader = null;
while(readers.hasNext()) {
    reader = (ImageReader)readers.next();
    if(reader.canReadRaster()) {
        break;  
         }
        }
ImageInputStream input =   ImageIO.createImageInputStream(f); 
reader.setInput(input); 
Raster raster = reader.readRaster(0, null); 
BufferedImage bi = new BufferedImage(raster.getWidth(), raster.getHeight(), 
BufferedImage.TYPE_4BYTE_ABGR); 
bi.getRaster().setRect(raster);

but result are still same https://i.sstatic.net/jNVm0.jpg

Here is an example of the issue:

enter image description here

The minimal code for viewing is:

      bufferedImage image=ImageIO.read(new File(imagefile));
      jlabel.seticon(new imageicon(image));      
      lbitem.setIcon(im);

and for storing

        File f = new File(s);
            long size=f.length();
            FileInputStream fis1=new FileInputStream(f);
            FileOutputStream fos2=new FileOutputStream("src/image/"+tfpn.getText()+".jpg");
            byte b[]=new byte[1000];
            int r=0;
            long count=0;
            while(true)
            {
                r=fis1.read(b,0,1000);
                fos2.write(b,0,1000);
                count = count+r;
                if(count==size)
                break;
                System.out.println(count);
            }

What could be causing the bad colors?


Solution

  • This problem is cause by a mismatch between reading/writing (creating/using) an image that contains alpha (transparency) but you are expecting it to contain no alpha (or the inverse). For example, if your image is BufferedImage.TYPE_4BYTE_ABGR and you output it to a file type that does not support alpha (transparency) , or you writer does not support alpha, it will look like your sample after reading and displaying it.

    Use type PNG (supports alpha channel) not JPG (does not support alpha channel)