Java生成二維碼並用FastDFS上傳到文件服務器返回圖片地址


1. maven依賴

 <dependency>
   <groupId>com.google.zxing</groupId>
   <artifactId>core</artifactId>
   <version>3.1.0</version>
</dependency>
 <dependency>
   <groupId>commons-codec</groupId>
   <artifactId>commons-codec</artifactId>
   <version>1.9</version>
</dependency>
<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>javase</artifactId>
   <version>3.2.1</version>
</dependency>

2. 生成二維碼工具類

package com.eongb0.common.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
  
//二維碼工具類(使用ZXingjar包)  
public class QRCodeUtils {  
    // 默認寬為300  
    private Integer width = 600;  
    // 默認高為300  
    private Integer height = 600;  
    // 默認二維碼圖片格式  
    private String imageFormat = "png";  
    // 默認二維碼字符編碼  
    private String charType = "utf-8";  
    // 默認二維碼的容錯級別  
    
    // 容錯等級 L、M、Q、H 其中 L 為最低, H 為最高  
    private ErrorCorrectionLevel corretionLevel = ErrorCorrectionLevel.M;  
    // 二維碼與圖片的邊緣  
    private Integer margin = 0;  
    // 二維碼參數  
    private Map<EncodeHintType, Object> encodeHits = new HashMap<EncodeHintType, Object>();  
  

    public QRCodeUtils(Integer width, Integer height, String imageFormat, String charType,  
            ErrorCorrectionLevel corretionLevel, Integer margin) {  
        if (width != null) {  
            this.width = width;  
        }  
        if (height != null) {  
            this.height = height;  
        }  
        if (imageFormat != null) {  
            this.imageFormat = imageFormat;  
        }  
        if (charType != null) {  
            this.charType = charType;  
        }  
        if (corretionLevel != null) {  
            this.corretionLevel = corretionLevel;  
        }  
        if (margin != null) {  
            this.margin = margin;  
        }  
    }  
  
    public QRCodeUtils(Integer width, Integer height, String imageFormat, String charType,  
            ErrorCorrectionLevel corretionLevel) {  
        this(width, height, imageFormat, charType, corretionLevel, null);  
    }  
  
    public QRCodeUtils(Integer width, Integer height, String imageFormat, String charType, Integer margin) {  
        this(width, height, imageFormat, charType, null, margin);  
    }  
  
    public QRCodeUtils(Integer width, Integer height, String imageFormat, String charType) {  
        this(width, height, imageFormat, charType, null, null);  
    }  
  
    public QRCodeUtils(Integer width, Integer height, String imageFormat) {  
        this(width, height, imageFormat, null, null, null);  
    }  
  
    public QRCodeUtils(Integer width, Integer height) {  
        this(width, height, null, null, null, null);  
    }  
  
    public QRCodeUtils() {  
    }  
  
    // 初始化二維碼的參數  
    private void initialParamers() {  
        // 字符編碼  
        encodeHits.put(EncodeHintType.CHARACTER_SET, this.charType);  
        // 容錯等級 L、M、Q、H 其中 L 為最低, H 為最高  
        encodeHits.put(EncodeHintType.ERROR_CORRECTION, this.corretionLevel);  
        // 二維碼與圖片邊距  
        encodeHits.put(EncodeHintType.MARGIN, margin);  
    }  
  
    // 得到二維碼圖片  
    public BufferedImage getBufferedImage(String content) {  
        initialParamers();  
        BufferedImage bufferedImage = null;  
        try {  
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.width,  
                    this.height, this.encodeHits);  
            
            
            //去掉白邊
            int[] rec = bitMatrix.getEnclosingRectangle();  
            int resWidth = rec[2] + 1;  
            int resHeight = rec[3] + 1;  
            BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);  
            resMatrix.clear();  
            for (int i = 0; i < resWidth; i++) {  
                for (int j = 0; j < resHeight; j++) {  
                    if (bitMatrix.get(i + rec[0], j + rec[1])) { 
                         resMatrix.set(i, j); 
                    } 
                }  
            }  
            //2
            int width = resMatrix.getWidth();
            int height = resMatrix.getHeight();
            bufferedImage = new BufferedImage(width, height,BufferedImage.TYPE_INT_ARGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                	bufferedImage.setRGB(x, y, resMatrix.get(x, y) == true ? 
                    Color.BLACK.getRGB():Color.WHITE.getRGB());
                }
            }
        } catch (WriterException e) {
            e.printStackTrace();  
            return null;  
        }  
        return bufferedImage;  
    }  
  
    // 將二維碼保存到輸出流中  
    public void writeToStream(String content, OutputStream os) {  
        initialParamers();  
        try {  
            BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.width, this.height,  
                    this.encodeHits);  
            MatrixToImageWriter.writeToStream(matrix, this.imageFormat, os);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
  
    // 將二維碼圖片保存為文件  
    public void createQrImage(String content, File file) {  
        initialParamers();  
        try {  
            BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.width, this.height,this.encodeHits);  
            MatrixToImageWriter.writeToFile(matrix, this.imageFormat, file);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
  
    // 將二維碼圖片保存到指定路徑  
    public void createQrImage(String content, String path) {  
        initialParamers();  
        try {  
            BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.width, this.height,this.encodeHits);  
            MatrixToImageWriter.writeToPath(matrix, this.imageFormat, new File(path).toPath());  
            //MatrixToImageWriter.
            
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
    
    
    public void newcreateQrImage(String content, String path) {  
        initialParamers();  
        try {  
            BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.width, this.height,this.encodeHits);  
           // MatrixToImageWriter.writeToPath(matrix, this.imageFormat, new File(path).toPath());  
            //MatrixToImageWriter.w
            
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }   
    
      
    //識別圖片二維碼  
    public String decodeQrImage(File file){  
        String content=null;  
        try {  
            BufferedImage bufferedImage=ImageIO.read(new FileInputStream(file));  
            LuminanceSource source=new BufferedImageLuminanceSource(bufferedImage);  
            Binarizer binarizer=new HybridBinarizer(source);  
            BinaryBitmap image=new BinaryBitmap(binarizer);  
            Map<DecodeHintType,Object> decodeHits=new HashMap<DecodeHintType, Object>();  
            decodeHits.put(DecodeHintType.CHARACTER_SET, this.charType);  
            Result result=new MultiFormatReader().decode(image, decodeHits);  
            content=result.getText();  
        }catch (Exception e) {  
            e.printStackTrace();  
        }  
        return content;  
    }  
      
    public Integer getWidth() {  
        return width;  
    }  
  
    public void setWidth(Integer width) {  
        this.width = width;  
    }  
  
    public Integer getHeight() {  
        return height;  
    }  
  
    public void setHeight(Integer height) {  
        this.height = height;  
    }  
  
    public String getImageFormat() {  
        return imageFormat;  
    }  
  
    public void setImageFormat(String imageFormat) {  
        this.imageFormat = imageFormat;  
    }  
  
    public String getCharType() {  
        return charType;  
    }  
  
    public void setCharType(String charType) {  
        this.charType = charType;  
    }  
  
    public ErrorCorrectionLevel getCorretionLevel() {  
        return corretionLevel;  
    }  
  
    public void setCorretionLevel(ErrorCorrectionLevel corretionLevel) {  
        this.corretionLevel = corretionLevel;  
    }  
  
    public Integer getMargin() {  
        return margin;  
    }  
  
    public void setMargin(Integer margin) {  
        this.margin = margin;  
    }  
  
    public Map<EncodeHintType, Object> getHits() {  
        return encodeHits;  
    }  
  
    public void setHits(Map<EncodeHintType, Object> hits) {  
        this.encodeHits = hits;  
    }  
  
}  

3.  將生成的二維碼上傳到FastDFS接口

   @ApiOperation("獲取二維碼URL")
    @GetMapping("getCodeUrl")
    public Result packageUrlForLink(@LoginUser(isFull = true) SysUser user){
        String link="";
        QRCodeUtils qrCode=new QRCodeUtils(100,100);
        qrCode.setMargin(1);
        String deptId = user.getDeptId();
        SysDept dept = userService.findDeptById(deptId);
        String content = "部門名稱:"+dept.getDeptName()+"\r\n打印人:"+user.getUsername() + "\r\n打印時間:" + GTime.getLogTime();
        BufferedImage image=qrCode.getBufferedImage(content);
        try {
            //以流的方式將圖片上傳到fastdfs上:
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", outputStream);
            InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
       // 調用FastDFS中的接口將數據流保存到服務器返回圖片地址 StorePath storePath = storageClient.uploadImageAndCrtThumbImage(inputStream,inputStream.available(),"png",null); link = "http://" + fileServerProperties.getFdfs().getWebUrl() + "/" + storePath.getFullPath(); }catch (IOException ex){ ex.printStackTrace(); } Map<String,Object> model = new HashMap<>(); model.put("imgStr",link); return Result.succeed(model); }

4. FastDFS配置文件 要對縮略圖的大小進行設置

fdfs:
  soTimeout: 1500
  connectTimeout: 1000
  tracker-list: ip:端口
  thumb-image:
    width: 100
    height: 100

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM