Java生成带圆形头像的二维码
import cn.hutool.extra.qrcode.QrCodeUtil; import cn.hutool.extra.qrcode.QrConfig; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import javax.imageio.ImageIO; import java.awt.*; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URL; public class QRCodeUtil { public static void main(String[] args) throws Exception { BufferedImage image = createLogoQrCode("https://xxxxxxxxx-h5-test.yyyyyy.com/pages/login/index?noback=true&Rcode=YYYYY&channel=3", "http://zeekrlife-oss-test.lkhaowu.com/default-avatar/7.png", 600, 600, 225, 225, 152, 152); ImageIO.write(image, "PNG", new File("\555.png")); } public static BufferedImage createLogoQrCode(String content, String logoPath, int width, int height, int x, int y, int w, int h) throws IOException { BufferedImage image = generateQrCode(content, width, height); BufferedImage QcLogoCode = insertLogoImage(image, logoPath, x, y, w, h); return QcLogoCode; } /** * 生成中间带logo的二维码 * * @param content 二维码内容 * @return */ private static BufferedImage generateQrCode(String content, int width, int height) { BufferedImage image = QrCodeUtil.generate(content, QrConfig.create() .setErrorCorrection(ErrorCorrectionLevel.L) .setWidth(width) .setHeight(height) .setMargin(0)); return image; } /** * 在二维码上画上圆形logo图标 * * @param image * @return * @throws Exception */ private static BufferedImage insertLogoImage(BufferedImage image, String logoPath, int x, int y, int w, int h) throws IOException { Image src = ImageIO.read(new URL(logoPath)); // 插入LOGO Graphics2D graph = image.createGraphics(); // 图片是一个圆型 Ellipse2D.Double shape = new Ellipse2D.Double(x, y, w, h); // 需要保留的区域 graph.setClip(shape); //留一个像素的空白区域,这个很重要,画圆的时候把这个覆盖 int border = 1; graph.drawImage(src, x, y, w - border * 2, h - border * 2, null); graph.dispose(); // 描写边框 graph = image.createGraphics(); graph.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Stroke s = new BasicStroke(5F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); graph.setStroke(s); graph.setColor(Color.WHITE); int border1 = 3; //画笔是4.5个像素,BasicStroke的使用可以查看下面的参考文档 //使画笔时基本会像外延伸一定像素,具体可以自己使用的时候测试 graph.drawOval(x + border * 2, y + border * 2, w - border1 * 2, h - border1 * 2); graph.dispose(); return image; } }
Maven依赖
<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.3</version> </dependency>
图片添加边框参考博文:
下一篇:
如何将本地项目上传到gitee