Hi all,
My real goal is to read the values from a graph in GIF format, into some meaningful data structure but in order to get started I need to be able to read the colour of each pixel of the GIF in question.
In order to test this i want to save the segment of the GIF i am reading to file for visual analysis, but am having trouble.
after reading this post I attempted to do something similar, however my output GIF always comes out completely black.
can anyone tell me what i've misunderstood?
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;
}