Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

java - How can I send a PNG of a QR-code in a HTTP response body (with Spark)?

I want to generate a QR-code image, convert it to PNG and return it as a HTTP response to my client.

To generate the QR-code I use ZXing. I already tested the conversion part by writing using a FileOutputStream with MatrixToImageWriter.writeToStream(...). That works like a charm.

The web framework I am currently using is Spark (Version 1.1.1). The return of the handle(...)-method is set as the response body. What am I doing wrong here?

With the current solution I get The image "http://localhost:4567/qrcode" cannot be displayed because it contains errors when performing the GET-request with Firefox.

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());
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just went through this. You can write any file/binary data/output stream using the following code:

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

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


return res.raw();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...