<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
SpringBoot、Maven
<!--二維條碼生成 --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.3</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.3</version> </dependency>
package com.milu.boss.common.util; import cn.hutool.core.codec.Base64; import cn.hutool.core.util.StrUtil; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import java.awt.*; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URL; import java.util.HashMap; /** * 連結二維條碼生成工具 * @author qzz */ @Slf4j @Component public class QrCodeUtil { /** * 預設寬度 */ private static final Integer WIDTH = 140; /** * 預設高度 */ private static final Integer HEIGHT = 140; /** * LOGO 預設寬度 */ private static final Integer LOGO_WIDTH = 22; /** * LOGO 預設高度 */ private static final Integer LOGO_HEIGHT = 22; /** * 圖片格式 */ private static final String IMAGE_FORMAT = "png"; private static final String CHARSET = "utf-8"; /** * 原生轉碼前面沒有 data:image/png;base64 這些欄位,返回給前端是無法被解析 */ private static final String BASE64_IMAGE = "data:image/png;base64,%s"; /** * 生成二維條碼,使用預設尺寸 * * @param content 內容 * @return */ public String getBase64QRCode(String content) { return getBase64Image(content, WIDTH, HEIGHT, null, null, null); } /** * 生成二維條碼,使用預設尺寸二維條碼,插入預設尺寸logo * * @param content 內容 * @param logoUrl logo地址 * @return */ public String getBase64QRCode(String content, String logoUrl) { return getBase64Image(content, WIDTH, HEIGHT, logoUrl, LOGO_WIDTH, LOGO_HEIGHT); } /** * 生成二維條碼 * * @param content 內容 * @param width 二維條碼寬度 * @param height 二維條碼高度 * @param logoUrl logo 線上地址 * @param logoWidth logo 寬度 * @param logoHeight logo 高度 * @return */ public String getBase64QRCode(String content, Integer width, Integer height, String logoUrl, Integer logoWidth, Integer logoHeight) { return getBase64Image(content, width, height, logoUrl, logoWidth, logoHeight); } private String getBase64Image(String content, Integer width, Integer height, String logoUrl, Integer logoWidth, Integer logoHeight) { ByteArrayOutputStream os = new ByteArrayOutputStream(); BufferedImage bufferedImage = crateQRCode(content, width, height, logoUrl, logoWidth, logoHeight); try { ImageIO.write(bufferedImage, IMAGE_FORMAT, os); } catch (IOException e) { log.error("[生成二維條碼,錯誤{}]", e); } // 轉出即可直接使用 return String.format(BASE64_IMAGE, Base64.encode(os.toByteArray())); } /** * 生成二維條碼 * * @param content 內容 * @param width 二維條碼寬度 * @param height 二維條碼高度 * @param logoUrl logo 線上地址 * @param logoWidth logo 寬度 * @param logoHeight logo 高度 * @return */ private BufferedImage crateQRCode(String content, Integer width, Integer height, String logoUrl, Integer logoWidth, Integer logoHeight) { if (StrUtil.isNotBlank(content)) { ServletOutputStream stream = null; HashMap<EncodeHintType, Comparable> hints = new HashMap<>(4); // 指定字元編碼為utf-8 hints.put(EncodeHintType.CHARACTER_SET, CHARSET); // 指定二維條碼的糾錯等級為中級 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 設定圖片的邊距 hints.put(EncodeHintType.MARGIN, 2); try { QRCodeWriter writer = new QRCodeWriter(); BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints); BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } if (StrUtil.isNotBlank(logoUrl)) { insertLogo(bufferedImage, width, height, logoUrl, logoWidth, logoHeight); } return bufferedImage; } catch (Exception e) { e.printStackTrace(); } finally { if (stream != null) { try { stream.flush(); stream.close(); } catch (IOException e) { e.printStackTrace(); } } } } return null; } /** * 二維條碼插入logo * * @param source 二維條碼 * @param width 二維條碼寬度 * @param height 二維條碼高度 * @param logoUrl logo 線上地址 * @param logoWidth logo 寬度 * @param logoHeight logo 高度 * @throws Exception */ private void insertLogo(BufferedImage source, Integer width, Integer height, String logoUrl, Integer logoWidth, Integer logoHeight) throws Exception { // logo 源可為 File/InputStream/URL Image src = ImageIO.read(new URL(logoUrl)); // 插入LOGO Graphics2D graph = source.createGraphics(); int x = (width - logoWidth) / 2; int y = (height - logoHeight) / 2; graph.drawImage(src, x, y, logoWidth, logoHeight, null); Shape shape = new RoundRectangle2D.Float(x, y, logoWidth, logoHeight, 6, 6); graph.setStroke(new BasicStroke(3f)); graph.draw(shape); graph.dispose(); } /** * 獲取二維條碼 * * @param content 內容 * @param output 輸出流 * @throws IOException */ public void getQRCode(String content, OutputStream output) throws IOException { BufferedImage image = crateQRCode(content, WIDTH, HEIGHT, null, null, null); ImageIO.write(image, IMAGE_FORMAT, output); } /** * 獲取二維條碼 * * @param content 內容 * @param logoUrl logo資源 * @param output 輸出流 * @throws Exception */ public void getQRCode(String content, String logoUrl, OutputStream output) throws Exception { BufferedImage image = crateQRCode(content, WIDTH, HEIGHT, logoUrl, LOGO_WIDTH, LOGO_HEIGHT); ImageIO.write(image, IMAGE_FORMAT, output); } }
public static void main(String[] args) { QrCodeUtil qrCodeUtil=new QrCodeUtil(); String content="https://www.baidu.com/"; String logoUrl="https://s3.ap-northeast-1.wasabisys.com/img.it145.com/202205/PCtm_d9c8750bed0b3c7d089fa7d55720d6cfm5mfvhislmw.png"; String url =qrCodeUtil.getBase64QRCode(content, logoUrl); System.out.println(url); }
執行結果:Base64 字串
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIwAAACMCAIAAAAhotZpAAACn0lEQVR42u3bQU7jMBQG4JYFtxhpWM6WA7CcO8MJuAYSiCPMCnUqWWNFGQlB/Z7tJt+vLtoqCYk/krw8zOEk0+dgCCAJJEgCSSBBEkgCCZJAgiSQBBIkgSSQIAkkaUI6JCRjf67+uCBBggQJ0rcOpud2vjIQLYM46rggQYIECVL8TkQNSsbNOXt/IEGCBAnSvpAyHkghQYIECRKkr24nu5EKCRIkSJC2iTQKuwVAFxwSJEiQtoOUMWFjhu/NFoIECRKk60DKTs9Bn3ocIEGCBAlS6kNozyZpy4NwzwIBEiRIkCDF3+RnmBDZgtHSJM0AgwQpf9pUxj5DakVKeg7bHVLLQPR5wOzTFJ6uwToK6bLRhDQvUpITJEh9kaJu5iH70Ni07VlEQIIECRKk3GIhoxl6/vjr/uX8StqHUV0SSJAgQVquW3kKFaTEouDiQy1I9bVa6+P9PbbBmlFobA3p5famvOrHsu5SqCzw/G/JujCkfkhLqvKxXO5WSPUNpCnOpIffr/W6t1rrfyFIMct8su7qFFka1Aqifl9PqT02WMci/Twelwz1crd8U7cDaQxSGfc/T4/nN293P1YF3upMKk4tNTekS67v370XJgltASnqRh2b9okxV99gnRwpZPYSpCykwClmkDrNC981UlQjMmNAs4uFlOszJEiQIEEanlFFREvhAwkSJEiQxhcOGTfkjJ8bVZi0FESQIEGCBGl8gzX7oThq+5stHCBBggRph0gZN/AZio5d/FcFJEiQIEEKLxB6TkqBBAkSJEj7Qspo/mY0l1Me9iFBggQJ0vAGa9QvR9QvUFRjFxIkSJAg5SL1bFxm/3EvuyELCRIkSJDikaRPIEESSJAEkkCCJJAEEiSBBEkgCSRIAkkgQRJIcvoLo2P+nGoPVwkAAAAASUVORK5CYII=
http://tools.jb51.net/transcoding/img2base64
5.1 base64圖片 轉 MultipartFile
package com.milu.boss.common.util; /** * base64轉multipartfile工具類 * @author qzz */ import org.springframework.web.multipart.MultipartFile; import sun.misc.BASE64Decoder; import java.io.*; /** * base64轉MultipartFile */ public class BASE64DecodedMultipartFile implements MultipartFile { private final byte[] imgContent; private final String header; /** * * @param imgContent * @param header */ public BASE64DecodedMultipartFile(byte[] imgContent, String header) { this.imgContent = imgContent; this.header = header.split(";")[0]; } @Override public String getName() { return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1]; } @Override public String getOriginalFilename() { return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1]; } @Override public String getContentType() { return header.split(":")[1]; } @Override public boolean isEmpty() { return imgContent == null || imgContent.length == 0; } @Override public long getSize() { return imgContent.length; } @Override public byte[] getBytes() throws IOException { return imgContent; } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(imgContent); } @Override public void transferTo(File dest) throws IOException, IllegalStateException { new FileOutputStream(dest).write(imgContent); } public static MultipartFile base64ToMultipart(String base64) { try { String[] baseStrs = base64.split(","); BASE64Decoder decoder = new BASE64Decoder(); byte[] b = new byte[0]; b = decoder.decodeBuffer(baseStrs[1]); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } return new BASE64DecodedMultipartFile(b, baseStrs[0]); } catch (IOException e) { e.printStackTrace(); return null; } } /** * base64 轉 MultipartFile,獲取對應的InputStream * @param base64 * @return */ public static InputStream getQrCodeInputStream(String base64){ MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(base64); try { return multipartFile.getInputStream(); } catch (IOException e) { return null; } } }
base64圖片轉MultipartFile :
MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(base64);
5.2 MultipartFile 上傳oss
/** * base64 轉 MultipartFile,獲取對應的InputStream * @param base64 * @return */ public static InputStream getQrCodeInputStream(String base64){ MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(base64); try { return multipartFile.getInputStream(); } catch (IOException e) { return null; } }
圖片流上傳oos:
/** * 圖片流上傳oos * @param fis * @return */ public String uploadImageUrl(InputStream fis){ String url = ""; try { String fileExt = "png";; //生成新的檔名 String newfilename = "file/"; Date now = new Date(); SimpleDateFormat date = new SimpleDateFormat("yyyyMMdd"); newfilename += date.format(now) + "/"; SimpleDateFormat time = new SimpleDateFormat("HHmmssSSS"); newfilename += time.format(now); newfilename += "_" + new Random().nextInt(1000) + "." + fileExt; ossService.upload(newfilename, fis); url = "設定的阿里雲OSS圖片地址OSS_PIC_URL" + newfilename; }catch (Exception e) { e.printStackTrace(); } return url; }
ossService.upload:
/** * 上傳檔案 */ public boolean upload(String filepath, InputStream inputstream) { boolean result = false; // 初始化設定引數 String OSS_ENDPOINT = "阿里雲 上傳oss 設定的 ENDPOINT"; String OSS_ACCESSKEYID = "阿里雲 上傳oss 設定的 CCESSKEYID"; String OSS_ACCESSKEYSECRET = "阿里雲 上傳oss 設定的 ACCESSKEYSECRET"; String OSS_BUCKET = "阿里雲 上傳oss 設定的 BUCKET"; OSSClient ossClient = null; try { if (filepath != null && !"".equals(filepath.trim())) { // 建立ClientConfiguration範例,按照您的需要修改預設引數 ClientConfiguration conf = new ClientConfiguration(); // 開啟支援CNAME選項 conf.setSupportCname(true); ossClient = new OSSClient(OSS_ENDPOINT, OSS_ACCESSKEYID, OSS_ACCESSKEYSECRET, conf); // 上傳 ossClient.putObject(OSS_BUCKET, filepath, inputstream); result = true; } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("檔案上傳異常"); } finally { // 關閉client ossClient.shutdown(); } return result; }
參考資料:https://zhuanlan.zhihu.com/p/158576491
到此這篇關於SpringBoot 二維條碼生成base64並上傳OSS的實現範例的文章就介紹到這了,更多相關SpringBoot 二維條碼生成base64內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45