如何在Java中生成透明GIF? [英] How can I generate a transparent GIF in Java?
本文介绍了如何在Java中生成透明GIF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码生成半红半蓝的GIF图像。
如何获得半红半透明?
The code below generates a GIF image that’s half red and half blue. How can I get one that’s half red and half transparent?
我尝试过使用 IndexColorModel
构造函数,它将透明像素索引作为参数,并在调用 BufferedImage $ c $时将图像类型更改为
IMAGE_TYPE_ARGB
c>构造函数,但没有什么对我有效。
I’ve tried using the IndexColorModel
constructor that takes a transparent pixel index as a parameter, and also changing the image type to IMAGE_TYPE_ARGB
in the call to the BufferedImage
constructor, but nothing is working for me.
int pixels[] = new int[90000];
for (int x = 0; x < 300; x++) {
for (int y = 0; y < 300; y++) {
pixels[(300 * y) + x] = (x < y) ? 1 : 0;
}
}
Color oneColor = Color.red;
Color anotherColor = Color.blue;
byte[] redMap = {(byte) (oneColor.getRed()), (byte) (anotherColor.getRed())};
byte[] greenMap = {(byte) (oneColor.getGreen()), (byte) (anotherColor.getGreen())};
byte[] blueMap = {(byte) (oneColor.getBlue()), (byte) (anotherColor.getBlue())};
IndexColorModel colorModel = new IndexColorModel(1, 2, redMap, greenMap, blueMap);
MemoryImageSource mis = new MemoryImageSource(300, 300, colorModel, pixels, 0, 300);
Image image = Toolkit.getDefaultToolkit().createImage(mis);
BufferedImage bufferedImage = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
bufferedImage.getGraphics().drawImage(image, 0, 0, null);
try {
ImageIO.write(bufferedImage, "gif", new File("example.gif"));
} catch (IOException e) {
e.printStackTrace();
}
推荐答案
原来 BufferedImage.TYPE_BYTE_INDEXED
更适合这种情况。这段代码可以解决问题:
Turns out that BufferedImage.TYPE_BYTE_INDEXED
is more appropriate for this case. This code does the trick:
Color oneColor = Color.blue;
Color anotherColor = Color.red;
byte[] redMap = {(byte) (oneColor.getRed()), (byte) (anotherColor.getRed())};
byte[] greenMap = {(byte) (oneColor.getGreen()), (byte) (anotherColor.getGreen())};
byte[] blueMap = {(byte) (oneColor.getBlue()), (byte) (anotherColor.getBlue())};
IndexColorModel colorModel = new IndexColorModel(1, 2, redMap, greenMap, blueMap, 0);
int transparency = colorModel.getTransparency();
int transparentPixel = colorModel.getTransparentPixel();
System.out.println("colorModel.getTransparency(): " + transparency);
System.out.println("colorModel.getTransparentPixel(): " + transparentPixel);
BufferedImage bufferedImage = new BufferedImage(300, 300, BufferedImage.TYPE_BYTE_INDEXED, colorModel);
WritableRaster writableRaster = bufferedImage.getRaster();
for (int x = 0; x < 300; x++) {
for (int y = 0; y < 300; y++) {
int[] fill = new int[1]; // A large block...
Arrays.fill(fill, (x < y) ? 0 : 1); // .. filled with one of the 7 first colors in the LUT.
writableRaster.setSamples(x, y, 1, 1, 0, fill);
}
}
这篇关于如何在Java中生成透明GIF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文