2014-12-04 87 views
1

我正在拍攝一幅圖像並畫上一個矩形,但問題是,對於某些圖像,矩形顏色很好,但其他顏色會發生變化。如何解決這樣的行爲Graphics2D setColor出現奇怪的顏色行爲

這是我的代碼

public class Index { 
static int[][] coordenadas = new int[1][4]; 
public static void main(String[] args) throws IOException { 

    coordenadas[0][0]=530; 
    coordenadas[0][1]=237; 
    coordenadas[0][2]=86; 
    coordenadas[0][3]=17; 
    //File file = new File("C:\\Users\\Juan\\Desktop\\2.jpg"); 
    File file = new File("C:\\Users\\Juan\\Desktop\\1.jpg"); 
    paint(file); 
} 

public static void paint(File file) throws IOException{ 
    BufferedImage img = ImageIO.read(file); 
    Graphics2D g = img.createGraphics();  
    g.setColor(Color.yellow);    
    //g.drawRect(coordenadas[0][0], coordenadas[0][2], coordenadas[0][2], coordenadas[0][3]);   
    g.fillRect(coordenadas[0][0], coordenadas[0][3], coordenadas[0][2], coordenadas[0][3]); 



    g.dispose(); 

    ImageIO.write(img,"jpg", new File("C:\\Users\\Juan\\Desktop\\outcome.jpg")); 
} 
} 

這是2個型動物輸出

撥錯輸出

Worng output

分辯輸出

的一個例子

Rigth output

這些是原始圖像

http://imageshack.com/a/img661/1940/bqwmPL.jpg

http://imageshack.com/a/img903/1447/vDwVtf.jpg

預先感謝您的時間和aswers

+0

犯了一些錯誤(一切都在甲骨文教程的Graphics2D)1.永遠載入圖像也不文件中密集的油漆,2使用的paintComponent或的paintIcon在這種情況下更好地和3 coordenadas應rellative不harcoded值 – mKorbel 2014-12-04 12:12:27

+0

嗨mr @mKorbel感謝您的評論,coordenadas是相對的,我剛剛在這裏發佈了硬編碼值,以顯示目的。關於paintComponent或paintIcon的用法我不明白如何在我的目標中使用,你有任何建議如何從磁盤加載圖像。我使用這種方法https://docs.oracle.com/javase/tutorial/2d/images/loadimage.html在此先感謝。 – 2014-12-04 12:30:48

回答

0

繼@mrKobel從來就的對策的探討改變了鏈接加載圖像,從文件到ImageIcon,以及所有作品。這是新的代碼。

public class Index { 

static int[][] coordenadas = new int[1][4]; 
static BufferedImage bi ; 
public static void main(String[] args) throws IOException { 

    coordenadas[0][0]=530; 
    coordenadas[0][1]=237; 
    coordenadas[0][2]=86; 
    coordenadas[0][3]=17; 
    ImageIcon img = new ImageIcon("C:\\Users\\Juan\\Desktop\\2.jpg");  
    BufferedImage image = new BufferedImage(img.getIconWidth(), img.getIconHeight(), BufferedImage.TYPE_INT_RGB); 
    Graphics2D g2d = (Graphics2D)image.getGraphics(); 
    img.paintIcon(null, g2d, 0, 0); 
    Color color = new Color(255,255,0,100); 
    g2d.setColor(color);    
    g2d.fillRect(coordenadas[0][0], coordenadas[0][1], coordenadas[0][2], coordenadas[0][3]);  
    ImageIO.write(image,"jpg", new File("C:\\Users\\Juan\\Desktop\\outcome.jpg")); 


} 


}