Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue using ImageIO.write jpg file: pink background [closed]

I'm using the following code to write a jpg file:

String url="http://img01.taobaocdn.com/imgextra/i1/449400070/T2hbVwXj0XXXXXXXXX_!!449400070.jpg"; String to="D:/temp/result.jpg"; ImageIO.write(ImageIO.read(new URL(url)),"jpg", new File(to)); 

But I get the result.jpg is a pink background image:

alt text

like image 455
Koerr Avatar asked Dec 08 '10 10:12

Koerr


People also ask

Can ImageIO read JPG?

imageio package. Image I/O has built-in support for GIF, PNG, JPEG, BMP, and WBMP. Image I/O is also extensible so that developers or administrators can "plug-in" support for additional formats. For example, plug-ins for TIFF and JPEG 2000 are separately available.

What does ImageIO write do?

The ImageIO. write method calls the code that implements PNG writing a “PNG writer plug-in”. The term plug-in is used since Image I/O is extensible and can support a wide range of formats.


2 Answers

I had similar problems. But then I solved it by using this one

   BufferedImage image = new BufferedImage(width, height,             BufferedImage.TYPE_INT_RGB);      //do something to populate the image    //such as    image.setRGB( x, y, pixelValue); //set your own pixels color       ImageIO.write(image, "jpg", new File("D:\\test.jpg")); 

Note that I'm using Java version 1.6.0_25-b06 and It's just works fine.

Maybe you can check the Java version.

like image 24
Ali Irawan Avatar answered Sep 28 '22 17:09

Ali Irawan


You can work around this by using Toolkit.createImage(url) instead of ImageIO.read(url) which uses a different implementation of the decoding algorithm.

If you are using the JPEG encoder included with the Sun JDK then you must also ensure that you pass it an image with no alpha channel.

Example:

private static final int[] RGB_MASKS = {0xFF0000, 0xFF00, 0xFF}; private static final ColorModel RGB_OPAQUE =     new DirectColorModel(32, RGB_MASKS[0], RGB_MASKS[1], RGB_MASKS[2]);      // ...  String sUrl="http://img01.taobaocdn.com/imgextra/i1/449400070/T2hbVwXj0XXXXXXXXX_!!449400070.jpg"; URL url = new URL(sUrl); Image img = Toolkit.getDefaultToolkit().createImage(url);  PixelGrabber pg = new PixelGrabber(img, 0, 0, -1, -1, true); pg.grabPixels(); int width = pg.getWidth(), height = pg.getHeight();  DataBuffer buffer = new DataBufferInt((int[]) pg.getPixels(), pg.getWidth() * pg.getHeight()); WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, RGB_MASKS, null); BufferedImage bi = new BufferedImage(RGB_OPAQUE, raster, false, null);  String to = "D:/temp/result.jpg"; ImageIO.write(bi, "jpg", new File(to)); 

Note: My guess is that the color profile is corrupted, and Toolkit.createImage() ignores all color profiles. If so then this will reduce the quality of JPEGs that have a correct color profile.

like image 178
finnw Avatar answered Sep 28 '22 17:09

finnw