QRcode使用zxing 生成二维码并上传到阿里云OSS对象存储服务器

最近接到一个新需求,在安卓和ios客户端有一个一键分享生成二维码然后让用户去注册。

这里用的是谷歌的工具包====== 《zxing》

maven依赖


        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>
      
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.0</version>
        </dependency>

逻辑分析:这里主要根据公司的具体业务来定

首先我自己定义了两个工具类一个用来下载阿里OSS服务器上的图片《代码如下》

package com.ruideng.edp.common.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Author: ZhiHuiAn
 * @Date: 2019/4/18 11:25
 * 获取阿里云服务器上的头像工具类
 */
public class AliYunOSSGetImageUtils {

    /**
     * 获取远程服务器上的头像
     * 然后保存到本地中
     *
     * @param imageUrl
     * @throws IOException
     */
    public static BufferedImage download(String imageUrl) throws IOException {

        //逻辑分析:分两种情况
        //          1.用户有头像的情况下,并且是阿里云服务器上的头像,那么就下载下来保存到本地,然后再读取出来,返回一个图片对象。
        //          2.如果用户没有头像,那就默认本地下载E单配Logo当做头像。
        try {
            if (imageUrl.equals("C://logo/logo.png")) {
                BufferedImage image = ImageIO.read(new File(imageUrl));
                return image;
            } else if (imageUrl.substring(0, 19).equals("http://yingkd-image")) {
                URL url = new URL(imageUrl);
                HttpURLConnection urlConnection = null;
                try {
                    urlConnection = (HttpURLConnection) url.openConnection();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                InputStream inputStream = null;
                OutputStream outputStream = null;
                try {
                    inputStream = urlConnection.getInputStream();
                    outputStream = new FileOutputStream(new File("c:/erweimalogo/" + imageUrl.substring(imageUrl.lastIndexOf("/") + 1)));  //保存图片,名称是截取后阿里云地址的名称
                    int num = 0;
                    while ((num = inputStream.read()) != -1) {
                        outputStream.write(num);
                        outputStream.flush();
                    }
                    //上面的操作是将图片从阿里云服务器上读取到头像然后保存到本地
                    //接下来还需要将图片从本地读取出来
                    BufferedImage headImage = ImageIO.read(new File("c:/erweimalogo/" + imageUrl.substring(imageUrl.lastIndexOf("/") + 1)));
                    return headImage;
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (inputStream != null && outputStream != null) {
                        outputStream.close();
                        inputStream.close();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

一个是用来生成自定义二维码Logo图片的工具类《代码如下》

package com.ruideng.edp.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * @Author: ZhiHuiAn
 * @Date: 2019/4/18 10:53
 * 生成二维码工具类
 */
public class QRCodeUtils {

//    public static void createQRCode(String headImagrUrl, String content, int w, int h) throws Exception {
//
//        // 1.根据内容参数生成二维码
//        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
//        BitMatrix encode = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, w, h);
//
//        // 2.创建图片
//        BufferedImage erWeiMaImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
//        for (int x = 0; x < w; x++) {
//            for (int y = 0; y < h; y++) {
//                if (encode.get(x, y)) {
//                    erWeiMaImage.setRGB(x, y, 0x000000);
//                } else {
//                    erWeiMaImage.setRGB(x, y, 0xffffff);
//                }
//            }
//        }
//
//        // 1.读取用户的头像
        BufferedImage logoImage = ImageIO.read(new File(headImagrUrl));
//        BufferedImage logoImage = AliYunOSSGetImageUtils.download(headImagrUrl);
//
//        //设置用户头像的大小
//        int w2 = 30;
//        int h2 = 30;
//        Image image2 = logoImage.getScaledInstance(w2, h2, Image.SCALE_FAST);
//        // 2.绘制logo
//        Graphics graphics = erWeiMaImage.getGraphics(); //根据二维码图片绘制,将用户头像加入到二维码中
//
//        int logoW = (w - w2) / 2;
//        int logoH = (h - h2) / 2;
//        graphics.drawImage(image2, logoW, logoH, null);
//
//        // 3.写出到本地
//        ImageIO.write(erWeiMaImage, "png", new File("e:/code/" + headImagrUrl.substring(headImagrUrl.lastIndexOf("/") + 1)));
//
//    }

    /**
     * 生成头像二维码保存到本地
     * 并返回头像二维码地址
     * @param headImagrUrl
     * @param content
     * @param w
     * @param h
     * @throws Exception
     */
    public static String createQRCode2(String headImagrUrl, String content, int w, int h) throws Exception {

        // 1.根据内容参数生成二维码
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        BitMatrix encode = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, w, h);

        // 2.创建图片
        BufferedImage erWeiMaImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                if (encode.get(x, y)) {
                    erWeiMaImage.setRGB(x, y, 0x000000);
                } else {
                    erWeiMaImage.setRGB(x, y, 0xffffff);
                }
            }
        }
        //获取头像
        BufferedImage logoImage = AliYunOSSGetImageUtils.download(headImagrUrl);

        //设置用户头像的大小
        int w2 = 60;
        int h2 = 60;
        Image image2 = logoImage.getScaledInstance(w2, h2, Image.SCALE_FAST);
        // 2.绘制logo
        Graphics graphics = erWeiMaImage.getGraphics(); //根据二维码图片绘制,将用户头像加入到二维码中

        int logoW = (w - w2) / 2;
        int logoH = (h - h2) / 2;
        graphics.drawImage(image2, logoW, logoH, null);

        // 3.写出到本地
        ImageIO.write(erWeiMaImage, "png", new File("c:/erweimalogo/" + headImagrUrl.substring(headImagrUrl.lastIndexOf("/") + 1)));

        return "c:/erweimalogo/"+ headImagrUrl.substring(headImagrUrl.lastIndexOf("/") + 1);

    }
}

具体逻辑》》》》

1. IOS和安卓端传入用户ID,根据用户ID到user表中查询用户的头像地址(用户保存在阿里oss服务器的头像链接)

2.调用上面的工具类,根据传入的头像地址有两种情况,一:如果用户的头像地址是空或者不是以阿里服务器开头的前缀(http://yingkd-image.oss-cn-hangzhou.aliyuncs.com/xxx.png)那么就去本地下载公司的Logo。

二:如果用户有自定义头像,那就去阿里OSS服务器上下载《我们公司的图片统一都是存储在阿里OSS服务器上》,因为是远程下载这里需要使用  import java.net.URL 类 和  import java.net.HttpURLConnection 两个类 然后使用IO流将图片保存到本地

最后再使用 ImageIO.read   读取图片,最后返回出去。

3. controller中调用二维码工具类生成带有头像的二维码

4.上传到阿里云OSS服务器,然后返回二维码的URL给  安卓/IOS

使用Java生成二维码,你可以依赖Google的zxing类库。这个类库提供了二维码生成的策略,你只需要调用它的API来生成二维码对象。首先,你需要准备以下信息:字符串内容、二维码的宽度和高度、字符集、颜色、外边距和纠错等级等。在zxing包中的MultiFormatWriter类是生成二维码的核心工具类,你可以使用它的encode方法将要封装的字符串内容转化为二维码对象。 以下是生成二维码的步骤: 步骤1:导入zxing类库,并创建MultiFormatWriter对象。 步骤2:创建一个Map集合,用于存储参数,包括字符集和二维码类型。 步骤3:调用MultiFormatWriter对象的encode方法,传入字符串内容和参数Map,将其转化为二维码对象。 步骤4:将二维码对象写入磁盘或输出流,以保存或展示二维码。 下面是一个简单的Java代码示例,演示了如何使用zxing生成二维码: ``` import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class QRCodeGenerator { public static void main(String[] args) { String content = "Hello, World!"; // 二维码内容 int width = 300; // 二维码宽度 int height = 300; // 二维码高度 String charset = "UTF-8"; // 字符集 // 设置参数 Map<EncodeHintType, Object> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, charset); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 纠错等级为高 try { // 生成二维码 BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); // 创建BufferedImage对象,并设置颜色模式 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); image.createGraphics(); // 设置二维码颜色 Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, width, height); graphics.setColor(Color.BLACK); // 绘制二维码 for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (matrix.get(i, j)) { graphics.fillRect(i, j, 1, 1); } } } // 保存二维码到磁盘 ImageIO.write(image, "png", new File("qrcode.png")); System.out.println("二维码已生成并保存到qrcode.png文件中。"); } catch (Exception e) { e.printStackTrace(); } } } ``` 这段代码将生成一个内容为"Hello, World!"的二维码,并保存到名为qrcode.png的文件中。你可以根据自己的需求调整代码中的参数,来生成不同样式的二维码。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [Java利用zxing生成二维码](https://blog.csdn.net/qq_43598138/article/details/105444641)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [Java利用Zxing生成二维码的简单实例](https://download.csdn.net/download/weixin_38598703/12794633)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值