最近項目中有一個需求,要將一個URL鏈接轉成二維碼,併合成到一個固定的背景圖片上的指定位置。其實將二維碼合成到圖片上還是將圖片合成到二維碼上,都是同一個道理。
需要採用google提供的 core-3.1.0.jar 包(點擊下載)來將URL轉化成二維碼圖片。
以下是將URL轉化成二維碼圖片的代碼:
/**
* 二維碼圖片的生成
* @param content 鏈接
* @param qrcode_width 二維碼寬
* @param qrcode_height 二維碼高
* @return
* @throws Exception
*/
public static BufferedImage createImage(String content, int qrcode_width, int qrcode_height) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, qrcode_width, qrcode_height, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
: 0xFFFFFFFF);
}
}
return image;
}
以下是合成圖片的代碼:
/**
* 合成圖片
* @param url 二維碼鏈接
* @param path 背景圖片地址
* @param startX 二維碼在背景圖片的X軸位置
* @param startY 二維碼在背景圖片的Y軸位置
* @param codeWidth 二維碼寬度
* @param codeHeight 二維碼高度
* @return 合成的圖片
*/
public static BufferedImage compositeImage(String url, String path, int startX, int startY, int codeWidth, int codeHeight) {
try {
BufferedImage headImage = createImage(url, null, codeWidth, codeHeight, true);
String backBIS64 = "";
Image backImage = null;
FileInputStream fileInputStream = new FileInputStream(path);
backBIS64 = ImageUtil.GetImageStr(fileInputStream);
// 讀取背景圖片
InputStream in = new ByteArrayInputStream(ImageUtil.GenerateImage(backBIS64));
backImage = ImageIO.read(in);
int alphaType = BufferedImage.TYPE_INT_RGB;
if (ImageUtil.hasAlpha(backImage)) {
alphaType = BufferedImage.TYPE_INT_ARGB;
}
BufferedImage back = new BufferedImage(backImage.getWidth(null), backImage.getHeight(null), alphaType);
// 畫圖
Graphics2D g = back.createGraphics();
g.drawImage(backImage, 0, 0, null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1));
g.drawImage(headImage, startX, backImage.getHeight(null) - startY, headImage.getWidth(null), headImage.getHeight(null), null);
g.dispose();
return back;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}