自動生成二維碼並嵌入現有背景模板,常用於海報生成、分享卡片等業務。
BufferedImage qrImage = ...; // 生成的二維碼圖片
BufferedImage bgImage = ImageIO.read(new File("背景圖片路徑")); // 讀取背景圖
Graphics2D g = bgImage.createGraphics();
// 計算二維碼在背景中的合適尺寸(不超過背景寬高的 50%)
int width = qrImage.getWidth() > bgImage.getWidth() * 5 / 10
? bgImage.getWidth() * 5 / 10 : qrImage.getWidth();
int height = qrImage.getHeight() > bgImage.getHeight() * 5 / 10
? bgImage.getHeight() * 5 / 10 : qrImage.getHeight();
// 計算居中座標
int x = (bgImage.getWidth() - width) / 2;
int y = (bgImage.getHeight() - height) / 2;
// 繪製二維碼到背景圖
g.drawImage(qrImage, x, y, width, height, null);
// 釋放資源
g.dispose();
bgImage.flush();
qrImage.flush();
// 輸出合成後的圖片
ImageIO.write(bgImage, "png", new File("輸出路徑/合成圖.png"));
dispose()、flush() 避免記憶體洩漏。利用 Java 2D API 實現二維碼與背景圖合成,核心在於 Graphics2D.drawImage() 的座標與尺寸計算,配合適當的資源管理,即可滿足大多數業務需求。