2016-06-29 39 views
1

我想從BufferedImage複製顏色到另一個bufferedImage,下面是我的代碼。 我知道我可以使用graphics.drawImage,但我需要更改某些顏色,這就是爲什麼我要逐個像素地複製顏色,而不是將圖像繪製在另一個BufferedImage上 雖然它不起作用。 「t.setRGB」行對BufferedImage「t」似乎沒有任何影響 保存圖像「t」後,我得到一個空白圖像。 我做錯了什麼?JAVA如何從一個bufferedImage複製顏色到另一個

還有一個問題。我如何修改「myColor」方法以使用「alpha」值?

import java.io.*; 
import java.awt.*; 
import java.awt.image.*; 
import javax.imageio.*; 

public class imgSt{ 

    public static int rgb; 

    public static int myColor(int r, int g, int b){ 
     rgb= (65536 * r) + (256 * g) + (b); 
     return rgb; 
    } 

    public static void main(String args[]){ 

     try { 
      BufferedImage img = ImageIO.read(new File("8.jpg")); 

      BufferedImage t= new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB); 

      int clear=0x000000FF; 
      int color, alpha, r, g, b; 

      for(int i=0; i<img.getWidth(); ++i){ 
       for(int j=0; j<img.getHeight(); ++j){ 

        color = img.getRGB(i,j); 
        alpha = (color>>24) & 0xff; 
        r = (color & 0x00ff0000) >> 16; 
        g = (color & 0x0000ff00) >> 8; 
        b = color & 0x000000ff; 

        t.setRGB(i,j, myColor(r, g, b) ); 
       } 
      } //for 

      ImageIO.write(t, "jpg", new File(" sT.jpg")); 

     } catch (IOException e){ e.printStackTrace(); } 

    }//main 
}//class 

回答

1

雖然使用其他答案中建議的柵格通常比使用getRGB()/setRGB()更快,但您的方法沒有任何根本性錯誤。

問題是getRGB()/setRGB()方法與ARGB值一起使用,而不僅僅是RGB。所以當你的myColor()方法離開alpha分量0時,這基本上意味着顏色將是100%透明的。這就是爲什麼你得到一個空白圖像。您可能需要100%不透明的像素。

這是你的方法的固定版本(我通常認爲這是清潔堅持位的變化,使轉換到/從包裝表示是相似的),創建於包裝ARGB格式不透明的顏色:

public static int myColor(int r, int g, int b) { 
    int argb = 0xFF << 24 | r << 16 | g << 8 | b; 
    return argb; 
} 

爲了便於閱讀,我也爲了可讀性而更改了拆包代碼,儘管並非嚴格必要:

int color = img.getRGB(i,j); 
int alpha = (color >>> 24) & 0xff; 
int r = (color >> 16) & 0xff; 
int g = (color >> 8) & 0xff ; 
int b = color & 0xff; 
+0

謝謝。我很抱歉這麼晚回覆。我的網絡被關閉了。你的方法起作用了,我也在保存我應該使用的文件時犯了一個錯誤:ImageIO.write(image,「jpg」,new FileOutputStream(fileOutputName))。相反,我使用新的文件(fileOutputName)。謝謝! –

0

您可以使用柵格做到這一點:

BufferedImage imsrc = ... // The source image, RGBA 
BufferedImage imres = ... // The resulting image, RGB or BGR 
WritableRaster wrsrc = imsrc.getRaster() ; 
WritableRaster wrres = imres.getRaster() ; 
for (int y=0 ; y < image.getHeight() ; y++) 
    for (int x=0 ; x < image.getWidth() ; x++) 
     { 
     wrres.setSample(x, y, 0, wrsrc.getSample(x, y, 0)) ; 
     wrres.setSample(x, y, 1, wrsrc.getSample(x, y, 1)) ; 
     wrres.setSample(x, y, 2, wrsrc.getSample(x, y, 2)) ; 
     } 

當使用光柵,你不必管理圖像編碼,信道被排序爲紅,綠,藍,α。所以我只是查看整個圖像,然後將RGB像素複製到結果中。

相關問題