1 、 jar 包: zxing-core-3.3.0.jar http://mvnrepository.com/artifact/com.google.zxing/core
Zxing-javase-3.3.0.jar http://mvnrepository.com/artifact/com.google.zxing/javase
BufferedImageLuminancesource.java
пакет com.webos.util; import java.awt.graphics2d; import java.awt.geom.affineTransform; import java.awt.image.bufferedImage; import com.google.zxing.luminancesource; public class buffereimageluminanceource extends {private final Pinful Bufference Imagemage Imagemage Imagemage; частный финал int остался; Частный финальный топ; public BufferedImageLuminancesource (BufferedImage Image) {this (Image, 0, 0, image.getWidth (), image.getheight ()); } public BufferedImageLuminancesource (BufferedImage Image, int left, int top, int width, int height) {super (ширина, высота); int sourcewidth = image.getWidth (); int sourceHeight = image.getheight (); if (left + width> sourcewidth || top + height> sourceheight) {бросить новый allosalargumentException («Прямоугольник Crop не вписывается в данные изображения.»); } for (int y = top; y <top+height; y ++) {for (int x = слева; x <слева+ширина; x ++) {if ((image.getrgb (x, y) & 0xff000000) == 0) {image.setrgb (x, y, 0xfffffffffffffffffff); // = White}}} this.Image = new BufferedImage (SourceWidth, SourceHeight, BufferedImage.Type_byte_gray); this.image.getGraphics (). DrawMage (Image, 0, 0, NULL); this.left = осталось; this.top = top; } public byte [] getRow (int y, byte [] row) {if (y <0 || y> = getheight ()) {бросить новый allosalargumentException ("Запрашиваемая строка находится вне изображения:" + y); } int width = getWidth (); if (row == null || row.length <width) {row = new Byte [width]; } image.getraster (). getDataelements (слева, топ + y, ширина, 1, ряд); вернуть ряд; } public byte [] getMatrix () {int width = getWidth (); int height = getheight (); int area = ширина * высота; byte [] matrix = new Byte [область]; image.getraster (). getDatelements (слева, верх, ширина, высота, матрица); вернуть матрицу; } public boolean iscropSupported () {return true; } public luminancesource Crop (int left, int top, int width, int height) {return new bufferemageluminancesource (image, this.left + left, this.top + top, ширина, высота); } public boolean isrotatesUpported () {return true; } public luminancesource rotateCounterClockwope () {int sourcewidth = image.getWidth (); int sourceHeight = image.getheight (); AffineTransform Transform = New AffineTransform (0,0, -1,0, 1,0, 0,0, 0,0, исходная власть); BufferedImage RotatedImage = New BufferedImage (SourceHeight, SourceWidth, BufferedImage.Type_byte_gray); Graphics2d g = rotatedimage.creategraphics (); g.drawimage (изображение, преобразование, ноль); g.dispose (); int width = getWidth (); вернуть новый BufferedImageLuminancesource (RotatedImage, Top, SourceWidth - (левая + ширина), getheight (), ширина); }}Qrcodeutil.java
пакет com.webos.util; import java.awt.basicsstroke; import java.awt.graphics; импорт java.awt.graphics2d; импорт java.awt.image; импорт java.awt.shape; import java.awt.geom.roundrectangle2d; импорт java.iMage.Image.Buffure.Buffure.Buffure.Buffue.Bufft. 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.common.bitmatrix; импорт com.google.zxing.common.hybridbinarizer; импортматрикс; импорт com.google.zxing.common.hybridbinariz com.google.zxing.qrcode.decoder.errorcorrectionlevel;/*** @classname: qrcodeutil* @description: 二维码编码* @author liuy* @date 2016 年 7月 9 日 下午 3:03:24**/public class qrcodeutil {// 设置二维码编码格式 private static string string arset = "ut-static arset =" ut-8 // 保存的二维码格式 Private Static Final String format_name = "jpg"; // 二维码尺寸 Приватный статический окончательный окончательный int qrcode_size = 800; // логотип 宽度 Частный статический окончательный окончательный logo_width = 80; // логотип 高度 Частный статический окончательный финал int logo_height = 80; / ** * @title: createImage * @description: 将二维码内容创建到 изображение 流 * @param content 二维码内容 * @param imgpath logo 图片地址 * @param neadcress 是否压缩 логотип 图片大小 * @return * @throws Exception 参数说明 * @return bufferemage 返回类型 * @throws */ private static bufferedimage create expressemage (string content, string logopath, boolean emplycome expresse) Hashtable <encodehinttype, object> ntsts = new hashtable <encodehinttype, object> (); nts.put (encodehinttype.error_correction, errorcorrectionlevel.h); nts.put (encodehinttype.character_set, charset); nts.put (encodehinttype.margin, 1); Bitmatrix Bitmatrix = new MultiformatWriter (). Encode (Content, barcodeformat.qr_code, qrcode_size, qrcode_size, ntsts); int width = bitmatrix.getwidth (); int height = bitmatrix.getheight (); BufferedImage Image = new BufferedImage (ширина, высота, bufferedimage.type_int_rgb); for (int x = 0; x <width; x ++) {for (int y = 0; y <eight; y ++) {image.setrgb (x, y, bitmatrix.get (x, y)? 0xff000000: 0xffffffffffffff); }} if (logopath == null || "" .equals (logopath)) {return image; } // 插入 Logo qrcodeutil.insertimage (Image, logopath, eledCompress); вернуть изображение; } / ** * @title: insertimage * @description: 将 логотип 插入到二维码中 * @param source 二维码 image 流 * @param imgpath logo 地址 * @param edcompress 是否压缩大小 * @Throw Файл (LogoPath); if (! file.exists ()) {System.err.println ("" + logoPath + "该文件不存在!"); возвращаться; } Image src = imageio.read (new File (logoPath)); int width = src.getwidth (null); int height = src.getheight (null); if (undecmpress) {// 压缩 логотип if (width> logo_width) {width = logo_width; } if (height> logo_height) {hight = logo_height; } Image Image = src.getScaledInstance (ширина, высота, image.scale_smooth); BufferedImage Tag = new BufferedImage (ширина, высота, bufferedimage.type_int_rgb); Graphics g = Tag.getGraphics (); g.drawimage (изображение, 0, 0, null); // 绘制缩小后的图 g.dispose (); src = изображение; } // 插入 Logo Graphics2d Graph = source.creategraphics (); int x = (qrcode_size - width) / 2; int y = (qrcode_size - высота) / 2; graph.drawimage (src, x, y, width, высота, нулевая); Форма формы = новый Roundrectangle2d.float (x, y, ширина, ширина, 6, 6); graph.setstroke (New BasicStroke (3F)); graph.draw (форма); graph.dispose (); } / ** * @title: mkdirs * @description: 创建文件夹 * @param destpath 文件夹地址 * @return void 返回类型 * @Throws * / private Static Boolean Mkdirs (String destpath) {file file = new File (destpath); // 当文件夹不存在时 , mkdirs 会自动创建多层目录 , 区别于 mkdir. (mkdir 如果父目录不存在则会抛出异常) if (! File.exists () &&! File.isdirectory ()) {file.mkdirs (); вернуть истину; } вернуть false; } / ** * @title: encode * @description: 生成二维码 * @param content 二维码内容 * @param imgpath logo 图片地址 * @param destpath 目标保存地址 * @param edcompress 是否压缩 图片大小 * @Throw BufferedImage image = qrcodeutil.createImage (содержимое, logopath, NeedCompress); if (mkdirs (destpath)) {string file = new random (). nextint (99999999) + ".jpg"; Imageio.write (image, format_name, новый файл (destpath + "/" + file)); }} / ** * @title: encode * @description: 生成二维码 * @param content 二维码内容 * @param destpath 目标保存地址 * @throhs Exception 参数说明 * @return void 返回类型 * @Throws * / public void Encode (строка содержимого, строка destpath), бросает исключение {qrcodeil.encode (content, null, destpath, false); } / ** * @title: Encode * @description: 生成二维码 * @param content 二维码内容 * @param imgpath Logo 图片地址 * @param outpul image = qrcodeutil.createImage (содержимое, logopath, NeedCompress); Imageio.write (image, format_name, output); } / ** * @title: Encode * @description: 生成二维码 * @param content 二维码内容 * @param output 输出流 * @throhs exception 参数说明 * @return void 返回类型 * @throws * / public static void encode (String Sontlect, вывод output) throws Exception {qrcodeil.encode (content, null, output, false); } / ** * @title: decode * @description: 对二维码解码 * @param file 文件对象 * @return 解码后的二维码内容字符串 * @throhs Exception 参数说明 * @return String 返回类型 * @Throws * / private Static String DeCode (файл файл) Throws Exception {BuffereMage Image; image = imageio.read (файл); if (image == null) {return null; } BufferedImageLuminancesource source = new BufferedImageLuminancesource (Image); Binarybitmap Bitmap = new BinarybitMap (новый гибридбинаризер (источник)); Hashtable <decodehinttype, String> ntsts = new Hashtable <decodehinttype, String> (); nts.put (decodehinttype.character_set, charset); вернуть новый MultiformatReader (). Decode (растровый, подсказки) .getText (); } / ** * @title: decode * @description: 对二维码解码 * @param path 文件路径 * @return * @throhs exception 参数说明 * @return String 返回类型 * @Throws * / public Static String DeCode (String Path) Throws exection {return qrcodeut.decode (новый файл (Path)); }}Qrcodeservlet.java
пакет com.webos.servlet; импорт java.io.ioexception; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; импорт javax.servlet.http.httpservlet; импорт javax.servlet.http.httpservlectrequest; javax.servlet.http.httpservletresponse; import com.webos.util.qrcodeutil;/ * * Класс реализации сервлета / * * @see httpservlet#httpservlet () */ public qrcodeservlet () {super (); }/ * * @see httpservlet#doget (httpservlectrequest, httpservletresponse * response) */protected void doget (httpservletrequest, httpservletresponse response) throws servletexception, ioexception {try {string = "http :/www.bake.bake.bake.bake.bake.bake.baksecept System.currentTimeMiLlis (); Qrcodeutil.encode (text, response.getOutputStream ()); } catch (Exception e) {e.printstackTrace (); }} / * * @see httpservlet#dopost (httpservletrequest, httpservletresponse * response) * / Защищенный void dopost (httpservletrequest, httpservletresponse response) throws vertexception, ioexception {// todo auto-generated method stube-stube (ratexception, respect); }}以上就是本文的全部内容 , 希望本文的内容对大家的学习或者工作能带来一定的帮助 同时也希望多多支持武林网!