java将image图片变成圆形
时间: 2023-06-16 13:04:55 浏览: 93
可以使用Java的Graphics2D类来将图片变成圆形。
以下是示例代码:
```java
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CircleImage extends JPanel {
private BufferedImage image;
public CircleImage(BufferedImage image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int width = getWidth();
int height = getHeight();
g2d.fillOval(0, 0, width, height);
g2d.setClip(new java.awt.geom.Ellipse2D.Float(0, 0, width, height));
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
}
public static void main(String[] args) throws IOException {
BufferedImage image = ImageIO.read(new File("image.jpg"));
CircleImage panel = new CircleImage(image);
JFrame frame = new JFrame("Circle Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
```
在这个示例代码中,我们首先使用`ImageIO.read()`方法读取图片,然后创建一个继承自JPanel的类`CircleImage`,并在`paintComponent()`方法中将图片变成圆形。最后在`main()`方法中创建一个JFrame并将`CircleImage`对象添加到其中。
你可以将`CircleImage`对象用于你的应用程序中,或者通过调用`ImageIO.write()`方法将其保存为文件。
阅读全文