Java equivalent of JavaScript Canvas getImageData

I am porting the HTML5 Canvas sample to Java, so good until I get this function call:

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

I searched google for a while and found this canvas spec page

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

After reading this function, I created the following function:

 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; } 

Is there a class in the Java Graphics API that has a built-in function, or should I use the one I created?

+4
source share
3 answers

I think the closest you will find in the standard Java API is the Raster class. You can get WritableRaster (used for processing low-level images) through BufferedImage.getRaster . The Raster class then provides methods such as getSamples , which populates int[] with image data.

+1
source

Thanks aioobe, I looked at the WritableRaster class and found the getPixels function that does exactly what I need, the end result:

 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 arise is that image.getType not a type that supports alpha compared to the question code, which leads to a smaller int[] ret , but you 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; } 
+1
source

Try

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

where bi is BufferendImage

0
source

Source: https://habr.com/ru/post/1338844/


All Articles