Java zxing generate two-dimensional code and barcode instance sharing _java

Source: Internet
Author: User
Tags ming mkdir parent directory

1,jar package : 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

Package com.webos.util;
Import Java.awt.Graphics2D;
Import Java.awt.geom.AffineTransform;
Import Java.awt.image.BufferedImage;
Import Com.google.zxing.LuminanceSource;
 public class Bufferedimageluminancesource extends Luminancesource {private final bufferedimage image;
 private final int left;
 private final int top;
 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 (width, hei
  Ght);
  int sourcewidth = Image.getwidth ();
  int sourceheight = Image.getheight (); if (left + width > Sourcewidth | | top + height > sourceheight) {throw new IllegalArgumentException ("Crop Rectang
  Le does not fit within image data. "); for (int y = top; y < top + height; y++) {for (int x = left; x < left + width; + +) {if (Image.getrgb (x, y ) & 0xff000000) = = 0) {Image.setrgb (x, y, 0xFFFFFFFF);
  = white}} this.image = new BufferedImage (Sourcewidth, Sourceheight, Bufferedimage.type_byte_gray);
  This.image.getGraphics (). DrawImage (image, 0, 0, NULL);
  This.left = left;
 This.top = top; Public byte[] GetRow (int y, byte[] row {if (Y < 0 | | | y >= getheight ()) {throw new Illegalargumentexceptio
  N ("Requested row is outside the image:" + y);
  int width = getwidth ();
  if (row = = NULL | | Row.length < width) {row = new Byte[width];
  } image.getraster (). getDataElements (left, top + y, width, 1, row);
 return row;
  Public byte[] Getmatrix () {int width = getwidth ();
  int height = getheight ();
  int area = width * height;
  byte[] Matrix = new Byte[area];
  Image.getraster (). getDataElements (left, top, width, height, matrix);
 return matrix;
 public Boolean iscropsupported () {return true; Luminancesource crop (int left, int top, int width, int height) {return new Bufferedimageluminancesource (image , This.left + LEFT, This.top + top, width, height);
 public Boolean isrotatesupported () {return true;
  Public Luminancesource rotatecounterclockwise () {int sourcewidth = Image.getwidth ();
  int sourceheight = Image.getheight ();
  AffineTransform transform = new AffineTransform (0.0, -1.0, 1.0, 0.0, 0.0, sourcewidth);
  BufferedImage rotatedimage = new BufferedImage (Sourceheight, Sourcewidth, Bufferedimage.type_byte_gray);
  Graphics2D g = rotatedimage.creategraphics ();
  G.drawimage (image, transform, null);
  G.dispose ();
  int width = getwidth ();
 Return to New Bufferedimageluminancesource (Rotatedimage, Top, Sourcewidth-(left + width), getheight (), width); }
}

Qrcodeutil.java

Package com.webos.util;
Import Java.awt.BasicStroke;
Import Java.awt.Graphics;
Import Java.awt.Graphics2D;
Import Java.awt.Image;
Import Java.awt.Shape;
Import Java.awt.geom.RoundRectangle2D;
Import Java.awt.image.BufferedImage;
Import Java.io.File;
Import Java.io.OutputStream;
Import java.util.Hashtable;
Import Java.util.Random;
Import Javax.imageio.ImageIO;
Import Com.google.zxing.BarcodeFormat;
Import Com.google.zxing.BinaryBitmap;
Import Com.google.zxing.DecodeHintType;
Import Com.google.zxing.EncodeHintType;
Import Com.google.zxing.MultiFormatReader;
Import Com.google.zxing.MultiFormatWriter;
Import Com.google.zxing.common.BitMatrix;
Import Com.google.zxing.common.HybridBinarizer;
Import Com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; /** * @ClassName: Qrcodeutil * @Description: Two-dimensional code code * @author Liuy * @date July 9, 2016 afternoon 3:03:24 * */public class Qrcodeu
 til {//Set two-dimensional code format private static final String CHARSET = "Utf-8"; Saved two-dimensional code format private static final String Format_name = "JPG";
 Two-dimensional code size private static final int qrcode_size = 800;
 LOGO width private static final int logo_width = 80;
 LOGO height private static final int logo_height = 80; /** * @Title: CreateImage * @Description: Create two-dimensional code content to image stream * @param content two-dimensional code contents * @param Imgpath logo image address * @pa Ram needcompress Compress logo picture size * @return * @throws Exception parameter description * @return bufferedimage return type * @throws * * PRIV Ate static BufferedImage createimage (string content, String Logopath, Boolean needcompress) throws Exception {Hashtable
  <encodehinttype, object> hints = new Hashtable<encodehinttype, object> ();
  Hints.put (Encodehinttype.error_correction, 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, height, bufferedimage.type_int_rgb);  for (int x = 0; x < width, x + +) {for (int y = 0; y < height; y++) {Image.setrgb (x, Y, Bitmatrix.get (x, y)?
   0XFF000000:0XFFFFFFFF); } if (Logopath = null | |
  "". Equals (Logopath)) {return image;
  }//Insert logo qrcodeutil.insertimage (image, Logopath, needcompress);
 return image; /** * @Title: Insertimage * @Description: Insert logo into two-dimensional code * @param source two-dimensional code image stream * @param imgpath logo address * @p Aram needcompress Compression Size * @throws Exception parameter description * @return void return type * @throws/private static void Insertimag
  E (bufferedimage source, String Logopath, Boolean needcompress) throws Exception {File File = new file (Logopath); if (!file.exists ()) {System.err.println ("+ Logopath +") The file does not exist!
   ");
  Return
  Image src = imageio.read (new File (Logopath));
  int width = src.getwidth (null);
  int height = src.getheight (null); if (needcompress) {//Compress logo if (width &GT
   Logo_width) {WIDTH = Logo_width;
   } if (height > logo_height) {height = logo_height;
   Image image = Src.getscaledinstance (width, height, image.scale_smooth);
   BufferedImage tag = new BufferedImage (width, height, bufferedimage.type_int_rgb);
   Graphics g = tag.getgraphics (); G.drawimage (image, 0, 0, NULL);
   Draw the reduced figure g.dispose ();
  src = image;
  }//Insert logo graphics2d graph = source.creategraphics ();
  int x = (qrcode_size-width)/2;
  int y = (qrcode_size-height)/2;
  Graph.drawimage (src, x, y, width, height, null);
  Shape shape = new Roundrectangle2d.float (x, y, Width, width, 6, 6);
  Graph.setstroke (New Basicstroke (3f));
  Graph.draw (Shape);
 Graph.dispose (); /** * @Title: Mkdirs * @Description: Create folder * @param destpath folder address * @return void return type * @throws/privat
  E Static Boolean mkdirs (String destpath) {File File = new File (destpath); When a folder does not exist, Mkdirs automatically creates a multi-tiered directory, distinguished from mkdir. (MkDir throws an exception if the parent directory does not exist) if (!file.existS () &&!file.isdirectory ()) {file.mkdirs ();
  return true;
 return false;  /** * @Title: Encode * @Description: Generate two-dimensional code * @param content two-dimensional code contents * @param Imgpath logo image address * @param destpath Target Save Address * @param needcompress compress logo picture size * @throws Exception parameter description * @return void return type * @throws/Private St atic void Encode (string content, String Logopath, String destpath, Boolean needcompress) throws Exception {Bufferedimag
  E image = Qrcodeutil.createimage (content, Logopath, needcompress);
   if (Mkdirs (DestPath)) {String file = new Random (). Nextint (99999999) + ". jpg";
  Imageio.write (image, Format_name, new file (DestPath + "/" + file)); }/** * @Title: Encode * @Description: Generate two dimensional code * @param content two-dimensional code contents * @param destpath Target Save address * @throws EXCEP tion parameter description * @return void return type * @throws/public static void encode (string content, String destpath) throws Except
 Ion {Qrcodeutil.encode (content, NULL, DestPath, FALSE); }/** * @TItle:encode * @Description: Generate two-dimensional code * @param content two-dimensional code contents * @param Imgpath logo image address * @param output stream * @param Needcompress Compress logo picture size * @throws Exception parameter description * @return void return type * @throws/public static void encode (St Ring content, String Logopath, OutputStream output, Boolean needcompress) throws Exception {bufferedimage image = Qrcod
  Eutil.createimage (content, Logopath, needcompress);
 Imageio.write (image, format_name, output); /** * @Title: Encode * @Description: Generate a two-dimensional code * @param content two-dimensional code contents * @param output stream * @throws Exception parameters. Ming * @return void return type * @throws/public static void encode (String content, OutputStream output) throws Exception
 {qrcodeutil.encode (content, NULL, output, false); /** * @Title: Decode * @Description: Decoding of two-dimensional codes * @param file Object * @return decoded two-dimensional code content string * @throws Exception parameters Ming * @return String return type * @throws */private 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));
  Hashtable<decodehinttype, string> hints = new Hashtable<decodehinttype, string> ();
  Hints.put (Decodehinttype.character_set, CHARSET);
 Return to New Multiformatreader (). Decode (bitmap, hints). GetText ();  /** * @Title: Decode * @Description: Decoding of two-dimensional codes * @param path file paths * @return * @throws Exception parameter description * @return String return type * @throws/public static String decode (string path) throws Exception {returns Qrcodeutil.decode (new
 File (path)); }
}

Qrcodeservlet.java

Package com.webos.servlet;
Import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Com.webos.util.QRCodeUtil; * * Servlet Implementation class Qrcodeservlet */@WebServlet ("/qrcodeservlet") public class Qrcodeservlet extends Http
 Servlet {private static final long serialversionuid = 1L;
 * * @see Httpservlet#httpservlet () * * * ()/public Qrcodeservlet () {super (); } * * * @see Httpservlet#doget (httpservletrequest request, HttpServletResponse * response) * * protected void doget ( HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {try {String text =
   "Http://www.baidu.com?timestamp=" + system.currenttimemillis ();
  Qrcodeutil.encode (text, Response.getoutputstream ());
  catch (Exception e) {e.printstacktrace (); }}/* @sEE httpservlet#dopost (httpservletrequest request, HttpServletResponse * response) * * protected void DoPost (Httpservle Trequest request, HttpServletResponse response) throws Servletexception, IOException {//TODO auto-generated method Stu
 b doget (request, response); }
}

Above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.