2016-08-24 95 views
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做一些特定的事嗎?感謝您的任何幫助,您可以提供。

+0

從迄今爲止我所做的研究看來,他們似乎做到了。我也有透明TIF的例子 – Justin

+0

嗯..爲什麼你將源頭拖到目的地兩次(並沿途創建兩個'Graphics'上下文)? – haraldK

回答

0

TIFF無法在調色板中存儲透明度信息(alpha通道)(如在您的IndexedColorModel中)。調色板僅支持RGB三元組。因此,將圖像寫入TIFF時,將顏色索引設置爲透明的事實會丟失。

如果你需要一個透明的TIFF,你的選擇是:

  • 正常使用,而不是RGBA索引顏色的(RGB,4個樣本/像素,無關聯的字母)。可能只需要使用BufferedImage.TYPE_INT_ARGBTYPE_4BYTE_ABGR。這將使輸出文件變大,但易於實現,應該更加兼容。幾乎所有的TIFF軟件都支持。
  • 用調色板圖像保存一個單獨的透明度蒙版(光度測量解釋設置爲4的1位圖像)。不知道它是否被許多軟件支持,有些人可能會將掩碼顯示爲單獨的黑白圖像。不知道如何在JAI/ImageIO中實現,可能需要編寫一個序列並設置一些額外的元數據。
  • 存儲包含透明索引的自定義字段。除了你自己的軟件以外,任何東西都不會被支持,但該文件仍然兼容,並且在其他軟件中使用白色(純色)背景進行顯示。您應該可以使用TIFF元數據進行設置。