Java获取图片传到前端,生成二维码给前端

可以将本地图片导入然后传到前端,也可以生成一个随意长度的二维码保存到本地,也可以传到前端,可以直接通过地址栏访问。要记得导入相关pom依赖包。

获取本地图片传到前端

    /**
     * @param
     * @paramm param
     * @功能描述  传图片
     */
    @GetMapping("/GenerateCode")
    public voidGenerateCode(HttpServletRequest request, HttpServletResponse response) {
        
        //读取文件   在用BufferedImage 读取
        File file = new File("H:\\IMAGEA\\qrcode_test.png");
        BufferedImage bu = null;
        try {
            bu = ImageIO.read(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

      //传到浏览器上
       try {
            ImageIO.write( bu, "PNG", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

}

生成二维码传到前端


    @GetMapping("/GenerateCode1")
    public void getCode(HttpServletRequest request, HttpServletResponse response) {
        // 二维码内容
        String url = "https://www.baidu.com/";
        // 生成二维码并指定宽高
        BufferedImage generate = QrCodeUtil.generate(url, 300, 300);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(generate, "jpg", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

生成二维码保存到本地后在传到前端

    /**
     * @param
     * @paramm param
     * @功能描述 二维码
     */
    @GetMapping("/GenerateCode")
    public Result GenerateCode(HttpServletRequest request, HttpServletResponse response) {
        String content = "http://www.baidu.com";//这里content为二维码数据。为地址将直接访问,为text将直接解析
        int width = 200; // 图像宽度
        int height = 200; // 图像高度
        String format = "png";// 图像类型
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 4);//设置二维码边的空度,非负数,默认值为4。
        BitMatrix bitMatrix = null;// 生成矩阵
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        
        //MatrixToImageWriter提供多种方式输出二维码,并同时提供二维码其他信息配置的重载方法
        try {
            MatrixToImageWriter.writeToFile(bitMatrix, format, new File("H:\\IMAGEA\\qrcode_test.png"));// 输出图像
        } catch (IOException e) {
            e.printStackTrace();
        }


        //读取文件   在用BufferedImage 读取
        File file = new File("H:\\IMAGEA\\qrcode_test.png");`在这里插入代码片`
        BufferedImage bu = null;
        try {
            bu = ImageIO.read(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //传到浏览器上
        try {
            ImageIO.write( bu, "PNG", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

       return Result.ok("H:\\IMAGEA\\qrcode_test.png");
    }

二维码相关依赖

pom文件

        <!-- 导入zxing的依赖 -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.2.1</version>
        </dependency>
        
        //hutool工具包
     <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.0.7</version>
        </dependency>

MatrixToImageConfig
package com.example.md.util;


public final class MatrixToImageConfig
{
    public static final int BLACK = -16777216;
    public static final int WHITE = -1;
    private final int onColor;
    private final int offColor;

    public MatrixToImageConfig()
    {
        this(-16777216, -1);
    }

    public MatrixToImageConfig(int onColor, int offColor)
    {
        this.onColor = onColor;
        this.offColor = offColor;
    }

    public int getPixelOnColor()
    {
        return this.onColor;
    }

    public int getPixelOffColor()
    {
        return this.offColor;
    }

    int getBufferedImageColorModel()
    {
        if ((this.onColor == -16777216) && (this.offColor == -1)) {
            return 12;
        }
        if ((hasTransparency(this.onColor)) || (hasTransparency(this.offColor))) {
            return 2;
        }
        return 1;
    }

    private static boolean hasTransparency(int argb)
    {
        return (argb & 0xFF000000) != -16777216;
    }
}
MatrixToImageWriter
package com.example.md.util;


import com.google.zxing.common.BitMatrix;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import javax.imageio.ImageIO;

public final class MatrixToImageWriter
{
    private static final MatrixToImageConfig DEFAULT_CONFIG = new MatrixToImageConfig();

    public static BufferedImage toBufferedImage(BitMatrix matrix)
    {
        return toBufferedImage(matrix, DEFAULT_CONFIG);
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix, MatrixToImageConfig config)
    {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, config.getBufferedImageColorModel());
        int onColor = config.getPixelOnColor();
        int offColor = config.getPixelOffColor();
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? onColor : offColor);
            }
        }
        return image;
    }

    @Deprecated
    public static void writeToFile(BitMatrix matrix, String format, File file)
            throws IOException
    {
        writeToPath(matrix, format, file.toPath());
    }

    public static void writeToPath(BitMatrix matrix, String format, Path file)
            throws IOException
    {
        writeToPath(matrix, format, file, DEFAULT_CONFIG);
    }

    @Deprecated
    public static void writeToFile(BitMatrix matrix, String format, File file, MatrixToImageConfig config)
            throws IOException
    {
        writeToPath(matrix, format, file.toPath(), config);
    }

    public static void writeToPath(BitMatrix matrix, String format, Path file, MatrixToImageConfig config)
            throws IOException
    {
        BufferedImage image = toBufferedImage(matrix, config);
        if (!ImageIO.write(image, format, file.toFile())) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
            throws IOException
    {
        writeToStream(matrix, format, stream, DEFAULT_CONFIG);
    }

    public static void writeToStream(BitMatrix matrix, String format, OutputStream stream, MatrixToImageConfig config)
            throws IOException
    {
        BufferedImage image = toBufferedImage(matrix, config);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }
}

效果

在这里插入图片描述

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要将Java生成的二维码展示到前端,可以通过以下步骤实现: 1. 使用Java生成二维码图片,例如zxing或Qrcode。 2. 将生成的二维码图片转换为Base64编码格式,可以使用Java库将图片转换为Base64字符串。 3. 在Java中将Base64字符串返回给前端,可以使用Spring MVC或其他Web框架将Base64字符串作为响应返回给前端。 4. 在前端中使用JavaScript解码Base64字符串,并将其展示为图片。 以下是一个示例Java代码,用于生成二维码并将其返回给前端: ``` @RequestMapping(value = "/qrcode", produces = MediaType.IMAGE_PNG_VALUE) @ResponseBody public ResponseEntity<byte[]> generateQRCode(@RequestParam("text") String text) throws Exception { // 生成二维码图片 QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, 200, 200); // 将二维码图片转换为BufferedImage BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix); // 将BufferedImage转换为Base64字符串 ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "png", baos); byte[] bytes = baos.toByteArray(); String base64Encoded = Base64.getEncoder().encodeToString(bytes); // 将Base64字符串返回给前端 final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_PNG); return new ResponseEntity<>(Base64.getDecoder().decode(base64Encoded), headers, HttpStatus.CREATED); } ``` 在前端中,可以使用以下JavaScript代码将Base64字符串转换为图片并展示: ``` // 将Base64字符串转换为图片并展示 var img = new Image(); img.src = 'data:image/png;base64,' + base64Encoded; document.getElementById('qrcode').appendChild(img); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黎明之道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值