java生成二维码 直接返回

html :<img id="reCode"  src="127.0.0.1/reCode"/>

也可以 <img id="reCode" >  js:  $("#reCode").attr("src","127.0.0.1/doctor/reCode");

以下是java  部分

pom.xml:

<dependency>

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

RecodeUtil : 自己建的工具类 ,只需要下面两个方法。

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

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Hashtable;
public static void creatRrCode(String contents, int width, int height,HttpServletResponse response) {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints); // 1、读取文件转换为字节数组
//            ByteArrayOutputStream out = new ByteArrayOutputStream();
            BufferedImage image = toBufferedImage(bitMatrix);
            //转换成png格式的IO流
            ImageIO.write(image, "png", response.getOutputStream());
//            byte[] bytes = out.toByteArray();
//            // 2、将字节数组转为二进制
//            BASE64Encoder encoder = new BASE64Encoder();
//            binary = encoder.encodeBuffer(bytes).trim();
        } catch (WriterException e) { // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
/**
 * image流数据处理
 *
 * @author ianly
 */
public static BufferedImage toBufferedImage(BitMatrix matrix) {
    int width = matrix.getWidth();
    int height = matrix.getHeight();
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
        }
    }
    return image;
}

controller层:

@RequestMapping("reCode")
public void reCode(HttpServletResponse response){
    QrCodeUtils.creatRrCode("https://blog.csdn.net/ianly123", 200,200,response);
}

扫描二维码关注公众号,回复: 4588240 查看本文章

注意 :我是改的别人的方法,我习惯这样做,再网上找一个差不多的教程,然后改动,比如本来的方法是要返回一个string

我要的是直接返回想展示动态验证码一样 ,就直接写出到

HttpServletResponse

就可以了,要是些到本地,就把输出流改成你的文件流好了。

类似于下面,当然我并没有实践,因为懒 哈哈哈,不过直接输出页面 上面的可以满足。

Path file=new File("D:/img.png").toPath();
            MatrixToImageWriter.writeToPath(bm, format, file);

猜你喜欢

转载自blog.csdn.net/somdip/article/details/84561965