java - imgscalr with background red -


i'm using (org.imgscalr.scalr) libraries resize images, when after resizing background turns red . code is:

bufferedimage imagempng = imageio.read(image); bufferedimage imagemjpg = scalr.resize(imagempng, method.quality, 1920, 937); 

can me?

thank you

the remainder of code omitted (the imageio save) , if png reading in has transparent channel or not (as @daft punk pointed out) important bits here.

i willing bet $1 png has alpha channel in , jpg not support alpha; unfortunately java's jpg encoder not know ignore alpha channel on bufferedimage pass in , discard 1 of real color channels (r/g/b) in favor of writing out alpha values instead of 1 of color channels.

for example, if have:

argb 

the java jpg encoder write out following 3 channels thinking rgb:

[arg] 

and discard blue channel.

fortunately, fix dead simple. create new bufferedimage of type type_int_rgb so:

bufferedimage imagetosave = new bufferedimage(imagemjpg.getwidth(), imagemjpg.getheight(), bufferedimage.type_int_rgb); 

then need "render" bufferedimage alpha channel it, strip alpha channel:

graphics g = imagetosave.getgraphics(); g.drawimage(imagemjpg, 0, 0, null); 

now can save out resulting imagetosave image jpg , fine.

tip: don't forget, if don't way image looks (blurry, artifacted, etc.) need pass arguments directly java jpg encoder tell not compress (read this) -- issue, has come in past when people "imgscalr looks bad!" -- turns out bufferedimage nice , sharp, java encoder aggressively compressing result.

i've been meaning address these little annoying gotcha's java images adding additional io helpers imgscalr library can load files , save them , not worry these nitty gritty details.


Comments