2012-04-04 119 views
0

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

+0

那么简单,没人回答?首先尝试一些你自己的努力。尝试使用Google搜索ImageIO,BufferedImade.getRgb()... – 2012-04-04 22:00:57

+0

[使用图像教程](http://docs.oracle.com/javase/tutorial/2d/images/index.html) – Jeffrey 2012-04-04 22:01:23

+1

可能的重复[如何转换Java图像转换为JPEG数组字节?](http://stackoverflow.com/questions/2568150/how-to-convert-java-image-into-jpeg-array-of-bytes) – 2012-04-04 22:03:10

回答

0

获得JPEG到Java可读对象最简单的方法如下:

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

的BufferedImage提供了用于在图像中在精确的像素位置获得的RGB值(XY整数坐标)的方法,所以它如果你想知道你想如何将它存储在一维数组中,那么你就可以决定了,但这是它的要点。

1

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

有一种方法可以将缓冲图像转换为整数数组,其中数组中的每个整数表示图像中像素的rgb值。

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

有趣的是,当整数数组中的元素被编辑时,图像中的相应像素也是如此。

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

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

即使有乘法和加法的坐标,它仍比BufferedImage类使用setRGB()方法更快。

编辑: 也请记住,图片需要的类型需要是TYPE_INT_RGB,而不是默认情况下。它可以通过创建相同尺寸的新图像以及TYPE_INT_RGB类型进行转换。然后使用新图像的图形对象将原始图像绘制到新图像上。

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