![](/img/trans.png)
[英]Is there an equivalent of graphstream (Java) in HTML5 (canvas + JavaScript)
[英]Java equivalent of JavaScript's Canvas getImageData
到目前为止,我正在将HTML5的Canvas示例移植到Java,直到我开始进行此函数调用为止:
Canvas.getContext('2d').getImageData(0, 0, 100, 100).data
我搜索了一段时间,找到了画布规范的此页面
阅读后,我在下面创建了此函数:
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;
}
Java Graphics API上有任何内置此功能的类,还是我应该使用自己创建的那个类?
我认为您可以在标准Java API中找到的最接近的东西是Raster
类。 您可以通过BufferedImage.getRaster
持有WritableRaster
(用于低级图像操作)。 然后, Raster
类提供诸如getSamples
类的方法,该方法将图像数据填充到int[]
。
谢谢aioobe,我查看了WritableRaster
类,发现正是我需要的getPixels
函数,最终结果是:
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;
}
可能发生的唯一问题是,与问题代码相比, image.getType
不是支持alpha的类型,从而导致较小的int[] ret
,但可以使用以下方法简单地转换图像类型:
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;
}
尝试
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", baos);
其中bi-BufferendImage
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.