8

While converting image using

UploadedFile uf; //as a paremeter in function; PrimeFaces Object;
BufferedImage old = ImageIO.read(uf.getInputstream());
ByteArrayOutputStream temp = new ByteArrayOutputStream();
ImageIO.write(old, "jpg", temp);

white colors are changed into red..

http://www.primefaces.org/showcase/ui/file/upload/basic.xhtml

Here's the effect:

beforeafter

Do you know how to handle this problem? Thanks for your help in advance :)

Rafcik
  • 362
  • 7
  • 18

3 Answers3

9

The problem is the alpha channel in the PNG file, which doesn't exist in the JPG file. Therefore, the alpha channel is replacing one of the red/green/blue channels in the output, and the colors are wrong. You can find an example of how to do it properly here: http://www.mkyong.com/java/convert-png-to-jpeg-image-file-in-java/

uoyilmaz
  • 3,035
  • 14
  • 25
  • Will check this right now! Thanks a lot. There's also one strange thing I've just noticed - while 'converting' JPG to JPG there's same effect... This makes me confused.. – Rafcik Aug 10 '15 at 08:15
1

Try this:

BufferedImage bufferedImageUp = (BufferedImage)up;    
BufferedImage old = new BufferedImage(bufferedImageUp.getWidth(), bufferedImageUp.getHeight(), bufferedImageUp.TYPE_INT_RGB);
ImageIO.write(old, "jpg", temp);
Zaid Malhis
  • 588
  • 4
  • 18
  • 1
    this needs `old.createGraphics().drawImage(bufferedImageUp, 0, 0, Color.WHITE, null);` but thanks for help! :) – Rafcik Aug 10 '15 at 08:42
1

The keypart is to write the BufferedImage onto a new BufferedImage using an RGB channel with White background. That'll fix the issue of weird colors:

public static InputStream encodeToJpg(String filepath) throws IOException {
    System.out.println("Encoding to JPG...");
    BufferedImage buffImg;
    InputStream origStream = new FileInputStream(new File(filepath));
    buffImg = ImageIO.read(origStream);
    origStream.close();

    // Recreate the BufferedImage to fix channel issues
    BufferedImage newBuffImg = new BufferedImage(buffImg.getWidth(), buffImg.getHeight(), BufferedImage.TYPE_INT_RGB);
    newBuffImg.createGraphics().drawImage(buffImg, 0, 0, Color.WHITE, null);
    buffImg.flush();

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    ImageIO.write(newBuffImg, "jpg", outStream);

    ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
    return inStream;
}
Cardin
  • 5,148
  • 5
  • 36
  • 37