java生成二维码并用fastdfs上传文件返回图片地址

建立生成二维码的功能
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>

写生成二维码的工具类:

package com.jinkao.distribution.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.IOException;
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());
                }
            }
            //去掉白边
            
            
            
            
            
           // bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);  
        } 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;  
    }  
  
}  


然后开发关于fastdfs的上传文件的方法,可以看一下这个地址:
springboot项目中fastdfs上传文件开发

这里我们用比如说一个链接来生成一个二维码,在上传到fstdfs上,来返回一个可以直接访问二维码链接的地址:
通用工具类:

 public    String  packageUrlForLink(String url){

        String link="";
        QRCodeUtils qrCode=new QRCodeUtils(400,400);
        qrCode.setMargin(1);
        BufferedImage image=qrCode.getBufferedImage(url);
        try {
           //以流的方式讲图片上传到fastdfs上:
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", outputStream);
            InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
       //commonFileUtil.upfileImage()的方式其实是调用的
   // fastFileStorageClient.uploadImageAndCrtThumbImage(is, size, fileExtName, metaData)的方法
            link= commonFileUtil.upfileImage(inputStream,inputStream.available(),"png",null);
        }catch (IOException ex){
            ex.printStackTrace();
        }
        return  link;
    };

还有就是fastdfs的配置文件 还要对缩略图的大小进行设置,不然会报错‘!!!!!

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

在拿一个链接去生成二维码的时候,直接就返回了一个可以直接访问的二维码图片的链接了

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很抱歉,我是一个语言模型AI,无法生成完整的Java代码。但是,我可以提供一些参考代码: ``` import java.io.File; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.csource.common.NameValuePair; import org.csource.fastdfs.ClientGlobal; import org.csource.fastdfs.StorageClient1; import org.csource.fastdfs.StorageServer; import org.csource.fastdfs.TrackerClient; import org.csource.fastdfs.TrackerServer; public class FastDFSClient { private static TrackerClient trackerClient; private static TrackerServer trackerServer; private static StorageServer storageServer; private static StorageClient1 storageClient; static { try { String conf = FastDFSClient.class.getClassLoader().getResource("fdfs_client.conf").getFile(); ClientGlobal.init(conf); trackerClient = new TrackerClient(); trackerServer = trackerClient.getConnection(); storageServer = null; storageClient = new StorageClient1(trackerServer, storageServer); } catch (Exception e) { e.printStackTrace(); } } /** * 上传文件 * @param file 文件对象 * @param fileName 文件名 * @return 返回文件在FastDFS中的路径 */ public static String[] upload(File file, String fileName) { try { NameValuePair[] metaList = new NameValuePair[1]; metaList[0] = new NameValuePair("fileName", fileName); return storageClient.upload_file(file.getAbsolutePath(), FileUtils.getExtension(file.getName()), metaList); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 上传文件 * @param inputStream 文件输入流 * @param fileName 文件名 * @return 返回文件在FastDFS中的路径 */ public static String[] upload(InputStream inputStream, String fileName) { try { byte[] bytes = IOUtils.toByteArray(inputStream); NameValuePair[] metaList = new NameValuePair[1]; metaList[0] = new NameValuePair("fileName", fileName); return storageClient.upload_file(bytes, FileUtils.getExtension(fileName), metaList); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 删除文件 * @param filePath 文件路径 * @return 成功返回0,失败返回其它 */ public static int delete(String filePath) { try { return storageClient.delete_file(filePath); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return -1; } } ``` 以上代码是一个 FastDFS 的工具类,封装了上传和删除文件的方法。其中,上传文件的方法提供了两种方式,分别是通过文件对象和输入流。在这里,你可以根据你的实际需求进行选择。由于 FastDFS 上传文件时需要指定文件的元数据,因此在上传文件时,我们使用一个 NameValuePair 数组来存储元数据。在这里,我们只指定了一个文件名作为元数据。如果你需要添加其他元数据,可以根据需要进行修改。 在使用这个工具类时,你需要在 classpath 路径下添加一个名为 fdfs_client.conf 的配置文件,这个文件包含了 FastDFS 的配置信息。你可以在 FastDFS 的官网上下载最新的配置文件,并将其放在 classpath 路径下。如果你不知道如何配置这个文件,请参考 FastDFS 的官方文档。 以下是使用这个工具类上传文件的示例代码: ``` File file = new File("/path/to/your/video.mp4"); String fileName = "video.mp4"; String[] result = FastDFSClient.upload(file, fileName); if (result != null) { String filePath = result[0] + "/" + result[1]; System.out.println("File path: " + filePath); } else { System.out.println("Upload file failed."); } ``` 在这个示例中,我们指定了一个名为 video.mp4 的文件,并将其上传FastDFS 中。如果上传成功,我们就可以得到文件在 FastDFS 中的路径。在这里,我们将文件路径拼接成了一个字符串,其中 result[0] 是文件所在的组名,result[1] 是文件的路径名。你可以根据需要对这个字符串进行进一步处理。 希望这些代码可以对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值