Convert QRCode to Image. Java
Using the following libraries: qrgen-1.2, zxing-core-1.7 and zxing-j2se-1.7 I generated QRCode:
ByteArrayOutputStream out = QRCode.from(output.toString()).withSize(1000,1000).to(ImageType.PNG).stream();
FileOutputStream fout = new FileOutputStream(new File("D:\\QR_Code.JPG"));
fout.write(out.toByteArray());
fout.flush();
fout.close();
What I intend to do with this is send the code to the method that accepts the java.awt.Image. How can I convert an instance of the QRCode class to an instance of the Image class without creating the QRCode.JPG in the first place? As I can see, this library does not provide users with methods that can accomplish this, so what is even possible? Maybe I can convert the stream to an image?
+3
source to share
1 answer
Just write qr code to byte array output stream, then use byte array on stream to create BufferedImage
.
import net.glxn.qrgen.QRCode;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
public static BufferedImage generate() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
QRCode.from("http://www.stackoverflow.com").writeTo(baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
return ImageIO.read(bais);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
0
source to share