簡體   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