Issue
I am trying to modify the following method so that it returns byte[]
(byte array) instead of BufferedImage
. I can also use another implementation that returns byte[]
, but that implementation is not configurable like the following. So, how can I make this method to return byte[]
instead of BufferedImage
?
public static BufferedImage getQRCode(String targetUrl, int width,
int height) {
Hashtable<EncodeHintType, Object> hintMap = new Hashtable<>();
hintMap.put(EncodeHintType.ERROR_CORRECTION,
ErrorCorrectionLevel.L);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix byteMatrix = qrCodeWriter.encode(targetUrl,
BarcodeFormat.QR_CODE, width, height, hintMap);
int CrunchifyWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(CrunchifyWidth,
CrunchifyWidth, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth);
graphics.setColor(Color.BLACK);
for (int i = 0; i < CrunchifyWidth; i++) {
for (int j = 0; j < CrunchifyWidth; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
return image;
}
Solution
You'll need to use something like ByteArrayOutputStream
public static byte[] toByteArray(BufferedImage bi, String format)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, format, baos);
byte[] bytes = baos.toByteArray();
return bytes;
Ref: https://mkyong.com/java/how-to-convert-bufferedimage-to-byte-in-java/ }
Answered By - Fernando Vaz
Answer Checked By - Katrina (JavaFixing Volunteer)