imgscalr with background red

时光毁灭记忆、已成空白 提交于 2019-11-29 02:11:50

The remainder of the code you omitted (the ImageIO save) and if the PNG you are reading in has a transparent channel or not (as @Daft Punk pointed out) are the important bits here.

I am willing to bet $1 that your PNG has an alpha channel in it and JPG does not support alpha; unfortunately Java's JPG encoder does not know to ignore the Alpha channel on a BufferedImage you pass in and it will discard one of the REAL color channels (R/G/B) in favor of writing out the alpha values instead of one of those color channels.

For example, if you have:

ARGB

The Java JPG encoder will write out the following 3 channels thinking they are RGB:

[ARG]

and discard the BLUE channel.

Fortunately, the fix is dead simple. Just create a new BufferedImage of type TYPE_INT_RGB like so:

BufferedImage imageToSave = new BufferedImage(imagemJpg.getWidth(), imagemJpg.getHeight(), BufferedImage.TYPE_INT_RGB);

then you need to "render" the BufferedImage with an Alpha channel to it, to strip the Alpha channel:

Graphics g = imageToSave.getGraphics();
g.drawImage(imagemJpg, 0, 0, null);

Now you can save out the resulting imageToSave image as a JPG and it will look fine.

TIP: Don't forget, if you don't like the way the image looks (blurry, artifacted, etc.) you need to pass arguments directly to the Java JPG encoder to tell it to not compress so much (read this) -- This is rarely an issue, but it has come up in the past when people say "imgscalr looks bad!" -- turns out the BufferedImage is really nice and sharp, but the Java encoder is too aggressively compressing the result.

I've been meaning to address these little annoying gotcha's with Java images by adding some additional IO helpers to the imgscalr library so you can just load files and save them and not worry about these nitty gritty details.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!