package com.cowr.common.utils; import com.google.zxing.BarcodeFormat; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.jfinal.kit.Base64Kit; import com.jfinal.log.Log; import net.coobird.thumbnailator.Thumbnails; import java.io.*; import java.util.Base64; public class ImageUtil { private static Log log = Log.getLog(ImageUtil.class); public static File createThumbnail(File imageFile, String newname) throws IOException { if (imageFile == null || imageFile.isDirectory() || !imageFile.exists()) { return null; } String oldpath = imageFile.getAbsolutePath(); String outfmt = oldpath.substring(oldpath.lastIndexOf(".") + 1, oldpath.length()).toLowerCase(); String newpath = imageFile.getParentFile().getAbsolutePath() + "/" + newname; Thumbnails.of(oldpath).scale(0.7f).outputFormat(outfmt).toFile(newpath); File newfile = new File(newpath); if (newfile != null && newfile.exists()) { return newfile; } return null; } public static boolean generateImage(String imgStr, File imgFile) {// 对字节数组字符串进行Base64解码并生成图片 if (imgStr == null) // 图像数据为空 return false; // BASE64Decoder decoder = new BASE64Decoder(); OutputStream out = null; try { // Base64解码 // byte[] bytes = decoder.decodeBuffer(imgStr); byte[] bytes = Base64.getDecoder().decode(imgStr); for (int i = 0; i < bytes.length; ++i) { if (bytes[i] < 0) {// 调整异常数据 bytes[i] += 256; } } // 生成图片 out = new FileOutputStream(imgFile); out.write(bytes); out.flush(); out.close(); return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } finally { if (out != null) { try { out.flush(); out.close(); } catch (Exception e) { log.error(e.getMessage(), e); } } } } public static byte[] getQRCodeImage(String text, int width, int height, String format) throws WriterException, IOException { QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height); ByteArrayOutputStream out = null; try { out = new ByteArrayOutputStream(); MatrixToImageWriter.writeToStream(bitMatrix, format, out); return out.toByteArray(); } catch (Exception e) { throw e; } finally { if (out != null) { out.close(); } } } public static String getQRCodeBase64(String text, int width, int height, String format) throws IOException, WriterException { return Base64Kit.encode(getQRCodeImage(text, width, height, format)); } public static void main(String[] args) { File file = new File("C:\\Users\\lisai\\Desktop\\402-1-鄂A7D1P11148.jpg"); try { createThumbnail(file, "123"); } catch (IOException e) { e.printStackTrace(); } } }