开发者

Image resize in Java breaks on some JPGs

开发者 https://www.devze.com 2023-01-24 04:58 出处:网络
I\'m using the code below to resize images and store them on the server. However, with some JPGs, the resize produces a reddish tint on the image. Any ideas what could be causing this? Here\'s the ori

I'm using the code below to resize images and store them on the server. However, with some JPGs, the resize produces a reddish tint on the image. Any ideas what could be causing this? Here's the original image: http://www.unctv.org/tWxkBbq_10M6wKRRL/PNCWWD01.jpg and here's what it produces afterward: http://www.unctv.org/tWxkBbq_10M6wKRRL/PABDFC01__1289231445291.jpg

Photoshop CS5 on the Mac is used to produce the JPG input for this app. Thanks.

public BufferedImage resizeVeryHigh(InputStream inputStream, File resizedFile) throws IOException {
  BufferedImage bufferedImage = null;
  try {
      Image newImage = ImageIO.read(inputStream);
      int newWidth = (int)this.targetWidth;
      ImageIcon imageIcon = new ImageIcon(newImage);
      Image image = imageIcon.getImage();
      Image resizedImage = null;

      int iWidth = image.getWidth(null);
      int iHeight = image.getHeight(null);

      // This code ensures that all the pixels in the image are loaded.
      Image temp = new ImageIcon(resizedImage).getImage();

      // Create the buffered image.
      bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_RGB);

      // Copy image to buffered image.
      Graphics g = bufferedImage.createGraphics();

      // Clear background and paint the image.
      g.setColor(Color.white);
      g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
      g.drawImage(temp, 0, 0, null);
      g.dispose();

      // Encodes image as a JPEG data stream
      FileOutputStream out = new FileOutputStream(resizedFile);
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
      JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(buf开发者_StackOverflow社区feredImage);
      param.setQuality(1.0f, true);
      encoder.setJPEGEncodeParam(param);
      encoder.encode(bufferedImage);
  }
  catch (Exception e) {
        this.error = e.getMessage();
  }
      return bufferedImage;
}


Your original image appears to be a normal RGB image. As the image is opaque, I'm sure what setColor() and fillRect() add, but they are not the problem. The reddish cast suggests an incorrectly initialized ARGB buffer or an incorrectly chosen graphics composite mode. You might try one of the ImageIO.write() methods to see if your JPEGImageEncoder is at fault.


Believe it or not, the issue had to do with the progressive setting in the Save for Web & Devices in Photoshop. Once I toggled that on, the file was processed fine by the Java app. Why, I don't know. Maybe someone can shed some light on this.

0

精彩评论

暂无评论...
验证码 换一张
取 消