1. Soporte de la generación y análisis de código QRCode y Zxing QR;
2. QRCode genera códigos QR y admite agregar imágenes, de la siguiente manera:
paquete común; import java.awt.color; import java.awt.graphics2d; import java.awt.image; imagen java.awt.image.bufferedImage; import java.io.file; import java.io.ioexception; import java.util.hashmap; import java.util.map; import javax.imageio.image.image.image.image.imageio; import jp.sourceforge.qrcode.qrcodedecoder; import jp.sourceForge.qrcode.exception.DecodingFailedException; import com.google.zxing.BarcodeFormat;import com.google.zxing.Binarizer;import com.google.zxing.BinaryBitmap;import com.google.zxing.EncodeHintType;import com.google.zxing.LuminanceSource;import com.google.zxing.MultiFormatReader;import com.google.zxing.MultiFormatWriter;import com.google.zxing.notfoundException; import com.google.zxing.writerexception; import com.google.zxing.common.bitmatrix; import com.google.zxing.common.hybridbinarize; import com.swetake.util.qrcode; /** * Clase de herramienta de generación de códigos QR * @author nube * @data 2016-12-15 * qrcode */public class QrCodeUtil {// Qr Code Color private Static final int Black = 0xff000000; // Código QR Color privado estático final int white = 0xffffffff; /** * <span style = "font-size: 18px; font-weight: blaD;"> El método ZXing genera código Qr </span> * @param text <a href = "javaScript: void ();" rel = "externo nofollow"> Contenido de código QR </a>* @param ancho QR Ancho de código* @param Height Qr Código Código* @param OutputPath Qr Generación de código y Guardar ruta* @param imageType Qr Código de generación Format*/ public static void void zxingcreate (string text, int = new HashMap <EncodeHintType, String> (); // Establezca el personaje codificado establecer His.put (codeDintType.character_set, "UTF-8"); Prueba {// 1. Genere el código QR bitmatrix code = new MultiformAtWriter (). ENCODE (Text, BarCodeFormat.qr_code, Width, Height, His); // 2. Obtenga el ancho del código QR y la altura int codewidth = coden.getWidth (); int codeHeight = encode.getheight (); // 3. Coloque el código QR en la transmisión de BufferedImage BufferedMage = new BufferedImage (Codewidth, CodeHeight, BufferedImage.Type_int_Rgb); for (int i = 0; i <codewidth; i ++) {for (int j = 0; j <codeHeight; j ++) {// 4. Bucle para corregir el contenido del código QR en la imagen Image.setRGB (i, J, coden.get (i, j)? Black: White); }} Archivo outputImage = nuevo archivo (outputPath); // Si la imagen no existe, cree la imagen if (! OutputiMage.Exists ()) outputiMage.createNewFile (); // 5. Escriba el código QR en la imagen ImageIO.Write (Image, ImageType, OutputImage); } catch (WriterException e) {E.PrintStackTrace (); System.out.println ("Falló la generación de código QR"); } catch (ioException e) {E.PrintStackTrace (); System.out.println ("Cambiar la imagen del código QR fallido"); }}/** * <span style = "font-size: 18px; font-weight: blaD;"> Análisis de código QR </span> * @param Analyzepath Qr Code ruta * @return * @throws ioexception */@suppresswarnings ({"sincera de sincera", "desacelerado") público estatic zxingcodealze (string thypes) Multiformatreader formatReader = new MultiformAtreader (); Resultado del objeto = nulo; intente {archivo archivo = nuevo archivo (analzepath); if (! file.exists ()) {return "El código QR no existe"; } BufferedImage image = imageIO.read (archivo); Luminancesource Source = new Luminancesourceutil (imagen); Binarizer binarizer = new HybridBinarizer (fuente); BinaryBitMap BinaryBitMap = New BinaryBitMap (binarizer); Sugerencias de mapas = new HashMap (); hints.put (encodeHintType.character_set, "UTF-8"); resultado = formatReader.Decode (binaryBitMap, sugerencias); } catch (NotFoundException e) {E.PrintStackTrace (); } resultado de retorno; }/*** <span style = "font-size: 18px; font-weight: blaD;"> Qrcode genera código Qr </span>* @param Content Qr Code Content* @param imgpath Qr Code Generation ruta* @param Versión Qr Code Version* @Param es Flag si generar una imagen del logotro de logotro que no genera*/Public Static Voreid QrcCeat (CTART CONTENT (CTART CONTENTA (cadena (CTART CONTENTA CTAR (CTAR CTLAT CONTENTA (CTART CONTENTA (CTHAD imgpath, int versión, string logoPath) {try {qrcode qrcodeHandler = new qrcode (); // Establezca la tasa de decodificación de errores del código QR, opcional L (7%) m (15%) Q (25%) H (30%). Cuanto mayor sea la tasa de decodificación de errores, menos información se puede almacenar, pero menor será el requisito de la claridad del código QR QRCodeHandler.SetqrCodeErrorCorrect ('M'); // n representa el número, A representa el carácter AZ, y B representa otros caracteres QRCodeHandler.SetqrCodeEncodeMode ('B'); // La versión 1 es una matriz de 21*21, y por cada 1 aumento en la versión, los dos lados del código QR aumentan en 4; Entonces, la versión 7 es una matriz con 45*45; La versión más alta es 40, que es una matriz con 177*177 QRCodeHandler.setqrCodeversion (versión); // Calcule el tamaño según la versión int imgSize = 67 + 12 * (versión - 1); byte [] contentBytes = content.getBytes ("GB2312"); BufferedImage bufiMg = new BufferedImage (imgSize, imgSize, BufferedImage.Type_int_rgb); Graphics2d gs = bufimg.createGraphics (); Gs.SetBackground (color.white); Gs.ClearRect (0, 0, imgsize, imgSize); // establecer color de imagen> negro gs.setcolor (color.black); // Establecer el compensación para no establecer puede causar error de análisis int pixoff = 2; // Salida Contenido> Código QR if (ContentBytes.length> 0 && ContentBytes.length <130) {boolean [] [] codeOut = qrcodeHandler.calqrcode (contentBytes); for (int i = 0; i <codeOut.length; i ++) {for (int j = 0; j <codeOut.length; j ++) {if (codeOut [j] [i]) {gs.fillrect (j * 3+pixoff, i * 3+pixoff, 3, 3); }}}} else {System.err.println ("Qrcode Content bytes longitud =" + contentBytes.length + "no en [0,130]."); } /* Determine si necesita agregar una imagen del logotipo* / if (logopath! = Null) {archivo icon = nuevo archivo (logoPath); if (icon.exists ()) {int width_4 = imgsize / 4; int width_8 = width_4 / 2; int hight_4 = imgSize / 4; int hight_8 = altura_4 / 2; Imagen img = imageIO.Read (icon); Gs.DrawImage (IMG, Width_4 + Width_8, Height_4 + Height_8, Width_4, Height_4, NULL); gs.dispose (); bufimg.flush (); } else {System.out.println ("Error: ¡La imagen de inicio de sesión no existe!"); }} gs.dispose (); bufimg.flush (); // crear archivo de código QR IMGFILE = nuevo archivo (imgpath); if (! imgfile.exists ()) imgfile.createNewFile (); // Obtenga la imagen de la cadena de imagen generada imgtype = imgpath.substring (imgpath.lastindexof (".") + 1, imgpath.length ()); // Generar código QR QRCode Image ImageIO.Write (BufiMg, IMGType, IMGFile); } catch (Exception e) {E.PrintStackTrace (); }}/*** <span style = "font-size: 18px; font-weight: blod;"> Qrcode Qr Code Analysis </span>* @param CodePath Qr Code ruta* @return Parsing Result*/public static String QrCodeanalyze (String CodePath) {File ImageFile = nuevo archivo (CodePath); BufferedImage bufiMg = nulo; Cadena decodeddata = null; Pruebe {if (! ImageFile.Exists ()) Devuelve "El código QR no existe"; bufimg = imageIO.Read (ImageFile); QrCodEdecoder decoder = new QrCodeDeCoder (); decodeddata = new String (decoder.decode (new imageUtil (bufiMg)), "GB2312"); } catch (ioException e) {System.out.println ("Error:" + E.getMessage ()); E.PrintStackTrace (); } Catch (decodingfailedException dfe) {system.out.println ("error:" + dfe.getMessage ()); dfe.printstacktrace (); } return decodedData; }} 3. Última publicación Código de prueba: prueba de paquete; import java.awt.image.bufferedImage; import java.io.inputstream; import java.net.url; import javax.imageio.imageio; importar común.imageutil; import Common.qrcodeUtil; import jp.sourceforge.qrcode.qrcodeDecoder; /*** Qr Code Generation Test Clase* @author Cloud* @data 2016-11-21* QrCodetest* /public class QrCodetest {public static void main (string [] args) lanza excepción { /*** QRCode Qr Code Generation Prueba* Qrcodeutil.qrcodecreate ("http://blog.csdn.net/u014266877", "e: //qrcode.jpg", 15, "e: //icon.png"); *//*** QRCode Qr Code Analysis Test* String QrCodeAnalyze = QrCodeUtil.qrCodeAnalyze ("e: //qrcode.jpg"); *//*** ZXINGCODE QR Test de generación de códigos* qrcodeutil.zxingcodeCreate ("http://blog.csdn.net/u014266877", 300, 300, "e: //zxingcode.jpg", "jpg"); *//*** ZXINGCODE QR Code Analysis* String zxinganalyze = qrcodeUtil.zxingCodeAnalyze ("e: //zxingcode.jpg") .ToString (); */ System.out.println ("éxito"); }}