如何在Java中生成透明GIF?

时间:2015-02-15 02:07:14

标签: java image gif

以下代码生成半红半蓝的GIF图像。 我怎样才能得到半红半透明的东西?

我尝试使用IndexColorModel构造函数将透明像素索引作为参数,并在调用IMAGE_TYPE_ARGB构造函数时将图像类型更改为BufferedImage,但是没有什么对我有用。

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

2 个答案:

答案 0 :(得分:0)

根据我的经验,我用alpha改变了颜色的透明度。例如,透明红色看起来像这样:

Color transparentred = new Color (255, 0, 0, alpha);

也许尝试为你的redMap,blueMap,greenMap

设置alpha

答案 1 :(得分:0)

事实证明BufferedImage.TYPE_BYTE_INDEXED更适合这种情况。这段代码可以解决问题:

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