Tips, Soluciones y Novedades en Tecnología

05/06/2023

Generando Imagen QR en Java



Google a creado varias APIS para facilitar el desarrollo de proyectos Java.

Cuando trabajamos con códigos de barras, código QR etc, tenemos que tener buenas librerías para que nos de soporte para generar estos formatos cifrados.



Ejemplos de usos son: (DNI trabajador, Código Universitario, etc), estos pueden ser imprimidos en fotocheck o carnets y con ellos se puede controlar muchos aspectos como Horarios de trabajos, fecha de ingreso, salida e identificación del mismo, en fin hay un sin números de usos para este tipo de cifrados.

A continuación vamos a generar un código QR en una imagen .PNG, le pasaremos un código a cifrar.

Primero tenemos que definir la deprencia a nuestro proyecto añadiendo la dependencia a pom.xml de nuestro proyecto, y si no utilizan maven lo pueden bajar diretamente el .jar (.jar) y agregarlo a la librería del proyecto.




 1
2
3
4
5
6
7
8
9
10
11

 <!-- Barcode image processing -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
</dependency>



El código en java para generar seria el siguiente.




 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

public static void main(String[] args) throws Exception {
generarImageQR("123456789", "png", "D:\\data\\imageQR.png");
}

private static void generarImageQR(String code, String TypeImage, String urlFile) throws Exception {
int size = 125;
String fileType = TypeImage;
File myFile = new File(urlFile);
try {
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix byteMatrix = qrCodeWriter.encode(code, BarcodeFormat.QR_CODE, size, size, 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);
}
}
}
ImageIO.write(image, fileType, myFile);
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}



Validando nuestra Imagen generada en : Read Online Image QR





Saludos cordiales.

0 comments:

Publicar un comentario