Getting pixel data from an image using java

前端 未结 6 1141
眼角桃花
眼角桃花 2020-12-02 14:11

I\'m trying to get the pixel rgb values from a 64 x 48 bit image. I get some values but nowhere near the 3072 (= 64 x 48) values that I\'m expectin

6条回答
  •  半阙折子戏
    2020-12-02 14:29

    I was looking for this same ability. Didn't want to enumerate the entire image, so I did some searching and used PixelGrabber.

    Image img = Toolkit.getDefaultToolkit().createImage(filename);
    PixelGrabber pg = new PixelGrabber(img, 0, 0, -1, -1, false);
    
    pg.grabPixels(); // Throws InterruptedException
    
    width = pg.getWidth();
    height = pg.getHeight();
    
    int[] pixels = (int[])pg.getPixels();
    

    You could use the int[] directly here, pixels are in a format dictated by the ColorModel from pg.getColorModel(), or you can change that false to true and force it to be RGB8-in-ints.

    I've since discovered that the Raster and Image classes can do this too, and there have been some useful classes added in javax.imageio.*.

    BufferedImage img = ImageIO.read(new File(filename)); // Throws IOException
    int[] pixels = img.getRGB(0,0, img.getWidth(), img.getHeight, null, 0, img.getWidth());
    
    // also available through the BufferedImage's Raster, in multiple formats.
    Raster r = img.getData();
    int[] pixels = r.getPixels(0,0,r.getWidth(), r.getHeight(), (int[])null);
    

    There are several getPixels(...) methods in Raster as well.

提交回复
热议问题