如何用Java将JPEG图像读入BufferedImage对象

des4xlb0  于 2022-12-28  发布在  Java
关注(0)|答案(3)|浏览(191)

这不是一个重复的问题,因为我已经在Google和StackOverflow中搜索了很长时间,仍然没有找到解决方案。
我有这两幅图:

这两张图片来自同一个网站,前缀相同,格式相同。唯一的区别是大小:第一个较大,而第二个较小。
我把两张图片都下载到本地文件夹,用Java把它们读入BufferedImage对象,但是当我把BufferedImage输出到本地文件时,我发现第一张图片几乎是红色的,而第二张是正常的(和原来一样),我的代码有什么问题吗?

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或其他东西。

r3i60tvu

r3i60tvu1#

这显然是一个已知的bug,我看到了几个建议(this是其中之一),建议使用Toolkit#createImage代替,这显然忽略了颜色模型。
我测试了这个,看起来工作正常。

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时,它看起来很好。

    • 已更新**

和一个explantation

h43kikqp

h43kikqp2#

我检查了你的代码在netbeans和面对你的问题,然后我改变了下面的代码没有问题:

public class Test {

    public static void main(String args[]) throws IOException {

        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);
        fos.write(rawData);
//        ImageIO.write(img, "JPEG", fos);
        fos.flush();
        fos.close();
    }

    private static byte[] getRawBytesFromFile(String path) throws FileNotFoundException, IOException {

        byte[] image;
        File file = new File(path);
        image = new byte[(int)file.length()];

        FileInputStream fileInputStream = new FileInputStream(file);
        fileInputStream.read(image);

        return image;
    }
}

请核对一下,并通知我结果;)
祝你好运

xxslljrj

xxslljrj3#

我怀疑这个解决方案可能在最初的海报的情况下工作得很好。

String fileName = imageFilePath;
File inFile = new File(fileName);
BufferedImage img = ImageIO.read(inFile);
...

最好的,

相关问题