image - How to make a TIFF transparent in Java using JAI? -
i'm trying write tiff bufferedimage
using java advanced imaging (jai), , unsure of how make transparent. following method works making pngs , gifs transparent:
private static bufferedimage maketransparent(bufferedimage image, int x, int y) { colormodel cm = image.getcolormodel(); if (!(cm instanceof indexcolormodel)) { return image; } indexcolormodel icm = (indexcolormodel) cm; writableraster raster = image.getraster(); int pixel = raster.getsample(x, y, 0); // pixel offset in icm's palette int size = icm.getmapsize(); byte[] reds = new byte[size]; byte[] greens = new byte[size]; byte[] blues = new byte[size]; icm.getreds(reds); icm.getgreens(greens); icm.getblues(blues); indexcolormodel icm2 = new indexcolormodel(8, size, reds, greens, blues, pixel); return new bufferedimage(icm2, raster, image.isalphapremultiplied(), null); }
but when writing tiff, background white. below code used writing tiff:
bufferedimage destination = new bufferedimage(sourceimage.getwidth(), sourceimage.getheight(), bufferedimage.type_byte_indexed); graphics imagegraphics = destination.getgraphics(); imagegraphics.drawimage(sourceimage, 0, 0, backgroundcolor, null); if (istransparent) { destination = maketransparent(destination, 0, 0); } destination.creategraphics().drawimage(sourceimage, 0, 0, null); bytearrayoutputstream baos = new bytearrayoutputstream(); imageoutputstream ios = imageio.createimageoutputstream(baos); tiffimagewriter writer = new tiffimagewriter(new tiffimagewriterspi()); writer.setoutput(ios); writer.write(destination);
i metadata manipulation later i'm dealing geotiff. still images white @ point. while debugging, can view bufferedimage
, transparent, when write image, file has white background. need specific tiffimagewriteparam? can provide.
tiff has no option of storing transparency info (alpha channel) in palette (as in indexedcolormodel
). palette supports rgb triplets. thus, fact set color index transparent lost when write image tiff.
if need transparent tiff, options are:
- use normal rgba instead of indexed color (rgb, 4 samples/pixel, unassociated alpha). use
bufferedimage.type_int_argb
ortype_4byte_abgr
, probably. make output file bigger, easy implement, , should more compatible. supported tiff software. - save separate transparency mask (a 1 bit image photometric interpretation set 4) palette image. not sure if supported software, may display mask separate b/w image. not sure how can achieved in jai/
imageio
, might require writing sequence , setting metadata. - store custom field containing transparent index. not supported own software, file still compatible , displayed white (solid) background in other software. should able set using tiff metadata.
Comments
Post a Comment