Java gerar código bidimensional para o servidor e upload de fotos de arquivo com um endereço de retorno FastDFS

1. dependência maven

<dependency> 
   <groupId> com.google.zxing </ groupId> 
   <artifactId> núcleo </ artifactId> 
   <versão> 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. As ferramentas de geração de código bidimensional

empacotar com.eongb0.common.utils; 

importar com.google.zxing *.; 
importação com.google.zxing.client.j2se.BufferedImageLuminanceSource; 
importação com.google.zxing.client.j2se.MatrixToImageWriter; 
importação com.google.zxing.common.BitMatrix; 
importação com.google.zxing.common.HybridBinarizer; 
importação com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; 

importação javax.imageio.ImageIO; 
importar Java.awt *.; 
importação java.awt.image.BufferedImage; 
importação java.io.File; 
importação java.io.FileInputStream; 
importação java.io.OutputStream; 
importação java.util.HashMap; 
importação java.util.Map; 
  
//二维码工具类(使用ZXingjar包)   
QRCodeUtils classe pública {   
    //默认宽为300  
    Integer width = 600 Privado;   
    // altura padrão de 300   
    Privado inteiro height = 600;   
    // default bidimensional formato de imagem de código   
    Privada ImageFormat String = "PNG";   
    // caracteres padrão codificação de código bidimensional   
    de Cordas CharType privada = "utf-8 ";   
    nível de código // padrão bidimensional de tolerância a falhas   
    
    // nível de tolerância a falhas L, M, Q, H, em que L é a mais baixa, H é a mais alta   
    privada ErrorCorrectionLevel corretionLevel = ErrorCorrectionLevel.M;   
    // código bidimensional com a borda imagem   
    margem inteiro privado = 0;   
    // código dimensional parâmetro   
    privada Mapa <EncodeHintType, Object> = novas novas encodeHits o HashMap <EncodeHintType, Object> ();   
  

    QRCodeUtils públicas (largura Integer, altura Integer, ImageFormat string, string CharType,  
            ErrorCorrectionLevel corretionLevel, a margem Integer) {    
        IF (width = null) {!   
            this.width = largura;  
        }   
        if (height = null) {!   
            This.Height = altura;  
        }   
        If (ImageFormat! = Null) {   
            this.imageFormat = ImageFormat;  
        }   
        If (CharType! = Null) {   
            this.charType = CharType;  
        }   
        If {(corretionLevel! = Null)   
            this.corretionLevel = corretionLevel;  
        }   
        If (margem! = Null) {   
            this.margin = margem;  
        }   
    }  
  
    QRCodeUtils públicas (largura inteiro, altura Integer, String ImageFormat, String CharType,   
            ErrorCorrectionLevel corretionLevel) {  
        este (largura, altura, ImageFormat, CharType, corretionLevel, nula);  
    }   
  
    QRCodeUtils públicas (largura inteiro, altura Integer, String ImageFormat, String CharType, margem Inteiro) {   
        este (largura, altura, ImageFormat, CharType, nulo, de margem);  
    }   
  
    QRCodeUtils públicas (largura inteiro, altura Integer, String ImageFormat, String CharType) {   
        este (largura, altura, ImageFormat, CharType, null, null);  
    }   
   
    QRCodeUtils públicas (largura Integer, altura Integer, String ImageFormat) {  
        Esta (largura, altura, ImageFormat, null, null, null);  
    }   
  
    QRCodeUtils públicas (largura inteiro, altura Inteiro) {   
        este (largura, altura, null, null, null, null);  
    }   
  
    QRCodeUtils públicas () {  
    }   
  
    // bidimensional parâmetro código de inicialização   
    privados initialParamers vazios () {   
        // codificação de caracteres   
        encodeHits.put (EncodeHintType.CHARACTER_SET, this.charType);   
        // nível de tolerância a falhas L, M, Q, H, em que L é a mais baixa, é H maior   
        encodeHits.put (EncodeHintType.ERROR_CORRECTION, this.corretionLevel);   
        imagem do código // bidimensional com margens   
        encodeHits.put (EncodeHintType.MARGIN, margem);   
    }   
  
    // obtém bidimensionais imagem código   
    público BufferedImage getBufferedImage (conteúdo string) {  
        initialParamers ();  
        BufferedImage BufferedImage = nulo;  
        try {   
            . BitMatrix bitMatrix = novo MultiFormatWriter () codificar (conteúdo, 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 = novo BitMatrix (resWidth, resHeight);  
            resMatrix.clear ();  
            para (int i = 0; i <resWidth; i ++) {   
                para (int j = 0; j <resHeight; j ++) {  
                    se (bitMatrix.get (i + rec [0], j + rec [1])) { 
                         resMatrix.set (i, j); 
                    } 
                }   
            }   
            // 2  
            int largura = resMatrix.getWidth (); 
            altura = int resMatrix.getHeight ();
            BufferedImage = novo BufferedImage (largura, altura, BufferedImage.TYPE_INT_ARGB); 
            para (int x = 0; X <largura; x ++) { 
                para (int y = 0; y <altura; y ++) { 
                	bufferedImage.setRGB (x, y, resMatrix.get (x, y) == verdadeiro? 
                    cores. BLACK.getRGB (): Color.WHITE.getRGB ()); 
                } 
            } 
        } Catch (WriterException e) { 
            e.printStackTrace ();  
            return null;  
        }   
        Retornar BufferedImage;  
    }   
  
    //将二维码保存到输出流中   
    WriteToStream public void (conteúdo String, OutputStream OS) {   
        initialParamers ();  
        experimentar {  
            BitMatrix matriz = novo MultiFormatWriter () codificar (conteúdo, BarcodeFormat.QR_CODE, this.width, This.Height,.   
                    This.encodeHits);  
            MatrixToImageWriter.writeToStream (matriz, this.imageFormat, SO);  
        } Catch (exceção e) {   
            e.printStackTrace ();  
        }   
    }   
  
    //将二维码图片保存为文件   
    createQrImage public void (conteúdo String, arquivo de arquivo) {   
        initialParamers ();  
            MatrixToImageWriter.writeToFile (matriz, this.imageFormat, arquivo);  
        } Catch (exceção e) {   
        o try {  
            BitMatrix matriz = novo MultiFormatWriter () codificar (conteúdo, BarcodeFormat.QR_CODE, this.width, This.Height, this.encodeHits).;  
        }  
            e.printStackTrace ();  
        }   
    }   
  
    //将二维码图片保存到指定路径   
    public void createQrImage (conteúdo, string path) {   
        initialParamers ();  
        try {   
            BitMatrix matriz = novo MultiFormatWriter () codificar (conteúdo, BarcodeFormat.QR_CODE, this.width, This.Height, this.encodeHits).;  
            MatrixToImageWriter.writeToPath (matriz, this.imageFormat, new File (path) .toPath ());  
            // MatrixToImageWriter. 
            
        } Catch (exceção e) {   
            e.printStackTrace ();   
        initialParamers ();  
        experimentar {  
    }   
    
    
    NewcreateQrImage public void (conteúdo String, String caminho) {   
            BitMatrix matriz = novo MultiFormatWriter () codificar (conteúdo, BarcodeFormat.QR_CODE, this.width, This.Height, this.encodeHits).;  
           // MatrixToImageWriter.writeToPath (matriz, this.imageFormat, new File (path) .toPath ());  
            //MatrixToImageWriter.w 
            
        } catch (exceção e) {   
            e.printStackTrace ();  
        }   
    }    
    
      
    //识别图片二维码   
    public String decodeQrImage (arquivo de arquivo) {   
        conteúdo String = null;  
        try {   
            BufferedImage BufferedImage = ImageIO.read (novo FileInputStream (arquivo));  
            Fonte LuminanceSource = novo BufferedImageLuminanceSource (BufferedImage);  
            Binarizer binarizer = novo HybridBinarizer (fonte);  
            Imagem BinaryBitmap = novo BinaryBitmap (binarizer);  
            Mapa <DecodeHintType, Object> decodeHits = new HashMap <DecodeHintType, Object> ();  
            decodeHits.put (DecodeHintType.CHARACTER_SET, this.charType);  
            Resultado resultado = novo MultiFormatReader () decodificar (imagem, decodeHits).;  
            conteúdo = result.getText ();  
        } catch (exceção e) {   
            e.printStackTrace ();  
        }   
        Retornar conteúdo;  
    }   
      
    Integer getWidth pública () {   
        width retorno;  
    }   
  
    SetWidth public void (largura Integer) {   
        This.width = largura;  
    }   
  
    Integer getHeight pública () {   
        altura retorno;  
    }   
  
    SetHeight public void (altura Integer) {   
        This.Height = altura;  
    }   
  
    GetImageFormat public String () {   
        return ImageFormat;  
    }   
  
    SetImageFormat public void (String ImageFormat) {   
        this.imageFormat = ImageFormat;  
    }   
  
    Cordas getCharType pública () {   
        retornar CharType;  
    }   
  
    SetCharType public void (String CharType) {   
        this.charType = CharType;  
    }   
  
    Pública ErrorCorrectionLevel getCorretionLevel () {   
        retornar corretionLevel;  
    }  
  
    setCorretionLevel public void (ErrorCorrectionLevel corretionLevel) {   
        this.corretionLevel = corretionLevel;  
    }   
  
    Integer getMargin pública () {   
        margem de retorno;  
    }   
  
    SetMargin public void (margem Integer) {   
        this.margin = margem;  
    }   
  
    Públicas mapa <EncodeHintType, Object> getHits () {   
        encodeHits de regresso;  
    }   
  
    Vazios setHits públicos (Mapa <EncodeHintType, Object> hits) {   
        this.encodeHits = sucessos;  
    }   
  
}  

3. O código bidimensional resultante carregado para os FastDFS de interface

   @ApiOperation ( "código bidimensional adquiriu a URL") 
    @GetMapping ( "getCodeUrl") 
    packageUrlForLink público o resultado (@LoginUser (= isFull para true) SYSUSER User) { 
        Cadeia link = ""; 
        QRCodeUtils QRCode novas novas QRCodeUtils = (100,100); 
        qrcode. setMargin (1); 
        Cordas DEPTID = user.getDeptId (); 
        SysDept o dept = userService.findDeptById (DEPTID); 
        cadeia de conteúdo = "nome do departamento:" + dept.getDeptName (+) " \ r \ n Imprimir homem:" + usuário .getUsername () + "\ r \ n tempo de impressão:" + GTime.getLogTime (); 
        a imagem BufferedImage qrCode.getBufferedImage = (conteúdo); 
        o try { 
            // transmitido upload de imagens para os FastDFS: 
            ByteArrayOutputStream os outputStream novas novas = ByteArrayOutputStream ();
            ImageIO.write (imagem, "png", outputStream); 
            InputStream inputStream = novo ByteArrayInputStream (outputStream.toByteArray ()); 
       //调用FastDFS中的接口将数据流保存到服务器返回图片地址 StorePath StorePath = storageClient.uploadImageAndCrtThumbImage (inputStream, InputStream.available (), "PNG", nula); link = "http: //". + fileServerProperties.getFdfs () getWebUrl () + "/" + storePath.getFullPath (); } catch (IOException ex) { ex.printStackTrace (); } Map <String, Object> Modelo = new HashMap <> (); model.put ( "imgStr", link); retorno Result.succeed (modelo); }

4. FastDFS arquivo de configuração para definir o tamanho das miniaturas

fdfs: 
  soTimeout: 1500 
  ConnectTimeOut: 1000 
  rastreador-List: ip:端口
  polegar-imagem: 
    largura: 100 
    altura: 100

  

Acho que você gosta

Origin www.cnblogs.com/petrolero/p/12539763.html
Recomendado
Clasificación