您的位置:首页 > 移动开发 > 微信开发

小程序动态生成二维码,生成image图片

2018-01-22 09:45 302 查看
前端:

<imagesrc="{{img_usrl}}"style="width:100%;height:104px;"bindlongtap="saveImg"></image>

js部分:在onLoad中请求

//我的userid值为:239a3c37-3c2e-4a9d-be74-557638b23b63
this.setData({img_usrl:getApp().getBaseUrl()+"/icon/"+userid});

java后台:

@RequestMapping("icon/{cateogry}")
publicvoidgetQrcodeImg(@PathVariable("cateogry")Stringcateogry,
HttpServletRequestrequest,
HttpServletResponseresponse){

try{
//cateogry的值为前端请求的值:239a3c37-3c2e-4a9d-be74-557638b23b63
Stringurl="固定写死的url路径?id参数="+cateogry;
BufferedImageimage=QRCodeUtli.getqrcode(url);
response.setContentType("image/png");

OutputStreamstream=response.getOutputStream();
ByteArrayOutputStreamout=newByteArrayOutputStream();
ImageIO.write(image,"png",out);
stream.write(out.toByteArray());
stream.flush();
stream.close();
}catch(Exceptione){
e.printStackTrace();
}
}


工具QRCodeUtli类:

packagecom.early.api.util;
importjava.awt.image.BufferedImage;
importjava.util.HashMap;
importjava.util.Map;
importcom.google.zxing.BarcodeFormat;
importcom.google.zxing.EncodeHintType;
importcom.google.zxing.MultiFormatWriter;
importcom.google.zxing.WriterException;
importcom.google.zxing.common.BitMatrix;
publicclassQRCodeUtli{

privatestaticfinalintBLACK=0xFF000000;
privatestaticfinalintWHITE=0xFFFFFFFF;

publicstaticBufferedImagegetqrcode(Stringcode){
intwidth=400;//图像宽度
intheight=400;//图像高度
Map<EncodeHintType,Object>hints=newHashMap<EncodeHintType,Object>();
hints.put(EncodeHintType.MARGIN,0);//设置白边宽度,取值0~4
hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
try{
BitMatrixbitMatrix=newMultiFormatWriter().encode(code,
BarcodeFormat.QR_CODE,width,height,hints);
BufferedImageimage=toBufferedImage(bitMatrix);
returnimage;
}catch(WriterExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
returnnull;
}
publicstaticBufferedImagetoBufferedImage(BitMatrixmatrix){
intwidth=matrix.getWidth();
intheight=matrix.getHeight();
BufferedImageimage=newBufferedImage(width,height,
BufferedImage.TYPE_INT_RGB);
for(intx=0;x<width;x++){
for(inty=0;y<height;y++){
image.setRGB(x,y,matrix.get(x,y)?BLACK:WHITE);
}
}
returnimage;
}
}


pom文件需要引用的包:

<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.1</version>
</dependency>



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: