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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.common.BitMatrix;
import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.util.HashMap; import java.util.Map;
public class QRCodeWithLogo { public static void main(String[] args) throws Exception { String content = "hello"; int width = 300; int height = 300; String format = "png"; String logoPath = "logo.png"; double ratio = 0.2;
MultiFormatWriter writer = new MultiFormatWriter(); Map<EncodeHintType,Object> hint =new HashMap<>(); hint.put(EncodeHintType.MARGIN,2); BitMatrix matrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height,hint);
BufferedImage logoImage = ImageIO.read(new File(logoPath)); int logoWidth = logoImage.getWidth(); int logoHeight = logoImage.getHeight();
int x = (int) ((width - logoWidth * ratio) / 2); int y = (int) ((height - logoHeight * ratio) / 2); int w = (int) (logoWidth * ratio); int h = (int) (logoHeight * ratio);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics();
g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, width, height); g2d.setColor(Color.BLACK);
for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (matrix.get(i, j)) { g2d.fillRect(i, j, 1, 1); } } }
g2d.drawImage(logoImage, x, y, w, h, null);
g2d.dispose();
ImageIO.write(image, format, new File("qrcode.png")); } }
|