Ajari Anda langkah demi langkah menggunakan desain java untuk menghasilkan kode QR
Di era Internet of Things, kode QR adalah hal yang sangat penting. Sekarang, apa pun Anda, Anda harus mendapatkan logo kode QR. Karena takut sudah ketinggalan zaman, Anda tidak dapat menggunakan kode QR untuk mengidentifikasinya. Mungkin suatu hari akta kelahiran atau buku pendaftaran rumah tangga akan diidentifikasi dengan kode QR. Hari ini saya benar -benar penuh dan melihat bahwa orang lain telah menambahkan kode QR ke blog mereka, dan saya juga ingin melakukan tes.
Ini terutama digunakan untuk mencapai dua poin:
1. Hasilkan kode QR dengan teks apa pun.
2. Tambahkan gambar di tengah kode QR.
1. Pekerjaan persiapan.
Siapkan Paket Inti Kode QR 3.0 QR dan gambar JPG.
Unduh paket kode QR QR.
Pertama, saya harus mengunduh paket zxing.jar. Saya menggunakan paket inti 3.0 di sini
Alamat Unduh: Sekarang telah dipindahkan ke GitHub: https://github.com/zxing/zxing/wiki/getting-started-developing,
Tentu saja, Anda juga dapat mengunduh paket jar dari repositori Maven: http://central.maven.org/maven2/com/google/zxing/core/
2. Pemrograman
1. Mulai Eclipse, buat proyek Java baru, dan temukan nama proyek (dalam contoh ini, beri nama Qrcodesoft). Klik Berikutnya:
2. Impor Paket Zxing.jar. Saya menggunakan paket inti 3.0 di sini: klik "Tambahkan toples eksternal (x) ...".
3. Buat dua kelas baru, yaitu:
Bufferedimageluminancesource.java
Qrcodeutil.java
Kode utamanya adalah: bufferedimageluminancesource.java dan qrcodeutil.java, di mana metode utama yang diuji terletak di qrcodeutil.java.
Bufferedimageluminancesource.java Kode Program:
Paket com.yihaomen.barcode; impor java.awt.graphics2d; impor java.awt.geom.affinetransform; impor java.awt.image.bufferedImage; impor com.google.zxing.luminancesource; Buffeding Class BufferedImageluminances Extenders LoughumeRance Extends Louginance Lougherce; Kelas Publik BufferedImageluminances Extends Louminance LoureMinances Louginances Louginance Lougherance; Top; publik bufferedimageluminancesource (gambar buferedimage) {this (gambar, 0, 0, image.getWidth (), image.getheight ());} public BufferedImageluminancesource (gambar bufferedHight, int int, int lebar, int tinggi) {super (lebar, tinggi); sumber int int, int) {super (lebar); sumber); Image.getHeight (); if (kiri + lebar> SourceWidth || Top + Height> SourceHeight) {lempar IllegalArgumentException baru ("Crop Rectangle tidak sesuai dengan data gambar.");} untuk (int y) <top + tinggi; y ++) {untuk (int x = x <x <kiri + width + width; y) {fiage (int x = x <x <kiri + width + width; 0xff000000) == 0) {image.setrgb (x, y, 0xffffff); // = white}}} this.image = BufferedImage baru (SourceWidth, SourceHeight, bufferedImage.type_byte_gray); this.image.getGraphics (). DrawImage (gambar, 0, 0, null); this.left = left; this.top = top;} public byte [] public [publow); geting (left = left; this.top = Top;} public byte [] public [public [] {left) {left (this.top = Top;} public byte [] [null); getHeight ()) {lempar IllegalArgumentException baru ("Baris yang diminta berada di luar gambar:" + y);} int lebar = getWidth (); if (row == null || row.length <width) {row = byte baru [lebar];} image.getraster (). getDataelements (left, landth); well, row, row, row, row, row, lebah, getMatrix () {int width = getWidth (); int height = getHeight (); int area = lebar * tinggi; byte [] matriks = byte baru [area]; gambar.getraster (). getDataelement (kiri, lebar, tinggi, matrix); return matrix;} public boolean iscrops public ISCROPS ISCROPS PUBLIC (MATRIX); return matrix;} public boolean iscrops public iscrops public ISCROPS ISCROPS ISCROPS PUBLIK YOUS (MATRIX); return matrix;} public boolean iscrops iScrops public ISCROPS ISCROPS ISCROPS ISCROPS PUBLIK YOUDW. kiri, int top, int lebar, tinggi int) {return baru bufferedimageluminancesource (gambar, this.left + kiri, this.top + top, lebar, tinggi);} public boolean isrotatesupported () {return true;} public luminancesource rotateCounclockwise () {sumberwidth = public luminancesource rotateCounceWise () {) {intorwidth = public luminancesource rotateCounceWise () {) {sumberwidth = public luminancesource rotateCounceWise () {) {sumberwidth = public luminanSource rotateCounceware () {) {sumberwidth = public luminancesOndThe.) Image.getHeight (); affinetransform transform = affinetransform baru (0,0, -1.0, 1.0, 0.0, sourceWidth); bufferedImage rotedImage = BufferedImage baru (sourceHeight, sourceWidth, bufferedimage.type_byte_gray); grafik g = rotedimage.croatcraphics (gigraphics); graphics2d g = rotedimage. null); g.dispose (); int width = getWidth (); return new bufferedimageluminancesource (rotedImage, top, sourceWidth - (kiri + lebar), getHeight (), lebar);}}Qrcodeutil.java Kode program:
Paket com.yihaomen.barcode; impor java.awt.basicstroke; impor java.awt.graphics; impor java.awt.graphics2d; import java.awt.image; impor java.awt.shape; impor java.awt.geom.roundrechlevle; java.io.file; impor java.io.outputstream; import java.util.hashtable; import java.util.random; impor javax.imageio.imageio; com.ginybitmaporpor.barporpormat; impor Com.google.zxing.binarymap; com.google.zxing.encodehinttype; import com.google.zxing.multiformatreader; import com.google.zxing.multiformTriter; import com.google.zxing.result; impor com.google.common.comon.bitmatrix; com.google.zxing.common.bitmatrix; com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;/** * QR code tool class* */public class QRCodeUtil {private static final String CHARSET = "utf-8";private static final String FORMAT_NAME = "JPG";// QR code size private static final int QRCODE_SIZE = 300;// LOGO width private static final int WIDTH = 60; // Logo Tinggi Pribadi Static Final Int Tinggi = 60; Private Static BufferedImage CreateImage (Konten String, String Imgpath, Boolean NeedCompress) melempar Exception {hashtable <encodeHintType, Object> hints = hashtable <encodeHintType, object> (); hints.puts.puteHinteHable <encodeHintype, object> (); hints.puts.puteHinteHable. ErrorCorrectionLevel.h); hints.put (encodeHintType.character_set, charset); hints.put (encodehinttype.margin, 1); bitmatrix bitmatrix = Multiformatwriter baru, encode (konten, barcodeformat.qr_code, qrcode_size, qrcode, qrcodeze, qrcode, qrcode, qrcode, qrcode_size, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode, qrcode. bitmatrix.getWidth (); int height = bitmatrix.getHeight (); bufferedImage gambar = BufferedImage baru (lebar, tinggi, bufferedimage.type_int_rgb); untuk (int x = 0; x <lebar; x ++) {for (int y = 0; y <height; y ++) {image.setrgb (x, y, bitmatrix.get (x, y)? 0xff000000: 0xffffff);}} if (Imgpath == null || ". imgpath, perlu compress); gambar kembali;}/** * Masukkan logo * * @param sumber * gambar kode qr * @param imgpath * alamat gambar logo * @param memerlukan compress * apakah akan kompres * @throws except */private static void insertImage (bufferedImage sumber, string iMgpath, boolean needcompaths) (! File.exists ()) {System.err.println (""+imgpath+"File ini tidak ada!"); return;} gambar src = imageo.read (file baru (imgpath)); int width = src.getwidth (null); int height = src.getheight (null); nearscress (nears = ifed (null); int height = src.getheight (null); nearscress (nears = ife {if); int height = src.getheight (null); Lebar) {width = width;} if (tinggi> tinggi) {height = height;} gambar gambar = src.getScaledInstance (lebar, tinggi, gambar.scale_smooth); tag buferedImage = new BufferedImage (width, height, bufferedImage.type_int_rgb); grafik g = tag = nnget (nolgrape (gigrap) (gigrape (gigrap) (gigrape (gigrap); gigrape (gigrap) (gigrape (gigrap); getulon (gigrape (gigape (gigrap); graphics, gergrape (neFeredImage. // Gambar grafik g.dispose (); src = gambar;} // masukkan grafik logografi2d = source.creategraphics (); int x = (qrcode_size - lebar)/ 2; int y = (qrcode_size - tinggi)/ 2; graph.drawimage (src, x, y, y, width, loncatan)/ 2; non -noLDrawImage (src, x, y, y, width, width, loncatan y, lebar, lebar, 6, 6); grafik. */public static void encode (konten string, string imgpath, string destpath, boolean membutuhkan compress) melempar pengecualian {bufferedImage image = qrcodeutil.createImage (konten, imgpath, needcompress); mkdirs (destPath); string file = new baru (). NEXTINT (999999999999999999999999999999 Format_name, file baru (destPath+"/"+file));}/*** Ketika folder tidak ada, mkdir akan secara otomatis membuat direktori multi-lapisan, yang berbeda dari mkdir. (Jika direktori induk tidak ada, pengecualian akan dilemparkan) * @author lanyuan * Email: [email protected] * @Date 2013-12-11 10:16:36 AM * @param destpath Store */public static void mkdirs (string destpath) {publican fille =) (destpath =) (destpath (string destpath) {file destpath =) (destpath =); DURE); // Ketika folder tidak ada, MKDIRS akan secara otomatis membuat direktori multi-lapisan, yang berbeda dari MKDIR. (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 (konten string, string imgpath, string destPath) melempar pengecualian {qrcodeutil.encode (konten, imgpath, destpath, false);}/** * menghasilkan kode qr * * @param content * @param destpath * publicy * @param perlu compress * apakah akan mengompres logo * @param destpath * publicy * @param perlu compress * apakah akan mengompres logo * @param destpath * publicy * @param needcompress * apakah akan mengompres LOGO * @Prows destPath * Publicy * @param perlu compress * apakah akan mengompres LOGO * @Prow NeedCompress) Lempar Pengecualian {qrcodeutil.encode (konten, null, destpath, needsompress);}/** * Hasilkan kode qr * * @param konten * konten @param destpath *, @throws Exception */public static encode (konten string, string destpath) Throws Exception {telah lemparan {qrode {qrode {qrode {qrode {qrode {qrode. false);}/** * Generate QR code (embedded LOGO) * * @param content * Content* @param imgPath * LOGO address* @param output * Output stream* @param needCompress * Whether to compress LOGO * @throws Exception */public static void encode(String content, String imgPath,OutputStream output, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);ImageIO.write(image, FORMAT_NAME, output);}/** * Generate QR code* * @param content * Content* @param output * Output stream* @throws Exception */public static void encode(String content, OutputStream output)throws Exception {QRCodeUtil.encode(content, null, output, false);}/** * Analyze QR code* * @param file * QR code image* @return * @throws Exception */public static String decode(File file) throws Exception {BufferedImage image;image = ImageIO.read(file);if (image == null) {return null;}BufferedImageLuminanceSource source = new Bufferedimageluminancesource (gambar); BinaryBitmap bitmap = BinaryBitmap baru (hybridbinarizer baru (sumber)); hasil hasil; hashtable <decodehinttype, objek> petunjuk = hashtable baru <decodehinttype, object> (); hints.put (decodeHintType.cretaType. (decodeHintType, object> (); hints.put (decodeHintType.cretaType. (decodeHintType, objek> (); hints.put (decodeHintType.CHORCHORTE. (decodeHintType, Object; Multiformatreader (). Decode (bitmap, hints); string resulttr = result.getText (); return resulttr;}/** * parsing kode qr * * @param path * qr kode gambar * @return * @throws Exception */public static string decode (string path) lemparan pengecualian {qrowsoid qrcode. main (string [] args) melempar pengecualian {string text = "http://www.yihaomen.com"; qrcodeutil.encode (teks, "c: /me.jpg", "c:/barcode", true);}}Hasilkan kode QR tanpa logo
Kode program adalah sebagai berikut:
public static void main (string [] args) melempar pengecualian {string text = "http://www.dans88.com.cn"; Qrcodeutil.encode (teks, "", "d:/myworkdoc", true);}Jalankan metode pengujian ini dan kode QR yang dihasilkan tidak memiliki logo, gayanya sebagai berikut:
Jika Anda tertarik, Anda dapat memindainya dengan ponsel Anda
Menghasilkan kode QR dengan logo
Logo Anda dapat menggunakan avatar Anda sendiri atau gambar yang Anda sukai, dan menggunakan kode berikut, kode program adalah sebagai berikut:
public static void main (string [] args) melempar pengecualian {string text = "http://www.dans88.com.cn"; Qrcodeutil.encode (teks, "d: /myworkdoc/my180.jpg", "d:/myworkdoc", true); }Satu -satunya perbedaan adalah bahwa alamat logo ditentukan secara sebelumnya, dan file gambar disk C digunakan di sini.
Pindai dengan ponsel Anda, dan teks yang ingin Anda muncul dapat muncul. Klik untuk memasukkan situs web Anda sendiri.
Di atas adalah menggunakan desain java untuk menghasilkan kode QR. Teman yang tertarik dapat merujuknya. Terima kasih atas dukungan Anda untuk situs ini!