2014-10-28 56 views
0

我在編輯一個BufferedImage。Java BufferedImage setRGB,getRGB錯誤

在改變圖片中的像素之後,我會進行檢查以確保新值符合我的預期。但是,他們沒有改變到指定的像素顏色

我認爲這可能與Alpha值有關,所以我最近添加了一個步驟,從原始像素中提取Alpha值,並確保在創建新顏色時使用該值以插入回到圖片。

System.out.println(newColors[0] + ", " + newColors[1] + ", " + newColors[2]); 
Color oldColor = new Color(image.getRGB(x, y)); 
Color newColor = new Color(newColors[0], newColors[1], newColors[2], oldColor.getAlpha()); // create a new color from the RGB values. 
image.setRGB(x, y, newColor.getRGB());// set the RGB of the pixel in the image. 

for (int col : getRGBs(x,y)) { 
    System.out.println(col); 
} 

getRGBs()返回一個陣列,其中

  • 索引0是紅值的方法
  • 索引1是綠色
  • 指數2爲藍色。

輸出看起來像:

206, 207, 207 
204 
203 
203 

正如你所看到的,值206, 207, 207回來出來的圖像作爲204, 203, 203 - 事實上,我每次改像素回來了作爲204, 203, 203。 我在做什麼錯?這只是沒有意義。 在此先感謝!

+0

爲什麼不使用'image.getRGB(X,Y)後''image.setRGB(X,Y,newColor.getRGB());'檢查,如果顏色是好嗎?如果他們沒問題,那麼錯誤是在'getRGBs(x,y)'裏面' – Ezequiel 2014-10-28 13:09:06

+0

發佈方法'getRGBs()'的代碼。可能是它有什麼問題。 – ortis 2014-10-28 13:13:53

+0

getRGBs()只是你說的,Ezequiel。這就是問題所在,它會返回我沒有放入圖像中的數字!謝謝。 – monster 2014-10-28 16:21:37

回答

1

我發現我自己的答案在網上,我將在下面總結一下吧:

在用的ColorModel BufferedImages像素設定爲選擇最接近的顏色。這意味着您可能無法獲得所需的顏色,因爲您可以設置的顏色僅限於ColorModel中的顏色。 您可以通過創建自己的BufferedImage並將源圖像繪製到該圖像上,然後操作這些像素來解決該問題。

BufferedImage original = ImageIO.read(new File(file.getPath())); 

    image= new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_3BYTE_BGR); 
    image.getGraphics().drawImage(original, 0, 0, null); 
    for(int y = 0; y < original.getHeight(); y++){ 
      for(int x = 0; x < original.getWidth(); x++){ 
       image.setRGB(x,y, original.getRGB(x,y)); 
      } 
    } 

這解決了這個問題。顯然,ColorModel沒有我指定的顏色,因此將像素調整爲最接近的顏色。

Source

0

我想你要找的是WritableRaster這有助於寫入圖像讀取。 使用ImageIO將最終更改寫入新文件或給出相同文件進行更改。

public class ImageTest { 

    BufferedImage image; 
    File imageFile = new File("C:\\Test\\test.bmp"); 

    public ImageTest() { 
     try { 
      image = ImageIO.read(imageFile); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    public void editImage() throws IOException { 
     WritableRaster wr = image.getRaster(); 
     int width = image.getWidth(); 
     int height = image.getHeight(); 

     for(int ii=0; ii<width; ii++) { 
      for(int jj=0; jj<height; jj++) { 
       int color = image.getRGB(ii, jj); 
       wr.setSample(ii, jj, 0 , 156); 
      } 
     } 

     ImageIO.write(image, "BMP", new File("C:\\Test\\test.bmp")); 
    } 

    public static void main(String[] args) throws IOException { 
     ImageTest test = new ImageTest(); 
     test.editImage(); 
    } 

} 
+0

雖然我還沒有嘗試過您的解決方案,但它似乎與我發佈的相似。謝謝,devilpreet。 – monster 2014-10-28 16:27:13