Java Advanced Imaging(JAI)を使用してBufferedImage
からTIFFを書き込もうとしていますが、透過的にする方法がわかりません。JAIを使ってJavaでTIFFを透明にするには?
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 is 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);
}
TIFFを書き込むとき、背景は常に白です。次の方法は、PNGとGIFを透明にする方法です。以下は、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);
私は実際のGeoTIFFを扱ってるように私はまた後でいくつかのメタデータ操作を行います。しかし、この時点でまだ画像は白です。デバッグ中は、BufferedImage
を見ることができ、それは透明ですが、イメージを書き込むとき、ファイルは白い背景になります。 TiffImageWriteParamに固有の何かをする必要がありますか?あなたが提供できるお手伝いをありがとう。
私がこれまで行ってきた研究から、彼らはやっているようです。透明なtifの例もあります – Justin
Hmmm ..目的地へのソースを2度描くのはなぜですか(途中で2つの 'Graphics'コンテキストを作成するのですか)? – haraldK