0
我正在嘗試使用Java Advanced Imaging(JAI)從BufferedImage
中編寫TIFF,但我不確定如何使其透明。以下方法可用於使PNG和GIF透明:如何使用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時,背景始終爲白色。以下是我用於編寫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
嗯..爲什麼你將源頭拖到目的地兩次(並沿途創建兩個'Graphics'上下文)? – haraldK