import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; public class QRCodePainter { public static void main(String[] args) { String backgroundImageFile = "background.jpg"; String qrCodeContent = "Hello, World!"; try { // 加载背景图片 BufferedImage image = ImageIO.read(new File(backgroundImageFile)); // 创建二维码 QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(qrCodeContent, BarcodeFormat.QR_CODE, 200, 200); // 绘制二维码到图片中心 int xPos = (image.getWidth() - bitMatrix.getWidth()) / 2; int yPos = (image.getHeight() - bitMatrix.getHeight()) / 2; for (int x = 0; x < bitMatrix.getWidth(); x++) { for (int y = 0; y < bitMatrix.getHeight(); y++) { image.setRGB(xPos + x, yPos + y, bitMatrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB()); } } // 保存带有二维码的新图片 String outputFile = "output.jpg"; ImageIO.write(image, "jpg", new File(outputFile)); System.out.println("成功生成带有二维码的图片:" + outputFile); } catch (IOException | WriterException e) { e.printStackTrace(); } } }
标签:google,java,上画,image,二维码,bitMatrix,import,图片 From: https://www.cnblogs.com/wujf/p/17760178.html