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?
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();
}