2011-09-03 68 views
1

我厭倦了下面的代碼來生成縮略圖,但是當我將它放在另一個圖像上時,縮略圖有一個白色的矩形。我如何使用java圖形2D去除它?如何擺脫使用java的圖像中的白色矩形

Image image = javax.imageio.ImageIO.read(new File(originalFile));  
    BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); 
    Graphics2D graphics2D = thumbImage.createGraphics(); 
    graphics2D.setBackground(Color.WHITE); 
    graphics2D.setPaint(Color.WHITE); 
    graphics2D.fillRect(0, 0, thumbWidth, thumbHeight);  
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 
    graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); 
    File file = new File(thumbnailFile); 
    if(javax.imageio.ImageIO.write(thumbImage, "png", file)) 
     return file; 
    } 

即使我刪除這三條線我得到黑色的矩形。

graphics2D.setBackground(Color.WHITE); 
graphics2D.setPaint(Color.WHITE); 
graphics2D.fillRect(0, 0, thumbWidth, thumbHeight); 

如何讓此圖像爲透明?請有人幫助我。

+0

graphics2D.setBackground(新顏色(0,0,0,0)); graphics2D.setPaint(new Color(0,0,0,0)); graphics2D.fillRect(0,0,thumbWidth,thumbHeight); – Antony

+0

當我放置在另一個圖像上時,我仍然會看到白色的矩形。 – Antony

回答

2
Color transparent = new Color(0,0,0,0) 

通過設置CompositehereAlphaComposite

// Create an image that supports arbitrary levels of transparency 
Graphics2D g2d = (Graphics2D) image.getGraphics(); 
BufferedImage thumbImage = g2d.getDeviceConfiguration().createCompatibleImage(
    thumbWidth, thumbHeight, Transparency.TRANSLUCENT); 
+0

graphics2D.setBackground(new Color(0,0,0,0)); graphics2D.setPaint(new Color(0,0,0,0)); graphics2D.fillRect(0,0,thumbWidth,thumbHeight); – Antony

2
..BufferedImage.TYPE_INT_RGB 

這應該是:

..BufferedImage.TYPE_INT_ARGB 
相關問題