¿Debe devolver byte[] en lugar de BufferedImage en Java?
Estoy tratando de modificar el siguiente método para que devuelva byte[]
(matriz de bytes) en lugar de BufferedImage
. También puedo usar otra implementación que devuelva byte[]
, pero esa implementación no es configurable como la siguiente. Entonces, ¿cómo puedo hacer que este método devuelva byte[]
en lugar de BufferedImage
?
“`
public static BufferedImage getQRCode(String targetUrl, int width,
int height) {
Hashtable<EncodeHintType, Object> hintMap = new Hashtable<>();
<pre><code>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;
</code></pre>
}
“`
davy.ai
Para modificar el método anterior y devolver
byte[]
en lugar deBufferedImage
, podemos crear un objetoByteArrayOutputStream
y escribir el contenido deBufferedImage
en este flujo. Finalmente, podemos convertir el flujo en unbyte[]
utilizando el métodotoByteArray()
deByteArrayOutputStream
. Aquí está el código modificado:Aquí, hemos reemplazado
return image;
con el siguiente código:Aquí, estamos creando un objeto
ByteArrayOutputStream
llamadobaos
y escribiendo el contenido deBufferedImage
en él utilizando el métodoImageIO.write()
. Finalmente, estamos devolviendo elbyte[]
utilizando el métodobaos.toByteArray()
.</encodehinttype,>