将gif图像转换为像素然后再转换为gif

时间:2010-03-28 22:01:25

标签: java image-processing

我的真正目标是从GIF格式的图形中读取值到一些有意义的数据结构,但为了开始,我需要能够读取有问题的GIF的每个像素的颜色。

为了测试这个我想要保存GIF的片段,我正在阅读文件进行视觉分析,但遇到了麻烦。

在阅读this post后,我尝试做类似的事情,但是我的输出GIF总是完全变黑。

谁能告诉我我误解了什么?

BufferedImage bi = ImageIO.read(new URL("http://upload.wikimedia.org/wikipedia/commons/3/36/Sunflower_as_GIF.gif"));
int x = 100;
int y = 100;
int width = 100;
int height = 100;
int[] data = grabPixels(bi, x, y, width, height);
BufferedImage img = createImage(data, width, height);
ImageIO.write(img, "gif", new File("part.gif"));

...

private int[] grabPixels(BufferedImage img, int x, int y, int width, int height)
{
    try
    {
        PixelGrabber pg = new PixelGrabber(img, x, y, width, height, true);
        pg.grabPixels();
        if ((pg.getStatus() & ImageObserver.ABORT) != 0)
            throw new RuntimeException("image fetch aborted or errored");
        return convertPixels((int[]) pg.getPixels(), width, height);
    }
    catch (InterruptedException e)
    {
        throw new RuntimeException("interrupted waiting for pixels", e);
    }
}

public int[] convertPixels(int[] pixels, int width, int height)
{
    int[] newPix = new int[width * height * 3];
    int n = 0;
    for (int j = 0; j < height; j++)
    {
        for (int i = 0; i < width; i++)
        {
            int pixel = pixels[j * width + i];
            newPix[n++] = (pixel >> 16) & 0xff;
            newPix[n++] = (pixel >> 8) & 0xff;
            newPix[n++] = (pixel) & 0xff;
        }
    }
    return newPix;
}

private BufferedImage createImage(int[] pixels, int width, int height)
{
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    WritableRaster raster = (WritableRaster) image.getData();
    raster.setPixels(0, 0, width, height, pixels);
    return image;
}

1 个答案:

答案 0 :(得分:0)

所有黑色的声音都像零,好像图像尚未加载。您可以检查grabPixels()返回的结果或指定超时。获得BufferedImage后,您可以使用getRaster()并使用WritableRaster