二维码Base64识别URL

/ 技术 / 1 条站内评论 / 606浏览

前言

有时候前端上传的图片想保存到数据库中,则需要讲图片进行base64转码,得到一串字符串存到数据库中,前端展示的时候直接传递base64编码即可,不仅减少了一次图片的请求,减少了带宽和页面的加载。


图片&base64

iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAF3ElEQVR4Xu2dW3LjMAwE4/sf2lu1VrwlZeXGcEDZUia/oEhwGg+KjpPb/X6/f+XnsgrcAviybP9uLICvzTeAL843gAP46gpcfH/pwQF8cQUuvr1kcABfXIGLb6+cwbfb7VApthds2/XpAs4dT5sl/+h51077/54/gBcl1AAOYDNESUCK4GTwA0AyOBm8RMKmB1MGqQlMGTfbTv6669P8ZKf1954fzuAAXn/KOgqAwD4PS4MJFsBFhQkg2YvL7A4bnT+Ai8qTwGQvLvO5gLtfM44+Rc8GMFuf6T149gbUDFHHBzA0+QBe3/RRBaKAouerh9y2HhzAAbwKWjdCKaA+bX7yd5vRrv/2XTQ5MLsEkWDkH5W47vlpvgDeKECCBbB5F00CJoNf33TN1ud0JZoyVhVsO959raLnVf8pgajFBDCU/KqA1bviAG5+z6ZDSzJYjPDZEarOH8DNhyzqgWSnHkYZR/OrJZfW6+qR5He1BUy/i646uuuI+HmnmtEBDITUDFOBq/MHcO1r3W130SpQtQTSeFo/GSxmMAnq2tUeRxXgaLu7f3q+GrDDGUwOuPYAfq1gAG/+9EgyOCV6pYBbQdwKRs+3ZzAteLT93RlZFfhoXX4cRs/6V3YCuBY65UNWbbrjRgVwTesAXnSinruV83IlmjLGvYioxeO/Ua7A3fshf2i9WTdz5QwmBwP49dUh6RfAmwiijKGKQIKrAUv+0HoBHMAv39P3Anq4RFOG0KFEjWj1EDTbP5pfzUiajypEAIOCFECqwAEs/g4WAaAMIDvNH8DNGaKWcAJI9l8PePapkno2AXIDggDT+mSn+alC0P7sHhzAhPC1PYDN1yCKcDr0EAAP79cXzZ8MBoUD+P8Cld+DqURTBKrPU8ZRRp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xygOR+AJNCJ7cH8MkBkvt/ADvimyACpNA3AAAAAElFTkSuQmCC


场景

现在我们有一个需求,后台得到图片base64后,同时图片又是二维码图像,此时我们又像得到二维码中的信息(URL)


两种方案

QRcode

优势

可以直接通过base64创建字节流,qrcode有个方法可以根据图片字节流进行解码。

劣势

该jar包在maven框架无法下载,只能通过网上下载jar导入到项目中

jar:点我下载


import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.exception.DecodingFailedException;
import sun.misc.BASE64Decoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;


/**
* Created by sanii
* 2018-05-22 19:11:33.
*/
public class Base64ToQrcode {



/**
* 解析二维码(QRCode
*
* @param imgPath 图片路径
* @return
*/
public static String decoderByPath(String imgPath) {
// QRCode 二维码图片的文件
File imageFile = new File(imgPath);
BufferedImage bufImg = null;
String content = null;
try {
bufImg = ImageIO.read(imageFile);
QRCodeDecoder decoder = new QRCodeDecoder();
content = new String(decoder.decode(new TwoDimensionCodeImage(bufImg)), "utf-8");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
} catch (DecodingFailedException dfe) {
System.out.println("Error: " + dfe.getMessage());
dfe.printStackTrace();
}
return content;
}


/**
* 解析二维码(QRCode
*
* @param base64Str base64字符串
* @return
*/
public static String decoderByBase64(String base64Str) {
BufferedImage bufImg = null;
String content = null;
try {
byte[] bytes =base64Stream(base64Str);
InputStream in_withcode = new ByteArrayInputStream(bytes);
bufImg = ImageIO.read(in_withcode);
QRCodeDecoder decoder = new QRCodeDecoder();
content = new String(decoder.decode(new TwoDimensionCodeImage(bufImg)), "utf-8");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
} catch (DecodingFailedException dfe) {
System.out.println("Error: " + dfe.getMessage());
dfe.printStackTrace();
}
return content;
}

public static byte[] base64Stream(String imgStr){

BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes = null;
try {
// Base64解码
bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
}catch(Exception e){

}
return bytes;
    }
}
import jp.sourceforge.qrcode.data.QRCodeImage;

import java.awt.image.BufferedImage;

/**
* 生成二维码生成属性
*
* @author sanii
*/
public class TwoDimensionCodeImage implements QRCodeImage {

BufferedImage bufImg;

public TwoDimensionCodeImage(BufferedImage bufImg) {
this.bufImg = bufImg;
}

@Override
public int getHeight() {
return bufImg.getHeight();
}

@Override
public int getPixel(int x, int y) {
return bufImg.getRGB(x, y);
}

@Override
public int getWidth() {
return bufImg.getWidth();
}

}


 测试


public static void main(String[] args) {
String base64str = "iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAF3ElEQVR4Xu2dW3LjMAwE4/sf2lu1VrwlZeXGcEDZUia/oEhwGg+KjpPb/X6/f+XnsgrcAviybP9uLICvzTeAL843gAP46gpcfH/pwQF8cQUuvr1kcABfXIGLb6+cwbfb7VApthds2/XpAs4dT5sl/+h51077/54/gBcl1AAOYDNESUCK4GTwA0AyOBm8RMKmB1MGqQlMGTfbTv6669P8ZKf1954fzuAAXn/KOgqAwD4PS4MJFsBFhQkg2YvL7A4bnT+Ai8qTwGQvLvO5gLtfM44+Rc8GMFuf6T149gbUDFHHBzA0+QBe3/RRBaKAouerh9y2HhzAAbwKWjdCKaA+bX7yd5vRrv/2XTQ5MLsEkWDkH5W47vlpvgDeKECCBbB5F00CJoNf33TN1ud0JZoyVhVsO959raLnVf8pgajFBDCU/KqA1bviAG5+z6ZDSzJYjPDZEarOH8DNhyzqgWSnHkYZR/OrJZfW6+qR5He1BUy/i646uuuI+HmnmtEBDITUDFOBq/MHcO1r3W130SpQtQTSeFo/GSxmMAnq2tUeRxXgaLu7f3q+GrDDGUwOuPYAfq1gAG/+9EgyOCV6pYBbQdwKRs+3ZzAteLT93RlZFfhoXX4cRs/6V3YCuBY65UNWbbrjRgVwTesAXnSinruV83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eXaBWYOj6AA/hlUVIrDlU4stN67SWaHCK7WnJpPtWurk/jqSJQiyL/A5gU2tgJWHfJD+DNe7LISx4ewAffJFVLkExy54EAFv8mhiv87BLm9kjyjwK0O6D29B6+6HAB0vMkoPo89dCjb9oCGO6qA7j2VZZk8E6kUAVR7VRBuku6/B5MGRP7ZypQzuDPdD9ekQIBTAqd3B7AJwdI7gcwKXRyewCfHCC5H8Ck0MntAXxygOR+AJNCJ7cH8MkBkvt/ADvimyACpNA3AAAAAElFTkSuQmCC";
try {
String str1= Base64ToQrcode.decoderByBase64(base64str);
System.out.println(str1);
} catch (Exception e) {
e.printStackTrace();
}
}


效果



Zxing

优势

google非常优秀开源的二维码解析框架,可以在maven仓库下载

劣势

不能通过字节流解码,只能通过图片的URL文件解码,我们

思路

先将图片的base64编码转码成二维码图片存到项目相关目录下,经过测试发现一个二维码大小在4k左右,不是很占用内存大小。在进行图片文件解码

maven依赖

<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.0</version>
</dependency>


根据图片路径解码

public static String testDecoder(String path) throws NotFoundException {
//二维码图片路径
File imageFile = new File(path);
BufferedImage image = null;
try {
image = ImageIO.read(imageFile);
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map<DecodeHintType, Object> hints = new HashMap<>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
//解码获取二维码中信息
Result result = new MultiFormatReader().decode(binaryBitmap, hints);
return result.getText();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}


主代码

    @Test
public void generate(){
//二维码图片路径
try {
final String filePath ="QRcode/";//图片保存到项目根目录该文件夹下
String base64str = "iVBORw0KG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dClCkw9mkoq9UDyh+Sg+VX/3fF2D6YNd2eQumFan+aj/VEPpudd/9SAepb2rl98pw1QxtAG1PnV+QhQAIsf4KuCBXDtC98/KlVXBqsZoJZM6rnu+u78syuGmhDtJdoVWC3hNF71J4BVxcTxBMwFQO648yeDQeEAphBc2ymg7BLdDaTq8NNx8X8puvN3P+/qV/WnfFU5+1BUdTiAHwpU9QrgncpIr2VUUOn5ZLDZs0dfK/YqRDVjqs+fHjBFOJ1aye4CpJajrk/7JX9V4NX1ppVocoAEJDsJRusHcHOJJCDdPSuAHwokg5dIcANMDaijKtQwYHVD7ngCQCVXXZ8AvPvQVd1PAO8oFcDVEGoalww++ceFFAcBPBkwvacRINWulkjyT+2Z1NNd/1R/1AB/XrhUP/AnAVWANN4VkF7LaP0AVhUSxwfwWrBkMHx8qJbEX5/BrmDdAlKBoAxw7e76pMdoyym/B5MAtEGy0/xknz3/7PUDWPzHWSSY2+PVCqYGCB1qq+sng5dIIABkdysIBeTbSzRFHDlIAnbbCchsezUDn++zgxWsLYMDWAuJAJ78f480HP2jAziAV1FFLWovBC9Tot0cU1sMradmaA5Zg4cMArF3iKk+tzcugJtLsAskGWx+/3f2a1IA/1+B0/Rg6lFUEumQ4mawur4bkLTes/WMfh5MV320AXqeNkDA1IAI4DeXaBWYOj6AA/hlUVIrDlU4stN67SWaHCK7WnJpPtWurk/jqSJQiyL/A5gU2tgJWHfJD+DNe7LISx4ewAffJFVLkExy54EAFv8mhiv87BLm9kjyjwK0O6D29B6+6HAB0vMkoPo89dCjb9oCGO6qA7j2VZZk8E6kUAVR7VRBuku6/B5MGRP7ZypQzuDPdD9ekQIBTAqd3B7AJwdI7gcwKXRyewCfHCC5H8Ck0MntAXxygOR+AJNCJ7cH8MkBkvt/ADvimyACpNA3AAAAAElFTkSuQmCC";
String fileName = UUID.randomUUID().toString().replace("-","");//使用UUID保证图片名字唯一
ImageBase64Utils.base64ToImageFile(base64str,filePath+fileName+".jpg");//通过base64编码生成图片保存到指定目录
String text = testDecoder(filePath + fileName + ".jpg");//读取执行目录文件进行解码
System.out.println(text);
} catch (IOException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
}
}

效果



资料参考:


https://my.oschina.net/yangyan/blog/490518


https://blog.csdn.net/kangcool_sn/article/details/53433502






  1. SAn

    selenIUM自动测试:二维码Base64识别URL - SAn Blog

    回复
召唤蕾姆
琼ICP备18000156号

鄂公网安备 42011502000211号