我有一個類似的問題。我有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等,並看看有什麼作用。祝你好運。