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

Java生成二维码以及二维码解码,图片与base64互相转化的实现

2020-06-27 04:31 1071 查看

二维码生成是使用 google 开源图形码工具Zxing。

maven依赖如下:

[code]<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.1</version>
</dependency>

具体实现直接上代码:

1.二维码相关

[code]public class ZxingKit {

private final static String PNG = "png";

/**
*
* @param url url
* @return base64 string
*/
public static String urlToBase64(String url) {
File file = new File("/image/");
if (!file.exists()) {
file.mkdirs();
}
String uuid = UUID.randomUUID().toString().replaceAll("-","");
String saveImgFilePath = "/image/code_"+uuid+".png";
Boolean encode = encode(url, BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, PNG, 200, 200,
saveImgFilePath);
if (encode) {
return ImageToBase64ByLocal(saveImgFilePath);
} else {
return "";
}
}

/**
*
* @param url url
* @param width 二维码宽度
* @param height 二维码高度
* @return base64 string
*/
public static String urlToBase64(String url, int width, int height) {
File file = new File("/image/");
if (!file.exists()) {
file.mkdirs();
}
String uuid = UUID.randomUUID().toString().replaceAll("-","");
String saveImgFilePath = "/image/code_"+uuid+".png";
Boolean encode = encode(url, BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, PNG, width, height,
saveImgFilePath);
if (encode) {
return ImageToBase64ByLocal(saveImgFilePath);
} else {
return "";
}
}

/**
*
* @param url url
* @param width 二维码宽度
* @param height 二维码高度
* @param imgPath  二维码路径
* @return base64 string
*/
public static String urlToBase64(String url, int width, int height, String imgPath) {
Boolean encode = encode(url, BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, PNG, width, height,
imgPath);
if (encode) {
return ImageToBase64ByLocal(imgPath);
} else {
return "";
}
}

/**
* Zxing图形码生成工具
*
* @param contents        内容
* @param barcodeFormat   BarcodeFormat对象
* @param format          图片格式,可选[png,jpg,bmp]
* @param width           宽
* @param height          高
* @param margin          边框间距px
* @param saveImgFilePath 存储图片的完整位置,包含文件名
* @return {boolean}
*/
public static boolean encode(String contents, BarcodeFormat barcodeFormat, Integer margin,
ErrorCorrectionLevel errorLevel, String format, int width, int height, String saveImgFilePath) {
Boolean bool = false;
BufferedImage bufImg;
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, errorLevel);
hints.put(EncodeHintType.MARGIN, margin);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
try {
// contents = new String(contents.getBytes("UTF-8"), "ISO-8859-1");
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, barcodeFormat, width, height, hints);
MatrixToImageConfig config = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
bufImg = MatrixToImageWriter.toBufferedImage(bitMatrix, config);
bool = writeToFile(bufImg, format, saveImgFilePath);
} catch (Exception e) {
e.printStackTrace();
}
return bool;
}

/**
* @param outputStream  可以来自response,也可以来自文件
* @param contents      内容
* @param barcodeFormat BarcodeFormat对象
* @param margin        图片格式,可选[png,jpg,bmp]
* @param errorLevel    纠错级别 一般为:ErrorCorrectionLevel.H
* @param format        图片格式,可选[png,jpg,bmp]
* @param width         宽
* @param height        高
*                      eg:
*                      ZxingKit.encodeOutPutSteam(response.getOutputStream(), qrCodeUrl, BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, "png", 200, 200);
*/
public static void encodeOutPutSteam(OutputStream outputStream, String contents, BarcodeFormat barcodeFormat, Integer margin, ErrorCorrectionLevel errorLevel, String format, int width, int height) {
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, errorLevel);
hints.put(EncodeHintType.MARGIN, margin);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

try {
BitMatrix bitMatrix = (new MultiFormatWriter()).encode(contents, barcodeFormat, width, height, hints);
MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(outputStream);
}

}

/**
* @param srcImgFilePath 要解码的图片地址
* @return {Result}
*/
@SuppressWarnings("finally")
public static Result decode(String srcImgFilePath) {
Result result = null;
BufferedImage image;
try {
File srcFile = new File(srcImgFilePath);
image = ImageIO.read(srcFile);
if (null != image) {
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
result = new MultiFormatReader().decode(bitmap, hints);
} else {
throw new IllegalArgumentException("Could not decode image.");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
return result;
}
}

/**
* 将BufferedImage对象写入文件
*
* @param bufImg          BufferedImage对象
* @param format          图片格式,可选[png,jpg,bmp]
* @param saveImgFilePath 存储图片的完整位置,包含文件名
* @return {boolean}
*/
@SuppressWarnings("finally")
public static boolean writeToFile(BufferedImage bufImg, String format, String saveImgFilePath) {
Boolean bool = false;
try {
File f = new File(saveImgFilePath);
if (!f.exists()) {
f.mkdirs();
}
bool = ImageIO.write(bufImg, format, f);
} catch (Exception e) {
e.printStackTrace();
} finally {
return bool;
}
}

/**
* 本地图片转换成base64字符串
*
* @param path 图片位置
* @reture 图片Base64
* @author Byr
* @dateTime 2019-03-07
*/
public static String ImageToBase64ByLocal(String path) {
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
try {
//获取图片路径
File file = new File(path);
in = new FileInputStream(file.getPath());

data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
return "data:image/png;base64," + encoder.encode(data);
}

/**
* 对字节数组字符串进行Base64解码并生成图片
* @param imgStr
* @param imgFilePath
* @return
*/
public static boolean GenerateImage(String imgStr, String imgFilePath) {
// 图像数据为空
if (imgStr == null)
{
return false;
}
imgStr = imgStr.replace("data:image/png;base64,","");
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
// 调整异常数据
if (bytes[i] < 0) {
bytes[i] += 256;
}
}
// 生成jpeg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}

/**
* base64 解码
* @param imgstr imgstr
* @return base64 string
*/
public static String base64Decode(String imgstr) {
File file = new File("/image/");
if (!file.exists()) {
file.mkdirs();
}
String uuid = UUID.randomUUID().toString().replaceAll("-","");
String saveImgFilePath = "/image/decode_"+uuid+".jpg";
Boolean encode = GenerateImage(imgstr, saveImgFilePath);
if (encode) {
Result decode = decode(saveImgFilePath);
String text = decode.getText();
return text;
} else {
return "";
}
}

public static void main(String[] args) {
//		String saveImgFilePath = "D://zxing2.png";
//		Boolean encode = encode("https://www.baidu.com", BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, "png", 200, 200,
//				saveImgFilePath);
//		if (encode) {
//			String toBase64ByLocal = ImageToBase64ByLocal(saveImgFilePath);
//			System.out.println(toBase64ByLocal);
//			Result result = decode(saveImgFilePath);
//			String text = result.getText();
//			System.out.println(text);
//		}
String s = urlToBase64("web_login,22222222222iugyuigjhgvjhfgh");
//        System.out.println(GenerateImage(s, "D:\\112.jpg"));
//        Result decode = decode("D:\\\\112.jpg");
//        String text = decode.getText();
String s1 = base64Decode(s);
System.out.println(s1);
}
}

2. base64与图片互转

[code]/**
* 本地图片转换成base64字符串
*
* @param path 图片位置
* @reture 图片Base64
* @author Byr
* @dateTime 2019-03-07
*/
public static String ImageToBase64ByLocal(String path) {
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
try {
//获取图片路径
File file = new File(path);
in = new FileInputStream(file.getPath());

data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
return "data:image/png;base64," + encoder.encode(data);
}

/**
* 对字节数组字符串进行Base64解码并生成图片
* @param imgStr
* @param imgFilePath
* @return
*/
public static boolean GenerateImage(String imgStr, String imgFilePath) {
// 图像数据为空
if (imgStr == null)
{
return false;
}
imgStr = imgStr.replace("data:image/png;base64,","");
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
// 调整异常数据
if (bytes[i] < 0) {
bytes[i] += 256;
}
}
// 生成jpeg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}

有问题欢迎留言~

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