普通二维码生成,并上传七牛云

本文介绍了一种使用Java实现的二维码生成和解析方法,利用Google ZXing库和七牛云存储服务,详细阐述了如何创建二维码图像并将其上传至云端。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pom.xm依赖

<!-- 二维码生成工具 -->
		<dependency>
		    <groupId>com.google.code.gson</groupId>
		    <artifactId>gson</artifactId>
		</dependency>
		<dependency>
		    <groupId>com.google.zxing</groupId>
		    <artifactId>core</artifactId>
		    <version>3.1.0</version>
		</dependency>
		<dependency>
		    <groupId>com.google.zxing</groupId>
		    <artifactId>javase</artifactId>
		    <version>3.0.0</version>
		</dependency>
		<!-- 七牛云 -->
		<dependency>
		    <groupId>com.qiniu</groupId>
		    <artifactId>qiniu-java-sdk</artifactId>
		    <version>7.2.18</version>
		</dependency>

创建QRCodeUtil.java二维码生成工具类

package org.ewhl.common.utils;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

public class QRCodeUtil {
	//二维码颜色  
    private static final int BLACK = 0xFF000000;  
    //二维码颜色  
    private static final int WHITE = 0xFFFFFFFF;  
  
    /*public static void main(String[] args) throws Exception {
    	zxingCodeCreate("http://www.baidu.com", 300, 300, "D:/qrcode.jpg", "jpg");
    	zxingCodeAnalyze("D:/qrcode.jpg");
	}*/
    /**  生成二维码
     * @param text    二维码内容
     * @param width    二维码宽 
     * @param height    二维码高 
     * @param outPutPath    二维码生成保存路径 
     * @param imageType     二维码生成格式 
     */  
    public static Map<String,Object> zxingCodeCreate(String text, int width, int height){  
        Map<EncodeHintType, String> his = new HashMap<EncodeHintType, String>();  
        //设置编码字符集  
        his.put(EncodeHintType.CHARACTER_SET, "utf-8");  
        try {  
            //1、生成二维码  
            BitMatrix encode = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, his);  
            //2、获取二维码宽高  
            int codeWidth = encode.getWidth();  
            int codeHeight = encode.getHeight();  
            //3、将二维码放入缓冲流  
            BufferedImage image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);  
            for (int i = 0; i < codeWidth; i++) {  
                for (int j = 0; j < codeHeight; j++) {  
                    //4、循环将二维码内容定入图片  
                    image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);  
                }  
            } 
            // 自定义内容
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", os);  
            InputStream is = new ByteArrayInputStream(os.toByteArray());  
            Map<String,Object> retMap = UploadUtils.upload(is);
            return retMap;
            /*//存储到本地
            File outPutImage = new File(outPutPath);  
            if(!outPutImage.exists())  
            	//outPutImage.createNewFile();  
            //5、将二维码写入图片  
            ImageIO.write(image, imageType, outPutImage);  */
        } catch (WriterException e) {  
            e.printStackTrace();  
            System.out.println("二维码生成失败");  
        } catch (IOException e) {  
            e.printStackTrace();  
            System.out.println("生成二维码图片失败");  
        }
		return null;  
    }  
      
    /** 二维码解析 
     * @param analyzePath    二维码路径 
     * @return 
     * @throws IOException 
     */  
    @SuppressWarnings({ "rawtypes", "unchecked" })  
    public static String zxingCodeAnalyze(String analyzePath) throws Exception{  
        MultiFormatReader formatReader = new MultiFormatReader();  
        String resultStr = null;  
        try {  
            File file = new File(analyzePath);  
            if (!file.exists())  
            {  
                return "二维码不存在";  
            }  
            BufferedImage image = ImageIO.read(file);  
            LuminanceSource source = new BufferedImageLuminanceSource(image);  
            Binarizer binarizer = new HybridBinarizer(source);    
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);  
            Map hints = new HashMap();  
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");  
            Result result = formatReader.decode(binaryBitmap, hints); 
            resultStr = result.getText();
        } catch (NotFoundException e) {  
            e.printStackTrace();  
        }    
        System.out.println(resultStr);
        return resultStr;  
    }  
      
}

创建上传七牛云工具类UploadUtils.java

package org.ewhl.common.utils;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
public class UploadUtils {

public static Map<String,Object> upload(InputStream stream) {

	Map<String,Object> retMap = new HashMap<String,Object>();
	// 构造一个带指定Zone对象的配置类
	Configuration cfg = new Configuration(Zone.zone0());
	// ...其他参数参考类注释
	UploadManager uploadManager = new UploadManager(cfg);
	// ...生成上传凭证,然后准备上传
	String accessKey = "七牛云上传凭证";
	String secretKey = "七牛云上传凭证";
	String bucket = "项目名称";
	// 默认不指定key的情况下,以文件内容的hash值作为文件名
	String key = UUID.randomUUID().toString().replaceAll("\\-", "");
	try {
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);
		try {
			Response response = uploadManager.put(stream, key, upToken, null, null);
			// 解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			retMap.put("url","http://qiniu.micromove.cn/"+putRet.key);
			retMap.put("hash",putRet.hash);
			/*System.out.println(putRet.key);
			System.out.println(putRet.hash);*/
		} catch (QiniuException ex) {
			Response r = ex.response;
			System.err.println(r.toString());
			try {
				System.err.println(r.bodyString());
			} catch (QiniuException ex2) {
				ex2.printStackTrace();
			}
		}
	} catch (Exception ex) {
		ex.printStackTrace();
	}
	return retMap;
}

}
测试方法

public Map<String,Object> generateQRCode(String token){
	Map<String,Object> retMap = new HashMap<String,Object>();
	//七牛云的方法会返回一个map类型的值,所以要注意接收类型
	retMap = QRCodeUtil.zxingCodeCreate(user.getInvideCode(), 100, 100);
	
}

微笑面对每一天,每一个坑都是以后的人生经验,每一次痛苦的经历都是宝贵的财富!趁年轻,还承担得起,多经历一些,不要等到承受不了的那天。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值