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; } }
有问题欢迎留言~
相关文章推荐
- java 二维码原理以及用java实现的二维码的生成、解码
- java 二维码原理以及用java实现的二维码的生成、解码
- java 二维码原理以及用java实现的二维码的生成、解码(转)
- Java实现Base64互相编解码转换图片与字符串
- java 二维码原理以及用java实现的二维码的生成、解码
- java 二维码原理以及用java实现的二维码的生成、解码
- java 二维码原理以及用java实现的二维码的生成、解码
- [java]生成带logo图片的二维码、以及二维码解码
- JAVA 文件与base64之间的转化, 以及Web实现base64上传文件
- java将图片转化为base64和base64转化为图片编码并保存在本地;以及android转base64编码
- 一个Java实现的把指定字符串生成二维码并保存成图片的代码
- java 生成二维码返回base64图片码有换行符的问题
- 后端生成二维码(Google zixing-去白边)转化为base64图片流渲染到前端
- 将图片文件转化为字节数组字符串,并对其进行Base64编码处理和 对字节数组字符串进行Base64解码并生成图片
- C#和JAVA利用BASE64实现图片编码解码
- 二维码的生成和解码Java实现(未测试)
- 微信公众平台 ---------java实现二维码带参生成本地图片(2017/11/10更新版)
- 基于ZXing Android实现生成二维码图片和相机扫描二维码图片即时解码的功能
- java poi设置生成的word的图片为上下型环绕以及其位置的实现
- 微信公众平台 ---------java实现二维码带参生成本地图片(2017/11/10更新版)