2009-06-17 113 views
10

我已經加載了一個jpg圖像,我想繪製字母和圓,給定一個x,y座標。如何通過Java編輯JPG圖像?

我一直在試圖找出ImageIcon

public void paintIcon(Component c, 
         Graphics g, 
         int x, 
         int y) 

請問這個方法讓我編輯JPG圖片的的paintIcon我想要的方式?什麼是組件c和圖形g參數?我會在它的身體上添加什麼來畫圈或字母?

我正在Netbeans 6.5上工作,我有什麼內置的任務(而不是ImageIcon)嗎?

回答

15

純Java的方法是使用ImageIOload的圖像作爲BufferedImage。然後您可以撥打createGraphics()獲取Graphics2D對象;然後你可以在圖像上繪製任何你想要的東西。

您可以使用嵌入在JLabelImageIcon做展示,你可以,如果你想允許用戶編輯圖像添加MouseListener和/或MouseMotionListenerJLabel

5

使用庫來做到這一點。一個你可能會嘗試的是JMagick

1

我imagen你可以使用這種方法覆蓋你需要的元素,每次在UI中繪製圖像時(這會發生無數次,因爲你不是在自己的圖像數據上繪製),但可能適合你的目的(並且如果覆蓋層隨時間變化則是有利的)。

喜歡的東西:

new ImageIcon("someUrl.png"){ 
    public void paintIcon(Component c, Graphics g, int x, int y) { 
     super(c, g, x, y); 
     g.translate(x, y); 

     g.drawOval(0, 0, 10, 10); 
     ... 

     g.translate(-x, -y); 
    } 
}; 

話雖如此,mmyers'答案是好多了,如果你要修改的圖像數據。

9

用Java處理圖像可以通過使用GraphicsGraphics2D上下文來實現。

可以使用ImageIO類加載圖像,如JPEG和PNG。 ImageIO.read方法需要File來讀入並返回BufferedImage,該文件可用於通過其Graphics2D(或Graphics,其超類)上下文操縱圖像。

Graphics2D上下文可用於執行許多圖像繪製和操作任務。有關信息和示例,The Java TutorialsTrail: 2D Graphics將是一個非常好的開始。

下面是一個簡化的示例(未測試的),這將打開一個JPEG文件,並得出一些圓和線(例外被忽略):

// Open a JPEG file, load into a BufferedImage. 
BufferedImage img = ImageIO.read(new File("image.jpg")); 

// Obtain the Graphics2D context associated with the BufferedImage. 
Graphics2D g = img.createGraphics(); 

// Draw on the BufferedImage via the graphics context. 
int x = 10; 
int y = 10; 
int width = 10; 
int height = 10; 
g.drawOval(x, y, width, height); 

g.drawLine(0, 0, 50, 50); 

// Clean up -- dispose the graphics context that was created. 
g.dispose(); 

上面的代碼將打開一個JPEG圖像,並且繪製一個橢圓形和一條線。一旦執行這些操作來操縱圖像,BufferedImage可以像任何其他Image一樣處理,因爲它是Image的子類。

例如,通過使用BufferedImage創建ImageIcon,一個可以嵌入圖像分割爲JButtonJLabel

JLabel l = new JLabel("Label with image", new ImageIcon(img)); 
JButton b = new JButton("Button with image", new ImageIcon(img)); 

JLabelJButton都具有其採取在ImageIcon構造,所以,可以是一個簡單的方法將圖像添加到一個Swing組件。