繁体   English   中英

Java中的图像处理

[英]Image Processing in Java

我想使用 JAVA 语言提取 jpeg 图像的像素值,并需要将其存储在 array(bufferdArray) 中以供进一步操作。 那么我如何从 jpeg 图像格式中提取像素值呢?

看看 BufferedImage.getRGB()。

这是一个精简的教学示例,说明如何拆分图像以对像素进行条件检查/修改。 根据需要添加错误/异常处理。

public static BufferedImage exampleForSO(BufferedImage image) {
BufferedImage imageIn = image;
BufferedImage imageOut = 
new BufferedImage(imageIn.getWidth(), imageIn.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
int width = imageIn.getWidth();
int height = imageIn.getHeight();
int[] imageInPixels = imageIn.getRGB(0, 0, width, height, null, 0, width);
int[] imageOutPixels = new int[imageInPixels.length];
for (int i = 0; i < imageInPixels.length; i++) {
    int inR = (imageInPixels[i] & 0x00FF0000) >> 16;
    int inG = (imageInPixels[i] & 0x0000FF00) >> 8;
    int inB = (imageInPixels[i] & 0x000000FF) >> 0;

    if (  conditionChecker_inRinGinB  ){
        // modify
    } else {
        // don't modify
    }

}
imageOut.setRGB(0, 0, width, height, imageOutPixels, 0, width);
return imageOut;
}

将 JPEG 转换为 java 可读的 object 的最简单方法如下:

BufferedImage image = ImageIO.read(new File("MyJPEG.jpg"));

BufferedImage 提供了获取图像中精确像素位置(XY integer 坐标)的 RGB 值的方法,因此您可以自行决定如何将其存储在一维数组中,但这就是它的要点.

有一种获取缓冲图像并将其转换为 integer 数组的方法,其中数组中的每个 integer 代表图像中像素的 rgb 值。

int[] pixels = ((DataBufferInt)image.getRaster().grtDataBuffer()).getData();

有趣的是,当 integer 数组中的一个元素被编辑时,图像中的相应像素也会被编辑。

为了从一组 x 和 y 坐标中找到数组中的像素,您可以使用此方法。

public void setPixel(int x, int y ,int rgb){
    pixels[y * image.getWidth() + x] = rgb;
}

即使有坐标的乘法和加法,仍然比在BufferedImage class中使用setRGB()方法要快。

编辑:还要记住,图像需要的类型需要是 TYPE_INT_RGB,默认情况下不是。 它可以通过创建具有相同尺寸且类型为 TYPE_INT_RGB 的新图像来转换。 然后用新图的图形object把原图画到新图上。

public BufferedImage toIntRGB(BufferedImage image){
    if(image.getType() == BufferedImage.TYPE_INT_RGB)
         return image;
    BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight, BufferedImage.TYPE_INT_RGB);
    newImage.getGraphics().drawImage(image, 0, 0, null);
    return newImage;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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