представлять
В основном используется пакет zxing Goole. Ниже приведен пример кода, который очень удобен для всех, чтобы понять и учиться. Код принадлежит предварительной структуре и имеет функции, и его необходимо улучшить и оптимизировать в соответствии с фактическим использованием.
Шаг 1: Maven Import zxing
<Depective> <groupid> com.google.zxing </GroupId> <artifactid> core </artifactid> <sersion> 3.2.1 </version> </depervice>
Шаг 2: Начните генерировать QR -код:
Private Static Final int Black = 0xff000000; Private Static Final int White = 0xfffffffff;/*** Сохранить сгенерированный QR -код в картинке* @param Matrix QR Code Class под пакетом ZXING* @return*/public Static BuffereMage TobufferedImage (Bitmatrix Matrix) {int width = matrix.getwidth (); int height = matrix.getheight (); BufferedImage Image = new BufferedImage (ширина, высота, bufferedimage.type_int_rgb); for (int x = 0; x <width; x ++) {for (int y = 0; y <height; y ++) {image.setrgb (x, y, matrix.get (x, y)? Black: White); }} return image;}/*** Сгенерировать QR -код и записать в файл* @param Content Scan Содержание QR -кода* @param Format Format изображения JPG* @param файл файла* @Throws Exception*/public static void writeToFile (строковое содержимое, строковое формат, файл файла) thiprows Exception {multiformAtWriter = new Multiformatwriter (); @Suppresswarnings ("rawtypes") map nts = new hashmap (); // Установить UTF-8, чтобы предотвратить китайские искаженные намеки. // Установить размер белой области вокруг QR -кода nts.put (encodehinttype.margin, 1); // Установите устойчивость к ошибкам QR -кода nts.put (encodehinttype.error_correction, errorcorrectionLectionlevel.h); // Нарисуйте QR -код Bitmatrix Bitmatrix = MultiformatWriter.encode (содержимое, barcodeformat.qr_code, ширина, высота, подсказки); BufferedImage Image = TobufferedImage (раствора); if (! Imageio.write (image, format, file)) {бросить новое ioException («Не удалось бы написать изображение формата» + format + »в" + file); }}Шаг 3: Запишите текст в картинку QR -кода:
/*** Добавить текст в QR-кодовое изображение* @param Press Text* @param qrfile QR-файл* @param fontstyle* @param color* @param fontsize*/public static void presstext (string presstext, файл qrfile, int fontstyle, color, int fontsize) trows ueclect {presstext = new string. Image src = imageio.read (qrfile); int ImageW = src.getWidth (null); int ImageH = src.getheight (null); BufferedImage Image = new BufferedImage (ImageW, ImageH, BufferedImage.type_int_rgb); Graphics g = image.creategraphics (); g.drawimage (src, 0, 0, imagew, imageh, null); // Установить цвет кисти g.setcolor (цвет); // Установить шрифт font font = new Font ("安安", fontstyle, fontsize); Metrics fontmetrics = g.getFontmetrics (Font); // Координаты текста на картинке установлены в середине здесь int startx = (width - metrics.stringwidth (presstext)) /2; int starty = высота/2; g.setfont (шрифт); G.DrawString (PressText, Startx, Starty); g.dispose (); FileOutputStream OUT = new FileOutputStream (QRFILE); Imageio.write (Image, "jpeg", Out); out.close (); System.out.println ("Image Press Success");}Шаг 4: Проверьте в основном методе, будет создан QR -код с текстом в середине
public static void main (string [] args) выбрасывает exection {file qrcfile = new File ("/users/deweixu/", "google.jpg"); WriteToFile ("www.google.com.hk", "jpg", qrcfile); presstext ("Google", qrcfile, 5, color.red, 32);}Суммировать
Вышеуказанное - все содержание этой статьи. Я надеюсь, что содержание этой статьи поможет вашему обучению или работе. Если у вас есть какие -либо вопросы, вы можете оставить сообщение для общения.