JAVA生成的二维码以及给二维码添加背景图片
JAVA生成的二維碼以及給二維碼添加背景圖片**
1.頁面只需一行代碼即可(用ajax請求得不到響應,也可以用表單提交)
window.location.href = “${ctx}/qrcode/getQrcodes?id=”+id
2.后臺代碼
public void getQrcode(String id,HttpServletResponse
httpServletResponse){
InputStream imagein = null;
try {
String[] idStr=ids.split(",");
httpServletResponse.setContentType(“application/zip”);
httpServletResponse.addHeader(“Content-Disposition”,
“attachment;filename=”
+ URLEncoder.encode(“二維碼.zip”, “utf-8”));
OutputStream outputStream = httpServletResponse.getOutputStream(); ZipOutputStream
zipOutputStream = new ZipOutputStream(outputStream);
String text = “”; // 二維碼內容PPNkkUNC4DNCQuDuOv
//String pressText = “商戶編號:”+merchant.getMerNo();//向享圖片中添加文字
int width = 330; // 二維碼圖片寬度
int height =330; // 二維碼圖片高度
String format = “png”;// 二維碼的圖片格式
//int fontStyle = 0; //字體風格
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, “utf-8”); // 內容所使用字符集編碼
BitMatrix bitMatrix = new MultiFormatWriter().encode(text,BarcodeFormat.QR_CODE, width, height,
hints);
//生成的二維碼
BufferedImage buffImg = MatrixToImageWriter.toBufferedImage(bitMatrix);
/Graphics gs = buffImg.createGraphics();
//設置畫筆的顏色
gs.setColor(Color.black);
//設置字體
Font font = new Font(“宋體”, fontStyle, 12);
FontMetrics metrics = gs.getFontMetrics(font);
//文字在圖片中的坐標 這里設置在中間
int startX = (width - metrics.stringWidth(pressText))/2 ;
int startY = height-300;
gs.setFont(font);
gs.drawString(pressText, startX, startY);/
//背景圖片的路徑
File logoFile = new File(QrcodeService.class.getClassLoader().getResource(“backgroundPicture.png”).getFile());
imagein = new FileInputStream(logoFile.toString());
//讀出背景圖片
BufferedImage image = ImageIO.read(imagein);
Graphics g = image.getGraphics();
//將二維碼畫到背景圖片中
g.drawImage(buffImg, 85, 100,buffImg.getWidth(), buffImg.getHeight(), null);
// 生成二維碼
ZipEntry entry=null;
entry = new ZipEntry(“圖片名字”+".png");
zipOutputStream.putNextEntry(entry);
ImageIO.write(image, format, zipOutputStream);
zipOutputStream.flush();
zipOutputStream.close();
outputStream.flush();
outputStream.close();
System.out.println(“完成二維碼生成”);
} catch(Exception e) {
e.printStackTrace();
throw new RuntimeException(“打包二維碼異常”);
}
}
3.pom文件
4.本人親測可用,不明白的請留言。
總結
以上是生活随笔為你收集整理的JAVA生成的二维码以及给二维码添加背景图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WITS标准(1)简介
- 下一篇: 【图片新闻】美国海军正在全力打造一支无人