public static void main(String[] args) throws IOException {
// 来源图
BufferedImage bi1 = ImageIO.read(new File("C:/Users/Administrator/Desktop/body_bg.jpg"));
// 根据需要是否使用 BufferedImage.TYPE_INT_ARGB
BufferedImage image = new BufferedImage(bi1.getWidth(), bi1.getHeight(), BufferedImage.TYPE_INT_ARGB);
Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1.getHeight());
Graphics2D g2 = image.createGraphics();
image = g2.getDeviceConfiguration().createCompatibleImage(bi1.getWidth(), bi1.getHeight(),
Transparency.TRANSLUCENT);
g2 = image.createGraphics();
// 将背景设置为透明。如果注释该段代码,默认背景为白色.也可通过g2.setPaint(paint) 设置背景色
g2.setComposite(AlphaComposite.Clear);
g2.fill(new Rectangle(image.getWidth(), image.getHeight()));
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f));
g2.setClip(shape);
// 使用 setRenderingHint 设置抗锯齿
g2.drawImage(bi1, 0, 0, null);
g2.dispose();
try {
// 输出图地址
ImageIO.write(image, "PNG", new File("C:/Users/Administrator/Desktop/4d.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
关键代码说明:
g2.setComposite(AlphaComposite.Clear);
该段代码主要将背景色设置为透明。如果注释该代码默认背景色为白色
g2.setPaint(paint)
设置背景色
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f));
设置透明度!数值越大透明度越低。
经过测试,上面的方法虽然可以设置背景为透明。但是背景边缘是有锯齿的。网上说加入
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
这段代码可消除锯齿。下面的方法同样可切圆图并且能去除锯齿。
public static boolean makeRoundedCorner(String srcImageFile, String outFilePath,Integer width,Integer height, String type, int cornerRadius) {
try {
File file = new File(srcImageFile);
BufferedImage image = ImageIO.read(file);
int w = image.getWidth();
int h = image.getHeight();
if (width != null) {
w = width;
}
if (height != null){
h = height;
}
BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = output.createGraphics();
output = g2.getDeviceConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT);
g2.dispose();
g2 = output.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.fillRoundRect(0, 0, w, h, cornerRadius, cornerRadius);
g2.setComposite(AlphaComposite.SrcIn);
g2.drawImage(image, 0, 0, w, h, null);
g2.dispose();
return ImageIO.write(output, type, new File(outFilePath));
} catch (IOException e) {
Log.error(e);
}
return false;
}
注意参数
cornerRadius
表示图片四周的弧度!将弧度设置为720即可切圆图了