Android Imitation micro-letter two-dimensional code and barcode _android

Source: Internet
Author: User

This example for you to share the Android imitation micro-letter two-dimensional code and barcode code, for your reference, the specific content as follows

Package your.

Qrcode.namespace;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import Java.util.HashMap;

Import Java.util.Map;
Import Com.google.zxing.BarcodeFormat;
Import Com.google.zxing.EncodeHintType;
Import Com.google.zxing.MultiFormatWriter;
Import com.google.zxing.WriterException;
Import Com.google.zxing.common.BitMatrix;
Import Com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
Import android.app.Activity;
Import Android.content.Context;
Import Android.graphics.Bitmap;
Import Android.graphics.Bitmap.Config;
Import Android.graphics.BitmapFactory;
Import Android.graphics.Canvas;
Import Android.graphics.Color;
Import Android.graphics.Matrix;
Import Android.graphics.PointF;
Import Android.graphics.Rect;
Import android.graphics.drawable.BitmapDrawable;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.util.Log;
Import android.view.Gravity;
Import Android.view.View;
Import Android.view.View.MeasureSpec;
Import Android.view.ViewGroup.LayoutParams; ImPort Android.widget.Button;
Import Android.widget.ImageView;
Import Android.widget.LinearLayout;

Import Android.widget.TextView;  The public class Qrcodetextactivityactivity extends activity {/** called the ' when the ' is the ' The activity ' is the ' the '
 = NULL;
 Button btn2 = null;

 ImageView Ivimageview = null;
 @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 Setcontentview (R.layout.main); BTN1 = (Button) Findviewbyid (r.id.button1);//Barcode BTN2 = (Button) Findviewbyid (r.id.button2);//Two-dimensional code Ivimageview = (Image
 View) Findviewbyid (R.ID.IMAGEVIEW1);

 Final String strcontestring = "c2b0f58a6f09cafd1503c06ef08ac7aeb7ddb91a602dac145551c102143e6159e385cdc294";
  Btn1.setonclicklistener (New View.onclicklistener () {public void OnClick (View v) {Bitmap mbitmap = null;
  Mbitmap = Creatbarcode (Qrcodetextactivityactivity.this, strcontestring, +, true);
  if (Mbitmap!= null) {Ivimageview.setimagebitmap (MBITMAP);
 }
  }
 }); BTn2.setonclicklistener (New View.onclicklistener () {public void OnClick (View v) {Bitmap mbitmap = null;

   try {if (!strcontestring.equals ("")) {Mbitmap = Create2dcode (strcontestring);
   Bitmap BM =//Bitmapfactory.decoderesource (Getresources (),//R.DRAWABLE.DIAGNOSE1); Ivimageview.setimagebitmap (CreateBitmap (Mbitmap, Zoombitmap Bitmapfactory.decoderesource (GetResources (), R.
   DRAWABLE.CCCC), 100,100));
  } catch (Exception e) {e.printstacktrace ();
 }
  }
 }); Public Bitmap Create2dcode (String str) throws Writerexception {map<encodehinttype, object> hints = new HashMap
 <encodehinttype, object> ();
 Hints.put (Encodehinttype.error_correction, ERRORCORRECTIONLEVEL.L);
 Hints.put (Encodehinttype.character_set, "GBK");
 Hints.put (Encodehinttype.character_set, "UTF-8"); Generate a two-dimensional matrix, specify the size of the encoding, do not generate a picture and then zoom, which will blur the recognition failure Bitmatrix matrix = new Multiformatwriter (). Encode (str, barcodeformat.qr_
 CODE, hints, and so on; int Width = matrix.getwidth ();
 int height = matrix.getheight ();
 The two-dimensional matrix is transformed into one-dimensional pixel group, which is the int[] pixels = new int[width * height];
 for (int i = 0; i < pixels.length i++) {pixels[i] = 0xFFFFFFFF; for (int y = 0; y < height; y++) {for (int x = 0; x < width = x +) {if (Matrix.get (x, y)) {Pixels[y * WI
  DTH + x] = 0xff000000;
 }} Bitmap Bitmap = Bitmap.createbitmap (width, height, Bitmap.Config.ARGB_8888);
 Generate bitmap through the number of pixels, specific reference API Bitmap.setpixels (pixels, 0, width, 0, 0, width, height);
 return bitmap;
 Public File Getcodepath (string name) {string extern_path = null; if (Environment.getexternalstoragestate (). Equals (environment.media_mounted) = = True) {Extern_path = Android.os.Envir
  Onment.getexternalstoragedirectory (). GetAbsolutePath () + "/";
  File F = new file (Extern_path);
  if (!f.exists ()) {f.mkdirs ();
 } return new File (Extern_path + name);
 /** * The blank width reserved on both ends of the picture * * Private int marginw = 20; /** * Barcode Code type * Private BarCodeformat Barcodeformat = barcodeformat.code_128; /** * Generate Barcode * * @param context * @param contents * What needs to be generated * @param desiredwidth * Generate barcode Broadband * @param de  Siredheight * Generates barcode height * @param displaycode * Whether the content is displayed below the barcode * @return/Public Bitmap Creatbarcode
 Context, String contents, int desiredwidth, int desiredheight, Boolean displaycode) {Bitmap = null;
  if (displaycode) {Bitmap Barcodebitmap = encodeasbitmap (contents, Barcodeformat, Desiredwidth, desiredheight);
  Bitmap Codebitmap = creatcodebitmap (contents, Desiredwidth + 2 * marginw, desiredheight, context);
 Ruseltbitmap = Mixturebitmap (Barcodebitmap, Codebitmap, New PointF (0, desiredheight));
 else {Ruseltbitmap = Encodeasbitmap (contents, Barcodeformat, Desiredwidth, desiredheight);
 return ruseltbitmap; /** * Generate display encoded BITMAP * * @param contents * @param width * @param height * @param context * @return * * Protect Ed Bitmap CreatcodebiTMap (String contents, int width, int height, context context) {TextView TV = new TextView (context); Linearlayout.layoutparams layoutparams = new Linearlayout.layoutparams (layoutparams.fill_parent, LayoutParams.WRAP_
 CONTENT);
 Tv.setlayoutparams (Layoutparams);
 Tv.settext (contents);
 Tv.setheight (height);
 Tv.setgravity (gravity.center_horizontal);
 Tv.setwidth (width);
 Tv.setdrawingcacheenabled (TRUE);
 Tv.settextcolor (Color.Black); Tv.measure (Measurespec.makemeasurespec (0, measurespec.unspecified), Measurespec.makemeasurespec (0,
 measurespec.unspecified));

 Tv.layout (0, 0, tv.getmeasuredwidth (), Tv.getmeasuredheight ());
 Tv.builddrawingcache ();
 Bitmap Bitmapcode = Tv.getdrawingcache ();
 return bitmapcode; /** * Generates barcode bitmap * * @param contents * What needs to be generated * @param format * encoding format * @param desiredwidth * @pa Ram Desiredheight * @return * @throws writerexception/protected Bitmap Encodeasbitmap (String contents, Barcodeforma t format, int desiredwidth, int desiredheight) {final int white = 0xFFFFFFFF;

 Final int black = 0xff000000;
 Multiformatwriter writer = new Multiformatwriter ();
 Bitmatrix result = null;
 try {result = Writer.encode (contents, format, desiredwidth, desiredheight, NULL);
 catch (Writerexception e) {//TODO auto-generated catch block E.printstacktrace ();
 int width = result.getwidth ();
 int height = result.getheight ();
 int[] pixels = new int[width * height];
  All are 0, or black, by default for (int y = 0; y < height; y++) {int offset = y * width; for (int x = 0; x < width + x + +) {Pixels[offset + x] = Result.get (x, y)?
  Black:white;
 } Bitmap Bitmap = Bitmap.createbitmap (width, height, Bitmap.Config.ARGB_8888);
 Bitmap.setpixels (pixels, 0, width, 0, 0, width, height);
 return bitmap; /** * Merge two bitmap into one * @param first * @param second * @param frompoint * The starting position of the second bitmap to start drawing (relative to number one bitmap * * @return/protected Bitmap Mixturebitmap (BITMAP)Bitmap Second, PointF frompoint) {if (a = null | | | second = NULL | | | frompoint = NULL) {return null; Bitmap Newbitmap = Bitmap.createbitmap (first.getwidth () + second.getwidth () + MARGINW, First.getheight () + second.
 GetHeight (), config.argb_4444);
 Canvas CV = new Canvas (NEWBITMAP);
 Cv.drawbitmap (MARGINW, 0, NULL);
 Cv.drawbitmap (second, frompoint.x, frompoint.y, NULL);
 Cv.save (Canvas.all_save_flag);

 Cv.restore ();
 return newbitmap; /*** Imitation micro-letter two-dimensional code start ***///Picture Shearing public Bitmap cutbitmap (Bitmap mbitmap, Rect R, Bitmap.config Config) {int width = R.wi
 DTH ();
 int height = r.height ();
 Bitmap croppedimage = bitmap.createbitmap (width, height, config);
 Canvas cvs = new Canvas (croppedimage);
 Rect dr = new Rect (0, 0, width, height);
 Cvs.drawbitmap (Mbitmap, R, Dr, NULL);
 return croppedimage; /*** * Merge Pictures * * @param src * @param watermark * @return * * Private Bitmap CreateBitmap (Bitmap src, Bitmap wate
 Rmark) {String tag = ' CreateBitmap '; Log.d(Tag, "Create a new bitmap");
 if (src = null) {return null;
 int w = src.getwidth ();
 int h = src.getheight ();
 int ww = Watermark.getwidth ();
 int wh = Watermark.getheight (); The Create the new blank bitmap bitmap newb = Bitmap.createbitmap (W, H, config.argb_8888);//Creates a new bitmap with the same width as src length Canvas c

 v = new Canvas (NEWB); Draw src into cv.drawbitmap (src, 0, 0, NULL);//at 0, 0 coordinates begin to draw into SRC//in the middle of SRC Watermark cv.drawbitmap (watermark, W/2 -WW/2, H/2-WH/2, NULL);//Set Ic_launcher position/Save All Clip cv.save (canvas.all_save_flag);//Store CV.
 Restore ();//store return NEWB; /*** * Zoom picture * * @param src * @param destwidth * @param destheigth * @return/private Bitmap Zoombitmap (bitm
 AP src, int destwidth, int destheigth) {String tag = "Lessenbitmap";
 if (src = null) {return null;
 int w = src.getwidth ();//source file size int h = src.getheight (); Calculate the scale-in this case = 0.4f float ScaleWidth = ((float) destwidth)/w;//Width zoom FLOat ScaleHeight = ((float) destheigth)/h;//height reduction ratio log.d (tag, "Bitmap width is:" + W);
 LOG.D (Tag, "bitmap height is:" + h);
 LOG.D (Tag, "New width is:" + destwidth);
 LOG.D (Tag, "New height is:" + destheigth);
 LOG.D (Tag, "scale width is:" + scalewidth);
 LOG.D (tag, "scale height is:" + scaleheight); Matrix M = new Matrix ()//Matrix M.postscale (ScaleWidth, ScaleHeight);//set matrices proportional Bitmap Resizedbitmap = Bitmap.createbitmap (
 SRC, 0, 0, W, H, M, true);//directly according to the proportion of the matrix to the source file into the return resizedbitmap;

 }

}
<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertical " android:background= "#ffffff" > <textview android:layout_width= "fill_parent android:layout_height=" Wrap_co Ntent "android:text=" @string/hello "/> <button android:id=" @+id/button1 "android:layout_width=" Match_ 
    Parent "android:layout_height=" wrap_content "android:text=" barcode "/> <button android:id=" @+id/button2 " Android:layout_width= "Match_parent" android:layout_height= "wrap_content" android:text= "Two-dimensional code"/> <Rel
      Ativelayout android:layout_width= "match_parent" android:layout_height= "match_parent" > <ImageView
      Android:id= "@+id/imageview1" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:layout_centerhorizontal= "true"
      Android:layout_centervertical= "true" android:scaletype= "Fitxy" android:src= "@drawable/ic_launcher"/&gt

  ;
 </RelativeLayout> </LinearLayout>

Picture art to do under processing. It looks like you need to make a stroke. PNG Transparent Background

In addition to two methods

/*** * Zoom picture and add stroke * * @param src * @param destwidth * @param destheigth * @return/private Bitmap Zoombitmapbord
 ER (Bitmap src, int destwidth, int destheigth) {String tag = "Lessenbitmap";
 if (src = null) {return null;
 int w = src.getwidth ();//source file size int h = src.getheight (); Calculate the scale-in this case = 0.4f float ScaleWidth = ((float) destWidth-4)/w;//width narrowing ratio float ScaleHeight
 = ((float) destHeigth-4)/h;//height reduction ratio log.d (tag, "Bitmap width is:" + W);
 LOG.D (Tag, "bitmap height is:" + h);
 LOG.D (Tag, "New width is:" + destwidth);
 LOG.D (Tag, "New height is:" + destheigth);
 LOG.D (Tag, "scale width is:" + scalewidth);
 LOG.D (tag, "scale height is:" + scaleheight); Matrix M = new Matrix ()//Matrix M.postscale (ScaleWidth, ScaleHeight);//set matrices proportional Bitmap Resizedbitmap = Bitmap.createbitmap ( SRC, 0, 0, W, H, M, true)//directly draw the source file in the proportion of the matrix to Bitmap newb = Bitmap.createbitmap (Destwidth, Destheigth, config.argb_88 88)//Create a new bitmap with the same width as src length Canvas CV = new Canvas (NEWB);
Cv.drawcolor (R.color.white);
 Cv.drawrgb (0,128,128); Cv.drawbitmap (Resizedbitmap, 2, 2, NULL);//Set Ic_launcher position/Save All Clip cv.save (canvas.all_save_flag);//save//s
 Tore Cv.restore ()//Storage return Getroundedcornerbitmap (NEWB); /** * Picture Fillet * @param bitmap * @return * * public static bitmap Getroundedcornerbitmap (bitmap bitmap) {bitmap OUTP
 UT = Bitmap.createbitmap (Bitmap.getwidth (), Bitmap.getheight (), config.argb_8888);
 Canvas Canvas = new Canvas (output);
 final int color = 0xff424242;
 Final Paint Paint = new Paint ();
 Final Rect Rect = new Rect (0, 0, bitmap.getwidth (), Bitmap.getheight ());
 Final RECTF RECTF = new RECTF (rect);
 Final float roundpx = 12;
 Paint.setantialias (TRUE);
 Canvas.drawargb (0, 0, 0, 0);
 Paint.setcolor (color);
 Canvas.drawroundrect (RECTF, ROUNDPX, ROUNDPX, paint);
 Paint.setxfermode (New Porterduffxfermode (mode.src_in));
 Canvas.drawbitmap (Bitmap, rect, rect, paint);

 return output;
 }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.