欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot 二維碼生成base64并上傳OSS的實(shí)現(xiàn)示例

 更新時(shí)間:2022年05月19日 15:30:15   作者:12程序猿  
本文主要介紹了SpringBoot 二維碼生成base64并上傳OSS的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

基礎(chǔ)環(huán)境

SpringBoot、Maven

代碼實(shí)現(xiàn)

1.添加依賴

<!--二維碼生成  -->
<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>

2.工具類

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 {

    /**
     * 默認(rèn)寬度
     */
    private static final Integer WIDTH = 140;
    /**
     * 默認(rèn)高度
     */
    private static final Integer HEIGHT = 140;

    /**
     * LOGO 默認(rèn)寬度
     */
    private static final Integer LOGO_WIDTH = 22;
    /**
     * LOGO 默認(rèn)高度
     */
    private static final Integer LOGO_HEIGHT = 22;

    /**
     * 圖片格式
     */
    private static final String IMAGE_FORMAT = "png";
    private static final String CHARSET = "utf-8";
    /**
     * 原生轉(zhuǎn)碼前面沒有 data:image/png;base64 這些字段,返回給前端是無法被解析
     */
    private static final String BASE64_IMAGE = "data:image/png;base64,%s";

    /**
     * 生成二維碼,使用默認(rèn)尺寸
     *
     * @param content 內(nèi)容
     * @return
     */
    public String getBase64QRCode(String content) {
        return getBase64Image(content, WIDTH, HEIGHT, null, null, null);
    }

    /**
     * 生成二維碼,使用默認(rèn)尺寸二維碼,插入默認(rèn)尺寸logo
     *
     * @param content 內(nèi)容
     * @param logoUrl logo地址
     * @return
     */
    public String getBase64QRCode(String content, String logoUrl) {
        return getBase64Image(content, WIDTH, HEIGHT, logoUrl, LOGO_WIDTH, LOGO_HEIGHT);
    }

    /**
     * 生成二維碼
     *
     * @param content    內(nèi)容
     * @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("[生成二維碼,錯(cuò)誤{}]", e);
        }
        // 轉(zhuǎn)出即可直接使用
        return String.format(BASE64_IMAGE, Base64.encode(os.toByteArray()));
    }


    /**
     * 生成二維碼
     *
     * @param content    內(nèi)容
     * @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);
            // 指定二維碼的糾錯(cuò)等級(jí)為中級(jí)
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            // 設(shè)置圖片的邊距
            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 內(nèi)容
     * @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 內(nèi)容
     * @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);
    }
}

3.測(cè)試生成

    public static void main(String[] args) {
        QrCodeUtil qrCodeUtil=new QrCodeUtil();
        String content="https://www.baidu.com/";
        String logoUrl="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png";
        String url =qrCodeUtil.getBase64QRCode(content, logoUrl);
        System.out.println(url);
    }

執(zhí)行結(jié)果: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=

4.base64 轉(zhuǎn)換為圖片在線工具

http://tools.jb51.net/transcoding/img2base64

5.base64圖片上傳oss

5.1 base64圖片 轉(zhuǎn) MultipartFile

package com.milu.boss.common.util;

/**
 * base64轉(zhuǎn)multipartfile工具類
 * @author qzz
 */
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import java.io.*;

/**
 * base64轉(zhuǎn)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 轉(zhuǎn) MultipartFile,獲取對(duì)應(yīng)的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圖片轉(zhuǎn)MultipartFile :

MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(base64);

5.2 MultipartFile 上傳oss

    /**
     * base64 轉(zhuǎn) MultipartFile,獲取對(duì)應(yīng)的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;
        // 初始化配置參數(shù)
        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())) {
                // 創(chuàng)建ClientConfiguration實(shí)例,按照您的需要修改默認(rèn)參數(shù)
                ClientConfiguration conf = new ClientConfiguration();
                // 開啟支持CNAME選項(xiàng)
                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 {
            // 關(guān)閉client
            ossClient.shutdown();
        }
        return result;
    }

參考資料:https://zhuanlan.zhihu.com/p/158576491

到此這篇關(guān)于SpringBoot 二維碼生成base64并上傳OSS的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)SpringBoot 二維碼生成base64內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java數(shù)據(jù)結(jié)構(gòu)中堆的向下和向上調(diào)整解析

    Java數(shù)據(jù)結(jié)構(gòu)中堆的向下和向上調(diào)整解析

    堆是一顆完全二叉樹,在這棵樹中,所有父節(jié)點(diǎn)都滿足大于等于其子節(jié)點(diǎn)的堆叫大根堆,所有父節(jié)點(diǎn)都滿足小于等于其子節(jié)點(diǎn)的堆叫小根堆。堆雖然是一顆樹,但是通常存放在一個(gè)數(shù)組中,父節(jié)點(diǎn)和孩子節(jié)點(diǎn)的父子關(guān)系通過數(shù)組下標(biāo)來確定
    2021-11-11
  • java實(shí)現(xiàn)窗口刷新的示例代碼

    java實(shí)現(xiàn)窗口刷新的示例代碼

    本文主要介紹了java實(shí)現(xiàn)窗口刷新的示例代碼,通過重寫paintComponent()方法和調(diào)用repaint()方法,可以實(shí)現(xiàn)窗口的即時(shí)刷新,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-02-02
  • Java基于接口實(shí)現(xiàn)模擬動(dòng)物聲音代碼實(shí)例

    Java基于接口實(shí)現(xiàn)模擬動(dòng)物聲音代碼實(shí)例

    這篇文章主要介紹了Java基于接口實(shí)現(xiàn)模擬動(dòng)物聲音代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-06-06
  • Java編寫的24點(diǎn)紙牌游戲

    Java編寫的24點(diǎn)紙牌游戲

    這篇文章主要介紹了Java編寫的24點(diǎn)紙牌游戲的相關(guān)資料,需要的朋友可以參考下
    2015-03-03
  • springboot操作阿里云OSS實(shí)現(xiàn)文件上傳,下載,刪除功能

    springboot操作阿里云OSS實(shí)現(xiàn)文件上傳,下載,刪除功能

    這篇文章主要介紹了springboot操作阿里云OSS實(shí)現(xiàn)文件上傳,下載,刪除功能,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-11-11
  • spring boot與spring mvc的區(qū)別及功能介紹

    spring boot與spring mvc的區(qū)別及功能介紹

    這篇文章主要介紹了spring boot與spring mvc的區(qū)別是什么以及spring boot和spring mvc功能介紹,感興趣的朋友一起看看吧
    2018-02-02
  • 新手易懂的Java客戶管理小項(xiàng)目

    新手易懂的Java客戶管理小項(xiàng)目

    本篇文章是作為一個(gè)很適合新手閱讀的初級(jí)小項(xiàng)目,客戶管理,它主要實(shí)現(xiàn)數(shù)據(jù)庫(kù)的增刪查改操作,管理每位客戶的不同信息,如果你也是開始學(xué)Java不久,這篇文章將很適合你
    2021-11-11
  • 阿里SpringBoot應(yīng)用自動(dòng)化部署實(shí)現(xiàn)IDEA版Jenkins

    阿里SpringBoot應(yīng)用自動(dòng)化部署實(shí)現(xiàn)IDEA版Jenkins

    這篇文章主要為大家介紹了阿里SpringBoot應(yīng)用自動(dòng)化部署實(shí)現(xiàn)IDEA版Jenkins過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-07-07
  • java字符串的大寫字母右移實(shí)現(xiàn)方法

    java字符串的大寫字母右移實(shí)現(xiàn)方法

    下面小編就為大家?guī)硪黄猨ava字符串的大寫字母右移實(shí)現(xiàn)方法。小編覺得聽不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-04-04
  • java web支持jsonp的實(shí)現(xiàn)代碼

    java web支持jsonp的實(shí)現(xiàn)代碼

    這篇文章主要介紹了java web支持jsonp的實(shí)現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-11-11

最新評(píng)論