Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

java - imgscalr with background red

I'm using (org.imgscalr.Scalr) libraries to resize some images, but when after resizing the background turns red . My code is:

BufferedImage imagemPng = ImageIO.read(image);
BufferedImage imagemJpg = Scalr.resize(imagemPng, Method.QUALITY, 1920, 937);

can you help me?

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...