Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Read JPEG image into BufferedImage object using Java

Tags:

java

image

jpeg

This is not a duplicated question here, because I've been searching for the solution for a long time in Google and StackOverflow, and still cannot find a solution.

I have these two images:

Larger Image

Smaller Image

These are two images from the same website with same prefix and same format. The only difference is the size: the first is larger, while the second is smaller.

I downloaded both of the images to local folder and used Java to read them into BufferedImage objects. However, when I outputted the BufferedImages to local files, I found that the first image was almost red, while the second was normal(same as original). What's wrong with my code?

byte[] rawData = getRawBytesFromFile(imageFilePath); // some code to read raw bytes from image file
ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(rawData));
BufferedImage img = ImageIO.read(iis);
FileOutputStream fos = new FileOutputStream(outputImagePath, false);
ImageIO.write(img, "JPEG", fos);
fos.flush();
fos.close();

PS: I used GIMP to open the first image and detected that the Color Mode is 'sRGB', no alpha or other stuff.

like image 381
victorunique Avatar asked Jan 13 '23 17:01

victorunique


1 Answers

This is apparently a know bug, I saw several suggestions (this is one) that suggest using Toolkit#createImage instead, which apparently ignores the color model.

I tested this and it seems to work fine.

public class TestImageIO01 {

    public static void main(String[] args) {
        try {
            Image in = Toolkit.getDefaultToolkit().createImage("C:\\hold\\test\\13652375852388.jpg");

            JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(in)), "Yeah", JOptionPane.INFORMATION_MESSAGE);

            BufferedImage out = new BufferedImage(in.getWidth(null), in.getHeight(null), BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = out.createGraphics();
            g2d.drawImage(in, 0, 0, null);
            g2d.dispose();

            ImageIO.write(out, "jpg", new File("C:\\hold\\test\\Test01.jpg"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

nb- I used the JOptionPane to verify the incoming image. When using ImageIO it comes in with the red tinge, with Toolkit it looks fine.

Updated

And an explantation

like image 130
MadProgrammer Avatar answered Jan 31 '23 01:01

MadProgrammer