如何在HTTP响应体(使用Spark)中发送QR码的PNG?

 摩奇甜品 发布于 2023-01-11 10:35

我想生成QR码图像,将其转换为PNG并将其作为HTTP响应返回给我的客户端.

为了生成QR码我使用ZXing.我已经通过使用FileOutputStreamwith 编写了测试转换部分MatrixToImageWriter.writeToStream(...).这就像一个魅力.

我目前使用的Web框架是Spark(版本1.1.1).handle(...)-method 的返回被设置为响应主体.我在这做错了什么?

使用当前的解决方案,我The image "http://localhost:4567/qrcode" cannot be displayed because it contains errors在使用Firefox执行GET请求时获得.

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

import static spark.Spark.get;
import spark.Request;
import spark.Response;
import spark.Route;

import com.google.gson.Gson;

import com.google.common.io.BaseEncoding;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class App {
    public static void main(String[] args) {
        get(new Route("/qrcode") {

            @Override
            public Object handle(Request request, Response response) {
                // Test data
                QrData data = new QrData("test");

                // Data is wrapped in JSON
                String json = new Gson().toJson(data);

                // Transform JSON to QR-code PNG byte string
                String qrString = "";
                try {
                    qrString = generatePngQrCode(json);
                } catch (Exception e) {
                    e.printStackTrace();
                } 

                // Set response parameters
                response.type("image/png");
                response.status(200);

                // Return response body
                return qrString;
            }
        });
    }

    public String generatePngQrCode(String content) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        // ZXing QR-code encoding
        BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, 400, 400);

        // Convert to PNG image and write to stream
        MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream);

        // Encode to Base 64  
        return BaseEncoding.base64().encode(outputStream.toByteArray());
    }
}

thouliha.. 14

刚刚经历过这个.您可以使用以下代码编写任何文件/二进制数据/输出流:

byte[] bytes = Files.readAllBytes(Paths.get(filePath));         
HttpServletResponse raw = res.raw();

raw.getOutputStream().write(bytes);
raw.getOutputStream().flush();
raw.getOutputStream().close();


return res.raw();

你真的应该刷新并关闭输出流吗?打开它的人应该关闭它.如果这是不同的,你能解释一下原因吗? (3认同)

为什么不返回“ raw”,因为您已经拥有它了? (2认同)

那响应头呢? (2认同)


Brett Okken.. 7

使用response.getRaw获取应该用于将PNG写入的OutputStream(使用MatrixToImageWriter).

2 个回答
  • 刚刚经历过这个.您可以使用以下代码编写任何文件/二进制数据/输出流:

    byte[] bytes = Files.readAllBytes(Paths.get(filePath));         
    HttpServletResponse raw = res.raw();
    
    raw.getOutputStream().write(bytes);
    raw.getOutputStream().flush();
    raw.getOutputStream().close();
    
    
    return res.raw();
    

    2023-01-11 10:38 回答
  • 使用response.getRaw获取应该用于将PNG写入的OutputStream(使用MatrixToImageWriter).

    2023-01-11 10:38 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有