我是靠谱客的博主 坚定冷风,这篇文章主要介绍java 切圆图代码(方图切圆图)背景为透明,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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(); } }

 关键代码说明:

复制代码
1
g2.setComposite(AlphaComposite.Clear);

 该段代码主要将背景色设置为透明。如果注释该代码默认背景色为白色

复制代码
1
g2.setPaint(paint)

 设置背景色

 

复制代码
1
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f));

 设置透明度!数值越大透明度越低。

 

经过测试,上面的方法虽然可以设置背景为透明。但是背景边缘是有锯齿的。网上说加入

复制代码
1
2
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

 这段代码可消除锯齿。下面的方法同样可切圆图并且能去除锯齿。

 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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; }

 

 

 注意参数

复制代码
1
cornerRadius

 表示图片四周的弧度!将弧度设置为720即可切圆图了

 

 

 

 

 

 

 

 

 

最后

以上就是坚定冷风最近收集整理的关于java 切圆图代码(方图切圆图)背景为透明的全部内容,更多相关java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(75)

评论列表共有 0 条评论

立即
投稿
返回
顶部