Unterrichten Sie Schritt für Schritt mit Java Design, um QR -Codes zu generieren
Im Zeitalter des Internet der Dinge sind QR -Codes eine sehr wichtige Sache. Egal was Sie sind, Sie müssen ein QR -Code -Logo erhalten. Aus Angst, veraltet zu sein, können Sie den QR -Code nicht verwenden, um ihn zu identifizieren. Möglicherweise wird eines Tages das Geburtsurkunde oder das Haushaltsregistrierungsbuch mit einem QR -Code identifiziert. Heute war ich aus einer Laune heraus und sah, dass andere ihre Blogs QR -Codes hinzugefügt hatten, und ich wollte auch einen Test machen.
Es wird hauptsächlich verwendet, um zwei Punkte zu erzielen:
1. Generieren Sie einen QR -Code mit jedem Text.
2. Fügen Sie ein Bild in der Mitte des QR -Codes hinzu.
1. Vorbereitungsarbeit.
Bereiten Sie das QR QR -Code 3.0 -Kernpaket und ein JPG -Bild vor.
Laden Sie das QR QR -Codepaket herunter.
Zunächst muss ich das Paket Zxing.jar herunterladen. Ich verwende hier das Kernpaket von 3.0
Download-Adresse: Jetzt wurde es auf GitHub verschoben: https://github.com/zxing/zxing/wiki/getting-started-developing,
Natürlich können Sie das JAR -Paket auch aus dem Maven -Repository herunterladen: http://central.maven.org/maven2/com/google/zxing/core/
2. Programmierung
1. Starten Sie Eclipse, erstellen Sie ein neues Java -Projekt und finden Sie den Projektnamen (in diesem Beispiel nennen Sie es Qrcodesoft). Klicken Sie auf Weiter:
2. Importieren Sie das Paket von Zxing.jar. Ich verwende hier das Kernpaket von 3.0: Klicken Sie auf "Hinzufügen von externem Glas (x) ...".
3. Erstellen Sie zwei neue Klassen, nämlich:
BufferedImageluminancesource.java
QrcodeUtil.java
Die Schlüsselcodes sind: bufferedImageluminancesource.java und qrcodeUtil.java, wo sich die getestete Hauptmethode in QrcodeUtil.java befindet.
BufferedImageluminancesource.java Programmcode:
Paket com.yihaomen.barcode; import Java.awt.Graphics2d; Import Java.awt.Geom.Affinetransform; Import Java.awt.image.Buffenedimage; top; public bufferedImageluminancesource (bufferedimage Bild) {this (Bild, 0, 0, Bild.getWidth (), Bild.Getheight ()); Image.getheight (); if (links + width> SourceWidth || Top + Höhe> SourceHeight) {Neue IllegalArgumentException ("Crop -Rechteck passt nicht in Bilddaten.")} für (int y = top; y <top + height; y ++) {für (int x = links; x <links + width; x ++) {if (y) {if (y) {if (y) {if (y) {if (y) {if (y) {if (y) {if; y) {if (y. y) {if (y) {if; y) {if (y. y) {if (y) {if (y) {if; y (y) {if (y) {if; y) {if; y) {if; y. 0xff000000) == 0) {image.setRGB (x, y, 0xffffff); // = weiß}}} this.image = new bufferedImage (SourceWidth, SourceHeight, BufferedImage.Type_Byte_Gray); this.image.getGraphics (). Drawimage (Bild, 0, 0, null); this.lEft = links; this.top = ober; getheight ()) {Neue IllegalArgumentException ("angefordert ist außerhalb des Bildes:" + y);} int width = getWidth (); if (row == null || row.länge <width) {row = newth];} Bild.getraster (). getMatrix () {int width = getWidth (); int height = getheight (); int Bereich = Breite * Höhe; Byte [] matrix = neuer Byte [Bereich]; Bild.getraster (). getDataelements (links, obere, width, Höhe, matrix); return matrix; links, int top, int width, int lhohe) {return New BufferedImageluminancesource (Bild, this.left + links, this.top + top, width, Höhe);} public boolean isRotatesupported () {return true;} public luminancesock rotateCounterclockwihe () {int Quellwiddh = Quellwidth = Quellwidth = Quellwidth = Quellwidth = Quellwiddh = Image.Getheight (); Affinetransform -Transformation = neue Affinetransform (0,0, -1,0, 1,0, 0,0, Sourcewidth); BufferedImage RotatedImage = new bufferedImage (SourceHeight, SourceSheighth, BufferedImage.Type_Byte_Gray); null); g.disponse (); int width = getwidth (); return New BufferedImagelumInancesource (RotatedImage, oben, Quellbreite - (links + Breite), Getheight (), Breite);}}QrcodeUtil.java Programmcode:
Paket com.yihaomen.barcode; import Java.awt.BasicStroke; Import Java.awt.graphics; Import Java.awt.graphics2d; Import Java.awt.image; Import Java.awt.Shape; java.io.file; import java.io.outputstream; import Java.util.hashtable; import Java.util.random; import Javax.imageo.imageo; import com.google.zxing.barcodeformat; com.gxing.biogymap; com.google.zxing.codeHintType; import com.google.zxing.multiformatreader; import com.google.zxing.multiformatwriter; com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;/*** QR-Code-Werkzeugklasse**/public class QrcodeUtil {private statische String charset = "utf-8"; private statische String-String-Format_Name = "JPG"; // QR CODE ERGING FINGS WRIDTATIC STATIC STATIC STATIC STATIC STATIC STATIC STATIC STATIC. 60; // Logo Höhe private statische endgültige int Höhe = 60; Private static bufferedImage createImage (String -Inhalt, String imgpath, boolean bedürfen ErrorCorrectionLevel.H);hints.put(EncodeHintType.CHARACTER_SET, CHARSET);hints.put(EncodeHintType.MARGIN, 1);BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);int width = bitmatrix.getWidth (); int height = bitmatrix.getheight (); bufferedImage image = new bufferedImage (width, Höhe, bufferedimage.type_int_rgb); for (int x = 0; x <Breite; x ++) {für (int y = 0; y <height; y ++) {image.setRGB (x, y, bitmatrix.get (x, y)? 0xff0000: 0xffffffffff);}} if (imgpath == null || ".Equals (Imgpath) {{{{} // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // NeedCompress); Rückgabe image;}/** * Logo einfügen * * @param Source * QR -Code -Bild * @param imgPath * Logo Bildadresse * @param NeedComPress *, ob komprimiert * @Throws AUCTION */private statische statische void Insert (BufferedImage -Quelle, String imgpath, boolean formComprent). {System.err.println (""+imgpath+"Diese Datei existiert nicht!");} Bild src = imageIO.read (neue Datei (imgpath)); int width = src.getWidth (null); inthohe = src.geththth); (Höhe> Höhe) {Höhe = Höhe;} Image Image = src.getScaledInstance (Breite, Höhe, Bild.Scale_Smooth); BufferedImage Tag = new bufferedImage (width, Höhe, bufferedimage.type_int_rgb); Grafiken G = Tag.getGraphics (); // Zeichnen Sie den reduzierten Graph g.disponse (); y, width, width, 6, 6);graph.setStroke(new BasicStroke(3f));graph.draw(shape);graph.dispose();}/** * Generate QR code (embedded LOGO) * * @param content * Content* @param imgPath * LOGO address* @param destPath * Store directory* @param needCompress * Whether to compress LOGO * @throws Exception */public static VOID CODE (String -Inhalt, String imgPath, String destpath, boolean bedürfen Datei (destpath+"/"+Datei));}/*** Wenn der Ordner nicht existiert, erstellt MKDIR automatisch mehrschichtige Verzeichnisse, die sich von MKDIR unterscheiden. (Wenn das übergeordnete Verzeichnis nicht vorhanden ist, wird eine Ausnahme ausgelöst) * @Author Lanyuan * E-Mail: [email protected] * @date 2013-12-11 10:16:36 am * @param destpath Store-Verzeichnis */public static void mkdirs (String destpath) {Datei-Datei = neue Datei (Destpat); // Wenn der Ordner nicht existiert, erstellt MKDIRS automatisch mehrschichtige Verzeichnisse, die sich von MKDIR unterscheiden. (mkdir will throw an exception if the parent directory does not exist)if (!file.exists() && !file.isDirectory()) {file.mkdirs();}}/** * Generate QR code (embedded LOGO) * * @param content * Content* @param imgPath * LOGO address* @param destPath * Storage address* @throws Exception */public static void encode(String content, String imgPath, String destpath) löst Ausnahme aus {qrcodeUtil.encode (Inhalt, ImgPath, destpath, false);}/** * QR -Code generieren * * @param Inhalt * Inhalt * @param destpath * Speicheradresse * @param bedarfscompress *, ob Logo -Ausnahme -Ausnahme, String -Destphe, String -Destphe, String -Destphe, String -Destphe, DestpheDPHOW -Ausnahme), DestpheDPHOWS -Ausnahme), String -Destphe, String -Destphe, Dennzeichen, billan als {QrCodeUtil.encode (Inhalt, null, destpath, NeedCompress);}/*** QR -Code generieren** @param Inhalt* Inhalt* @param destpath* Speicheradresse* @throws Exception*/public static void code (String -Inhalt, String Destpat) Ausnahmeberechter {qrCodeDil.codge (Content, Null, Null, Null, Destpat, Destpath); Logo) * * @param Inhalt * Inhalt * @param imgpath * Logo -Adresse * @param output * Ausgabestream * @param bedarfsCompress *, ob Logo komprimiert werden soll * @Throws Exception */public static void codes (String -Inhalt, String imgpath, outputStream Output, Boolean NeedCompress) Ausnahme {bufpuledimage Image = qrcodil.creimage (contentimage Image = qrcodil.creimage (qrcode). NeedCompress); ImageIO.Write (Bild, format_name, output);}/** * QR -Code generieren * * @param Inhalt * Inhalt * @param output * output stream * @throws Exception */public static void codieren (String -Inhalt, Ausgabeausgabe) lehnt Ausnahme aus {qrCodeil.encode -content (content, null, fehl). Image * @Return * @throws Exception */public static String Decodes (Dateidatei) löst Ausnahme aus {bufferedImage Image; Image = imageio.read (Datei); if (image == null) {return null;} bufferedImageluminancesource Source = New BufferedImageluminancesORCE (ague); Ergebnis; Hashtable <decodeHintType, Objekt> Hinweise = neuer Hashtable <decodeHintType, Objekt> (); Hints.put (decodeHintType.character_set, charset); result = new MultiformatReader (). Decode (Bitmap, Hinweise); @param Pfad * QR -Code -Bildadresse * @return * @throws Exception */public static String Decode (String -Pfad) löst Ausnahme aus {return qrCodeUtil.decode (neue Datei (Pfad));} public static void main (String [] args) treibt Ausnahme aus {String text = "http://www.yihaomen.com"; "c: /me.jpg", "c:/barcode", true);}}Generieren Sie den QR -Code ohne Logo
Der Programmcode lautet wie folgt:
public static void main (String [] args) löst eine Ausnahme aus {String text = "http://www.dans88.com.cn"; QrCodeUtil.encode (Text, "", "D:/myworkdoc", true);}Führen Sie diese Testmethode aus und der generierte QR -Code hat kein Logo, der Stil lautet wie folgt:
Wenn Sie interessiert sind, können Sie es mit Ihrem Telefon scannen
Generieren Sie einen QR -Code mit einem Logo
Logo Sie können Ihren eigenen Avatar oder ein Bild verwenden, das Sie mögen, und den folgenden Code verwenden. Der Programmcode lautet wie folgt:
public static void main (String [] args) löst eine Ausnahme aus {String text = "http://www.dans88.com.cn"; QrCodeUtil.encode (Text, "d: /myworkdoc/my180.jpg", "d:/myworkdoc", true); }Der einzige Unterschied besteht darin, dass die Adresse des Logos auf der vorherigen Basis angegeben ist und die Bilddateien der C -Festplatte hier verwendet werden.
Scannen Sie mit Ihrem Mobiltelefon, und der Text, den Sie ansehen möchten, kann angezeigt werden. Klicken Sie hier, um Ihre eigene Website einzugeben.
Das obige ist die Verwendung von Java -Design, um QR -Codes zu generieren. Interessierte Freunde können sich darauf beziehen. Vielen Dank für Ihre Unterstützung für diese Seite!