简体   繁体   中英

Java equivalent of JavaScript's Canvas getImageData

I'm porting a HTML5's Canvas sample to Java, so far so good, until i get on this function call :

Canvas.getContext('2d').getImageData(0, 0, 100, 100).data

I googled for a while and found this page of the canvas specification

http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#pixel-manipulation

After reading it, I created this function below :

public int[] getImageDataPort(BufferedImage image) {
    int width = image.getWidth();
    int height = image.getHeight();

    int[] ret = new int[width * height * 4];

    int idx = 0;
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            int color = image.getRGB(x, y);

            ret[idx++] = getRed(color);
            ret[idx++] = getGreen(color);
            ret[idx++] = getBlue(color);
            ret[idx++] = getAlpha(color);
        }
    }
    return ret;
}

public int getRed(int color) {
    return (color >> 16) & 0xFF;
}

public int getGreen(int color) {
    return (color >> 8) & 0xFF;
}

public int getBlue(int color) {
    return (color >> 0) & 0xFF;
}

public int getAlpha(int color) {
    return (color >> 24) & 0xff;
}

There is any class on Java Graphics API that has this function built-in or i should use the one that i had created?

I think the closest thing you'll find in the standard Java API is the Raster class. You can get hold of a WritableRaster (used for low-level image manipulation) through BufferedImage.getRaster . The Raster class then provides methods such as getSamples which fills an int[] with image data.

Thanks aioobe, i've looked at the WritableRaster class and found the getPixels function which does exactly what i needed, the final result is :

public int[] getImageDataPort(BufferedImage image) {
    int width = image.getWidth();
    int height = image.getHeight();

    int[] ret = null;

    ret = image.getRaster().getPixels(0, 0, width, height, ret);

    return ret;
}

The only problem that may happen is when the image.getType isn't a type that supports alpha in comparison with the code of the question, resulting in a smaller int[] ret , but one can simply convert the image type with :

public BufferedImage convertType(BufferedImage image,int type){
    BufferedImage ret = new BufferedImage(image.getWidth(), image.getHeight(), type);
    ColorConvertOp xformOp = new ColorConvertOp(null);
    xformOp.filter(image, ret);
    return ret;
}

Try

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", baos);

where bi - BufferendImage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM