如何使用java从图像中删除白色矩形

时间:2011-09-03 14:52:47

标签: java

我已经厌倦了以下代码来生成拇指指甲但是当我将它放在另一个图像上时,缩略图有一个白色矩形。如何使用java graphics 2D删除它?

  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);   

如何让这张图片透明?请有人帮助我。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

..BufferedImage.TYPE_INT_RGB

应该是:

..BufferedImage.TYPE_INT_ARGB