2013-04-09 64 views
4

这里没有重复的问题,因为我一直在Google和StackOverflow中搜索解决方案很长一段时间,但仍找不到解决方案。如何使用Java将JPEG图像读入BufferedImage对象

我有这两个图像:

Larger Image

Smaller Image

这些都是来自同一个网站用相同的前缀,格式相同的两个图像。唯一的区别是尺寸:第一个更大,而第二个更小。

我将这两个图像下载到本地文件夹,并使用Java将它们读入BufferedImage对象。但是,当我将BufferedImages输出到本地文件时,我发现第一张图像几乎是红色,而第二张图像是正常的(与原始图像相同)。我的代码有什么问题? PS:我用GIMP打开第一张图像并检测到色彩模式是'sRGB',没有alpha或其他东西。

+1

EMM,你选择一个漂亮的照片我喜欢你的味道:) 我不知道什么是颜色的问题,但尝试这个 'BufferedImage的IMG = ImageIO.read(new File(“path/to/image”));' – Azad 2013-04-09 06:55:26

+0

其实,我试过了,但是失败了...... – victorunique 2013-04-09 07:04:31

+0

[用红色面具创建的java缓冲图像](http:// stackoverflow.com/questions/12963685/java-buffered-image-created-with-red-mask) – haraldK 2016-05-19 09:27:34

回答

9

这显然是一个知道的错误,我看到了几个建议(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

+0

谢谢。有用。 – victorunique 2013-04-09 07:46:34

0

我检查在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; 
    } 
} 

请检查并通知我结果的;)

祝你好运

+0

感谢您的回复更重要的是,当它复制图像文件时,它确实有效。但是,您知道,我需要将图像文件读入BufferedImage对象以进行进一步处理(如旋转或缩放),所以这不是解决此问题的方法。 – victorunique 2013-04-09 07:23:07

+0

我使用Photoshop将图像格式更改为PNG,然后将png文件更改为JPEG。新的jpg文件一切正常。 [这是](http://postimg.org/image/b7y5hh9qf/)新图像。 – 2013-04-09 07:49:37

+0

是的,就像@MadProgrammer说的那样,它是ImageIO的一个bug,它无法读取某种类型的JPEG。当您使用PS将其重新保存为标准JPEG时,问题就解决了。 – victorunique 2013-04-09 07:58:56

相关问题