您的位置:首页 > 编程语言 > Java开发

Java:生成带logo的二维码(ZXing)

2017-06-25 11:15 387 查看
相关jar包下载:ZXing3.3.0.jar

public class QRCodeCreateWithLogo {
public BufferedImage gengrateQRCode(String contents,int size){
BufferedImage targetImage=null;

HashMap hints=new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 2);//留白

try {
BitMatrix bitMatrix=new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, size, size,hints);
targetImage=new BufferedImage(size,size,BufferedImage.TYPE_INT_RGB);
for(int x=0;x<size;x++){
for(int y=0;y<size;y++){
targetImage.setRGB(x, y, bitMatrix.get(x, y)? 0x0AC516:0xFFFFFFFF);//0x0AC516绿色二维码
}
}
} catch (Exception e) {
e.printStackTrace();
}
return targetImage;
}
//srcQRCode为要添加logo的二维码,path为logo路径
public BufferedImage insertLogo(BufferedImage srcQRCode,String path,
int size) throws Exception{
File logo=new File(path);
if(!logo.exists()){
return srcQRCode;
}
Image logoImg=ImageIO.read(logo);

Image targetLogo=logoImg.getScaledInstance(size, size, Image.SCALE_SMOOTH);//压缩logo
BufferedImage targetBuffLogo=new BufferedImage(size,size,BufferedImage.TYPE_INT_RGB);
targetBuffLogo.getGraphics().drawImage(targetLogo, 0, 0,null);//重新生成压缩后的logo

int pos=(srcQRCode.getWidth()-size)/2;
Graphics2D g=srcQRCode.createGraphics();
g.drawImage(targetBuffLogo, pos, pos,size,size, null);//绘制logo

Shape shape=new RoundRectangle2D.Float(pos, pos, size, size, 6, 6);//绘制带圆角的边框
g.setStroke(new BasicStroke(3F));//设置画笔(边框)宽度
g.draw(shape);
g.dispose();

return srcQRCode;
}
public void saveImage(BufferedImage targetImage,String format,String path){
try {
ImageIO.write(targetImage, format, new File(path));
} catch (IOException e) {
e.printStackTrace();
}
}
//
public static void main(String [] args) throws Exception{
QRCodeCreateWithLogo qrcodeTool=new QRCodeCreateWithLogo();
BufferedImage qrCode=qrcodeTool.gengrateQRCode("http://www.sisu.shop/", 400);
qrcodeTool.saveImage(qrCode, "png", "D:/sisu.png");

BufferedImage qrCodeWidLogo=qrcodeTool.insertLogo(ImageIO.read(new File("D:/sisu.png")), "D:/logo.jpg", 40);
qrcodeTool.saveImage(qrCodeWidLogo, "png", "D:/sisuwithlogo.png");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  qrcode zxing java 二维码