2014-05-15 91 views
1

我需要创建一个BufferedImage (环型),但我可以只创建矩形式矩形一个Java编写的。然后我想创建与一些配置中的BufferedImage内部的椭圆形,最后我要绘制哪个应该在圆形形状,而不是在矩形的BufferedImage被插入的圆形内部的矩形图标。 现在我能够做到以下几点如何创建一个圆形的BufferedImage而不是创建使用图形

BufferedImage img = "SomeImage.png"; 
BufferedImage bfImage = new BufferedImage(200,200,BufferedImage.TYPE_INT_ARGB); 
Graphics2D graphics  = bfImage.createGraphics(); 
graphics.fillOval(0, 0, 200, 200); 
graphics.drawImage(img, 0, 0, null); 

(这将创建bfImage对象内部的圆形椭圆形) 现在我需要借助“IMG”,这是矩形说100 * 100大小的形状。 这个我可以使用 当我这样做时,我的最终图像正在绘制在矩形BfImage中,我不想要。我想要图像“img”在圆形椭圆中绘制,它不应该超出边界的圆形椭圆形。 总之,而不是在矩形bfImage绘制我的最终图像可以我有一个圆形bfImage上,我可以直接绘制我的图像。 使用图形在Java2D中执行此操作的任何逻辑。

回答

2

我从来没有遇到过一个矩形形式的二维数组而不是的意义上的“圆形图像”。如果你所关心的是圆圈外的像素不可见,只需将这些像素的alpha设置为0即可。一个简单的方法是首先用ARGB(0,0,0,0)填充整个矩形图像,然后绘制任何你想要的东西。

另外,不是如果你打算将这个缓冲区作为图像文件保存,你必须确保你导出/保存为支持透明的PNG或TIFF格式。

1

由于@justinzane说,你不能有一个真正的圆形图像。所有BufferedImage s将是矩形的。

但是:您可以通过使用AlphaComposite类和规则AlphaComposite.SrcIn来达到您的效果。我已经添加了一个完全运行的示例,并在下面添加了屏幕截图,compose方法是重要部分。

Screen shot, showing how a template + image = image inside template

public class AlphaCompositeTest { 
    private static BufferedImage compose(final BufferedImage source, int w, int h) { 
     BufferedImage destination = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); 
     Graphics2D graphics = destination.createGraphics(); 
     try { 
      graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
      graphics.setColor(Color.BLACK); // The color here doesn't really matter 
      graphics.fillOval(0, 0, destination.getWidth(), destination.getHeight()); 

      if (source != null) { 
       graphics.setComposite(AlphaComposite.SrcIn); // Only paint inside the oval from now on 
       graphics.drawImage(source, 0, 0, null); 
      } 
     } 
     finally { 
      graphics.dispose(); 
     } 

     return destination; 
    } 

    public static void main(String[] args) throws IOException { 
     final BufferedImage original = ImageIO.read(new File("lena.png")); 
     final BufferedImage template = compose(null, original.getWidth(), original.getHeight()); 
     final BufferedImage composed = compose(original, original.getWidth(), original.getHeight()); 

     SwingUtilities.invokeLater(new Runnable() { 
      @Override public void run() { 
       JFrame frame = new JFrame(); 
       frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 

       JPanel panel = new JPanel(new BorderLayout(10, 10)); 
       panel.add(new JLabel("+", new ImageIcon(template), SwingConstants.LEFT), BorderLayout.WEST); 
       panel.add(new JLabel("=", new ImageIcon(original), SwingConstants.LEFT), BorderLayout.CENTER); 
       panel.add(new JLabel(new ImageIcon(composed)), BorderLayout.EAST); 

       frame.add(new JScrollPane(panel)); 

       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 
} 

见例如the Compositing tutorial更多的信息和例子。