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:
Do you know how to handle this problem? Thanks for your help in advance :)
Paint is a built-in Windows tool that you can use it to convert a PNG image to JPEG without losing quality. , open the PNG image with Paint. Open the PNG image with Paint and navigate to File > Save as > JPEG picture. Then, choose a location, add a name, and make sure the file format is set to JPEG.
Convert in Microsoft PaintGo to File > Save as and open the Save as type drop-down menu. You can then select JPEG and PNG, as well as TIFF, GIF, HEIC, and multiple bitmap formats. Save the file to your computer and it will convert.
In seconds, you can convert your JPG images to PNG format. PNG files offer capabilities such as transparency, faded edges, and higher quality compression. Whether you need to convert small or large JPG images, our converter tool upholds the quality and provides results instantly.
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/
Try this:
BufferedImage bufferedImageUp = (BufferedImage)up;
BufferedImage old = new BufferedImage(bufferedImageUp.getWidth(), bufferedImageUp.getHeight(), bufferedImageUp.TYPE_INT_RGB);
ImageIO.write(old, "jpg", temp);
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With