如何使用Java将JPEG图像读入BufferedImage对象 [英] How to Read JPEG image into BufferedImage object using Java

查看:1344
本文介绍了如何使用Java将JPEG图像读入BufferedImage对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是一个重复的问题,因为我一直在Google和StackOverflow中搜索解决方案,但仍无法找到解决方案。

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.

我有这两张图片:

这是来自同一网站的两张图片,具有相同的前缀和相同的格式。唯一的区别是大小:第一个更大,而第二个更小。

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.

我将两个图像下载到本地文件夹并使用Java将它们读入BufferedImage对象。但是,当我将BufferedImages输出到本地文件时,我发现第一张图像几乎是红色,而第二张图像是正常的(与原始图像相同)。我的代码出了什么问题?

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:我使用GIMP打开第一张图像并检测到颜色模式为'sRGB',没有alpha或其他东西。

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

推荐答案

这显然是一个知道错误,我看到了几个建议(这个是一个建议使用 Toolkit #creativeImage 相反,它显然忽略了颜色模型。

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-我用的是 JOptionPane 来验证传入的图像。当使用 ImageIO 时,它带有红色调,带有 Toolkit 它看起来很好。

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.

已更新

以及 explantation

这篇关于如何使用Java将JPEG图像读入BufferedImage对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆