Научите вас шаг за шагом, используя Java Design для генерации QR -кодов
В эпоху Интернета вещей QR -коды - очень важная вещь. Теперь, что бы вы ни были, вы должны получить логотип QR -кода. Из -за страха быть устаревшим, вы не можете использовать QR -код для его идентификации. Может быть, однажды свидетельство о рождении или книга регистрации домохозяйства будут отождествлены с QR -кодом. Сегодня я был по прихоти и увидел, что другие добавили QR -коды в свои блоги, и я также хотел сделать тест.
В основном используется для достижения двух точек:
1. Сгенерируйте QR -код с любым текстом.
2. Добавьте изображение в середине QR -кода.
1. Подготовка работы.
Подготовьте основной пакет QR QR Code 3.0 и изображение JPG.
Загрузите QR QR -пакет.
Во -первых, я должен скачать пакет Zxing.jar. Я использую основной пакет 3.0 здесь
Адрес загрузки: теперь он был перенесен на github: https://github.com/zxing/zxing/wiki/getting-started-developing,
Конечно, вы также можете загрузить пакет JAR из Maven Repository: http://central.maven.org/maven2/com/google/zxing/core/
2. Программирование
1. Начните Eclipse, создайте новый Java Project и найдите имя проекта (в этом примере назовите его Qrcodesoft). Нажмите Далее:
2. Импорт пакет zxing.jar. Я использую основной пакет 3.0 здесь: нажмите «Добавить внешнюю банку (x) ...».
3. Создайте два новых класса, а именно:
BufferedImageLuminancesource.java
Qrcodeutil.java
Ключевые коды: BufferedImageLuminancesource.java и qrcodeutil.java, где основной протестированный метод находится в qrcodeutil.java.
BufferedImageLuminancesource.java Программный код:
пакет com.yihaomen.barcode; import java.awt.graphics2d; import java.awt.geom.affineTransform; import java.awt.image.bufferedImage; импорт com.google.zxing.luminancesource; top; public BufferedImageLuminancesource (изображение BufferedImage) {this (изображение, 0, 0, image.getWidth (), image.getheight ());} public BufferedImageLuminancesource (BufferedImage Image, int Left, int width, int height) {super (width, ehize); int sourcewidth = image. image.getheight (); if (слева + ширина> исходная width || top + height> sourceheight) {throw new allogalargumentException ("Прямоугольник обрезки не вписывается в данные изображения.");} для (int y = top; y <top + height; y ++) {для (int x = x <loft + width; x + x (image.get. get.je.get. 0xff000000) == 0) {image.setrgb (x, y, 0xffffff); // = White}}} this.image = new BufferedImage (SourceWidth, SourceHeight, BufferedImage.Type_byte_gray); this.image.getGraphics (). DrawMage (изображение, 0, 0, null); this.left = this.top = op; > = getheight ()) {бросить new allogalargumentException ("Запрашиваемая строка находится вне изображения:" + y);} int width = getWidth (); if (row == null || row.length <width) {row = new Byte [width];} image.getraster (). GetDatelements (Left, Top + y, width, 1, width, 1, width, 1, width, 1, width -width, 1, width, 1, width, 1, width, 1, width, 1, width, width, 1 getMatrix () {int width = getWidth (); int height = getheight (); int aem = width * height; byte [] matrix = new Byte [rea]; image.getraster (). getDataelements (слева, верхняя, ширина, высота, матрица); вернуть матрицу;} public boolean iscolean iscolean iscolean iscolean iscolean iscolean iscolean iscolean iscolean iscolean iscolean iscolean iscolean iscolean iscolean Слева, int top, int width, int height) {return new bufferedimageluminanceource (image, this.left + left, this.top + top, width, height);} public boolean isrotatesupported () {return true;} public luminancesourceource rotateCounterClock -wys () {int sourcewidth = Image. getHightHightHighTHE (); image.getheight ();; offinetransform transform = new AffineTransform (0,0, -1,0, 1,0, 0,0, источник -Width); BufferedImage rotatedImage = new BufferedImage (SourceHeight, SourceWidth, BufferedImage.type_byte_gray); null); g.dispose (); int width = getWidth (); вернуть новый BufferedImageLuminancesource (RotatedImage, Top, SourceWidth - (слева + ширина), getheight (), width);}}Qrcodeutil.java программный код:
пакет com.yihaomen.barcode; импорт java.awt.basicsstroke; импорт java.awt.graphics; импорт java.awt.graphics2d; импорт java.awt.image; импорт java.awt.shape; импорт java.awt.geom.roundrectangle2d; импорт java. java.io.file; импорт java.io.outputstream; import java.util.hashtable; импорт java.util.random; import javax.imageio.imageio; импорт com.google.zxing.barcodeformat; импорт com.google.zxing.binarybitmap; импорт. com.google.zxing.encodehinttype; import com.google.zxing.multiformatreader; import com.google.zxing.multiformatwriter; импорт com.google.zxing.result; импорт com.google.zxing.common.bitmatrix; импорт com.google.zxing.common.hybridbinaRizer; 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; // Высота логотипа частная статическая конечная конечная высота = 60; частное статическое BufferedImage createimage (String Content, String Imgpath, Boolean edCompress) Throws Exception {hashtable <encodehinttype, Object> hints = new Hashtable <Encodehinttype, Object> (); hints.put (encodehintpe. 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_s, wildsize; Bitmatrix.getWidth (); int height = bitmatrix.getheight (); BufferedImage Image = new BufferedImage (ширина, высота, bufferedimage.type_int_rgb); для (int x = 0; x <ширина; x ++) {for (int y = 0; y <eight; y ++) {image.setrgb (x, y, bitmatrix.get (x, y)? 0xff000000: 0xffffff);}} if (imgpath == null || "". imgpath, edcompress); return image;}/** * Вставьте логотип * * @param source * qr code picture * @param imgpath * Адрес изображения логотипа * @param edcompress * Будет ли сжать * @Throws Exception */private static void inSertImage (imgpath, spring in nemgpath, imgpath, imgpath) (im new -файл neable) {im new -файл neable) {im new) {im new) (! file.exists ()) {System.err.println (""+imgpath+"этого файла не существует!"); return;} image src = imageio.read (new File (imgpath)); int width = src.getwidth (null); int height = src.getheeThe (nul {width = width;} if (высота> высота) {height = height;} изображение изображение = src.getscaledInstance (ширина, высота, image.scale_smooth); BufferedImage Tag = new BuffereMage (ширина, высота, bufferemage.type_int_rgb); graphics g = tag.getgraphics (); g.dullage (1, neplullage (1, 1, neplullagage (); // Нарисуйте уменьшенный график g.dispose (); src = image;} // вставить логографию2d Graph = source.creategraphics (); int x = (qrcode_size - ширина)/ 2; int y = (qrcode_size - height)/ 2; graph.davimage (src, x, y, wildth, height, nullraate; 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 encode (String Content, String imgpath, String destpath, Boolean edcompress), выбросы исключения {bufferedimage image = qrcodeutil.createimage (content, imgpath, edcompress); mkdirs (destpath); string file = new Random (). Новый файл (destpath+"/"+file));}/*** Когда папка не существует, MKDIR автоматически создаст многослойные каталоги, которые отличаются от MKDIR. (Если родительский каталог не существует, будет брошено исключение) * @author lanyuan * Электронная почта: [email protected] * @date 2013-12-11 10:16:36 * @param Destpath Store Directory */public void mkdirs (строка destpath) {file = new file (destpath); // Когда папка не существует, MKDIRS автоматически создаст многослойные каталоги, которые отличаются от 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(String Содержание, строка Imgpath, String destpath) Throws Exception {qrcodeutil.encode (content, imgpath, destpath, false);}/** * Сгенерировать QR -код * * @param content * @param destpath * {Qrcodeutil.encode (content, null, destpath, edcompress);}/*** Сгенерировать QR -код*** @param content* content* @param destpath* adsement* @throws exception*/public static void encod (встроенный логотип) * * @param content * content * @param imgpath * address * @param output * output stream * @param edcompress *, чтобы сжать логотип * @throhs exection */public static void encode (строка, строка imgpath, outputstream output, boolean -crpress) throws exemptaite {bufferemage image = qrcodeil.crcodeil.crcodemage, contentiemage, contentiemage, contentiemage. NeedCompress); imageio.write (image, format_name, output);}/** * Сгенерировать QR -код * * @param content * content * @param output * output Stream * @Throws Exception */public static void encode (String Sontlem, outputStream output) throws execument {qrcodeil.encode (content, null, output, falseStream); 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(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));Result Результат; hashtable <decodehinttype, Object> ntsts = new Hashtable <decodehinttype, object> (); hints.put (decodehinttype.character_set, charset); result = new MultiformatReader (). Decode (Bitmap, ntslts); strucetr = gettextext (); @param path * QR -код Адрес * @return * @Throws Exception */public Static String Decode (Path Path) Throws Exception {return qrcodeutil.decode (новый файл (path));} public static void main (string [] args) throws exection {string text = "http://www.yhoamen.com"; "c: /me.jpg", "c:/barcode", true);}}Генерировать QR -код без логотипа
Код программы выглядит следующим образом:
public static void main (string [] args) бросает исключение {string text = "http://www.dans88.com.cn"; Qrcodeutil.encode (text, "", "d:/myworkdoc", true);}Запустите этот метод испытаний, и сгенерированный QR -код не имеет логотипа, стиль заключается в следующем:
Если вам интересно, вы можете сканировать его с помощью телефона
Создать QR -код с помощью логотипа
Логотип вы можете использовать свой собственный аватар или изображение, которое вам нравится, и использовать следующий код, код программы выглядит следующим образом:
public static void main (string [] args) бросает исключение {string text = "http://www.dans88.com.cn"; Qrcodeutil.encode (текст, "d: /myworkdoc/my180.jpg", "d:/myworkdoc", true); }Единственное отличие состоит в том, что адрес логотипа указан на предыдущей основе, и здесь используются файлы изображений диска C.
Сканируйте с вашим мобильным телефоном, и может появиться текст, который вы хотите появиться. Нажмите, чтобы ввести свой собственный веб -сайт.
Выше приведено использовать дизайн Java для генерации QR -кодов. Заинтересованные друзья могут ссылаться на это. Спасибо за поддержку этого сайта!