2010-03-28 103 views
0

我的真正目标是从GIF格式的图形中读取值,转换为一些有意义的数据结构,但为了开始使用,我需要能够读取每个图像的颜色有问题的GIF像素。将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

如果您在互联网上使用图像或您的硬件驱动程序而不是一个,会发生什么情况? – 2010-03-29 09:38:42

回答

0

全黑听起来像是零,如同在拍摄还没有加载。您可能会检查grabPixels()返回的结果或指定超时。一旦你有一个BufferedImage,你可以使用getRaster()并与WritableRaster一起工作。