2014-01-28 136 views
0

前言:我試圖將swt ImageData保存爲gif文件,但它拋出「不支持的顏色深度」。我決定將org.eclipse.swt.graphics.ImageData轉換爲java.awt.image.BufferedImage,它工作正常,直到我開始使用透明度。使用ImageIO寫入功能在GIF文件中透明的問題

問題:透明像素沒有正確處理,而是使用繪製GC時使用的最後前景色進行着色。我注意到這種不希望的效果是在我的代碼中的這一行。

ImageIO.write(bufferedImage, "gif", file); 

做一些網絡搜索後,我發現該問題在JDK 7 http://ubuntuforums.org/archive/index.php/t-1060128.html

的問題是我必須使用Java 6不7.任何人都可以請你告訴我這可怎麼解決實現?

回答

0

我有一個類似的問題。我有ImageData,我試圖用透明度寫入GIF或PNG。我使用了下面的轉換函數,它對我很有用。

static BufferedImage convertToAWT(ImageData data) { 
    ColorModel colorModel = null; 
    PaletteData palette = data.palette; 
    if (palette.isDirect) { 
     int alphaMask = 0xff; 
     colorModel = new DirectColorModel(data.depth, palette.redMask, palette.greenMask, palette.blueMask, alphaMask); 

     BufferedImage bufferedImage = new BufferedImage(colorModel, colorModel.createCompatibleWritableRaster(data.width, data.height), false, null); 
     for (int y = 0; y < data.height; y++) { 
      for (int x = 0; x < data.width; x++) { 
       int pixel = data.getPixel(x, y); 
       RGB rgb = palette.getRGB(pixel); 

       // ASSUME that pixel==0 is transparent!!!! 

       int alpha = (pixel == 0) ? 0 : alphaMask; 

       bufferedImage.setRGB(x, y, alpha << 24 | rgb.red << 16 | rgb.green << 8 | rgb.blue); 
      } 
     } 
     return bufferedImage; 
    } else { 
     return null; // not supported 
    } 
} 


private static void writeToFile(Image img, String name) 
{ 
    BufferedImage ii = convertToAWT(img.getImageData()); 

    try 
    { 
     // You can change this to write GIF or JPG also 

     ImageIO.write(ii, "PNG", new File(name + ".png")); 
    } 
    catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 
}   

請注意,這假設像素零是透明的。這可能不適合你。也許你可以嘗試其他值,如-1或255等,並看看有什麼作用。祝你好運。