I have a webserver that creates a QRcode. During the process, I get a BarcodeQRCode object from which I can get the image (.getImage()).
I am not sure how I can send back to the client this image. I don't want to save it in a file but just send back data in response to JSON request. For information, I have a similar case from which I get a PDF file that works great:
private ByteArrayRepresentation getPdf(String templatePath, JSONObject json) throws IOException, DocumentException, WriterException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(..., baos);
// setup PDF content...
return new ByteArrayRepresentation(baos.toByteArray(), MediaType.APPLICATION_PDF);
}
Is there a way to do something similar more or less like:
private ByteArrayRepresentation getImage(JSONObject json) throws IOException, DocumentException, WriterException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Image qrCode = getQRCode(json); /// return the BarcodeQRCode.getImage()
ImageIO.write(qrCode, "png", baos);
return new ByteArrayRepresentation(baos.toByteArray(), MediaType.IMAGE_PNG);
}
But this is not working. I get: argument mismatch; Image cannot be converted to RenderedImage.
EDIT
No compilation error after modification as proposed below. However, the returned image seems to be empty (or at least not normal). I put the error-free code if anyone has an idea what is wrong:
@Post("json")
public ByteArrayRepresentation accept(JsonRepresentation entity) throws IOException, DocumentException, WriterException {
JSONObject json = entity.getJsonObject();
return createQR(json);
}
private ByteArrayRepresentation createQR(JSONObject json) throws IOException, DocumentException, WriterException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Image codeQR = getQRCode(json);
BufferedImage buffImg = new BufferedImage(codeQR.getWidth(null), codeQR.getHeight(null), BufferedImage.TYPE_4BYTE_ABGR);
buffImg.getGraphics().drawImage(codeQR, 0, 0, null);
return new ByteArrayRepresentation(baos.toByteArray(), MediaType.IMAGE_PNG);
}
private Image getQRCode(JSONObject json) throws IOException, DocumentException, WriterException {
JSONObject url = json.getJSONObject("jsonUrl");
String urls = (String) url.get("url");
BarcodeQRCode barcode = new BarcodeQRCode(urls, 200, 200, null);
Image codeImage = barcode.createAwtImage(Color.BLACK, Color.WHITE);
return codeImage;
}