I am trying to adjust the contrast of a BufferedImage
using RescaleOp
. Changing the contrast of an image without alpha channel works fine, but for images with an alpha channel it creates a yellow tint; what am I doing wrong?
To verify that the issue arises because of the alpha channel I loaded the original file into Gimp, added an alpha channel and then exported the file to another png image, which yielded the second image I try to change the contrast of.
public class Test
{
public static void main(String[] args) throws IOException
{
changeContrast(new File("contrast/base_image_without_alpha.png"),
new File("contrast/output_without_alpha.png"));
changeContrast(new File("contrast/base_image_with_alpha.png"),
new File("contrast/output_with_alpha.png"));
}
private static void changeContrast(File sourceImageFile, File targetImageFile) throws IOException
{
BufferedImage image = ImageIO.read(sourceImageFile);
RescaleOp rescaleOp = new RescaleOp(1.8f, 0, null);
rescaleOp.filter(image, image);
ImageIO.write(image, "png", targetImageFile);
}
}
images to try for yourself: http://www.mediafire.com/file/15r1zh27ccjj1w1/contrast.zip
MCVE to try it out for yourself (easily)
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import java.net.*;
public class TestAlphaRescale {
public static void main(String[] args) throws Exception {
File f = new File("output_without_alpha.png");
URL url = new URL("https://i.stack.imgur.com/S3m9W.jpg");
Desktop desktop = Desktop.getDesktop();
changeContrast(url,f);
desktop.open(f);
desktop.browse(url.toURI());
f = new File("output_with_alpha.png");
// with alpha
url = new URL("https://i.stack.imgur.com/memI0.png");
changeContrast(url,f);
desktop.open(f);
desktop.browse(url.toURI());
}
private static void changeContrast(URL sourceImageURL, File targetImageFile) throws IOException {
BufferedImage image = ImageIO.read(sourceImageURL);
RescaleOp rescaleOp = new RescaleOp(1.8f, 0, null);
rescaleOp.filter(image, image);
ImageIO.write(image, "png", targetImageFile);
}
}