分享

仿微信二维码生成以及条形码生成

 JwwooLIB 2013-11-22
  1. package your.QRCode.namespace;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.util.HashMap;  
  6. import java.util.Map;  
  7.   
  8. import com.google.zxing.BarcodeFormat;  
  9. import com.google.zxing.EncodeHintType;  
  10. import com.google.zxing.MultiFormatWriter;  
  11. import com.google.zxing.WriterException;  
  12. import com.google.zxing.common.BitMatrix;  
  13. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;  
  14. import android.app.Activity;  
  15. import android.content.Context;  
  16. import android.graphics.Bitmap;  
  17. import android.graphics.Bitmap.Config;  
  18. import android.graphics.BitmapFactory;  
  19. import android.graphics.Canvas;  
  20. import android.graphics.Color;  
  21. import android.graphics.Matrix;  
  22. import android.graphics.PointF;  
  23. import android.graphics.Rect;  
  24. import android.graphics.drawable.BitmapDrawable;  
  25. import android.os.Bundle;  
  26. import android.os.Environment;  
  27. import android.util.Log;  
  28. import android.view.Gravity;  
  29. import android.view.View;  
  30. import android.view.View.MeasureSpec;  
  31. import android.view.ViewGroup.LayoutParams;  
  32. import android.widget.Button;  
  33. import android.widget.ImageView;  
  34. import android.widget.LinearLayout;  
  35. import android.widget.TextView;  
  36.   
  37. public class QRCodeTextActivityActivity extends Activity {  
  38.     /** Called when the activity is first created. */  
  39.     Button btn1 = null;  
  40.     Button btn2 = null;  
  41.     ImageView ivImageView = null;  
  42.   
  43.     @Override  
  44.     public void onCreate(Bundle savedInstanceState) {  
  45.         super.onCreate(savedInstanceState);  
  46.         setContentView(R.layout.main);  
  47.         btn1 = (Button) findViewById(R.id.button1);// 条形码  
  48.         btn2 = (Button) findViewById(R.id.button2);// 二维码  
  49.         ivImageView = (ImageView) findViewById(R.id.imageView1);  
  50.         final String strconteString = "c2b0f58a6f09cafd1503c06ef08ac7aeb7ddb91a602dac145551c102143e6159e385cdc294";  
  51.   
  52.         btn1.setOnClickListener(new View.OnClickListener() {  
  53.             public void onClick(View v) {  
  54.                 Bitmap mBitmap = null;  
  55.                 mBitmap = creatBarcode(QRCodeTextActivityActivity.this,  
  56.                         strconteString, 300300true);  
  57.                 if (mBitmap != null) {  
  58.                     ivImageView.setImageBitmap(mBitmap);  
  59.                 }  
  60.             }  
  61.         });  
  62.         btn2.setOnClickListener(new View.OnClickListener() {  
  63.             public void onClick(View v) {  
  64.                 Bitmap mBitmap = null;  
  65.                 try {  
  66.                     if (!strconteString.equals("")) {  
  67.                         mBitmap = Create2DCode(strconteString);  
  68.   
  69.                         // Bitmap bm =  
  70.                         // BitmapFactory.decodeResource(getResources(),  
  71.                         // R.drawable.diagnose1);  
  72.                         ivImageView.setImageBitmap(createBitmap(  
  73.                                 mBitmap,  
  74.                                 zoomBitmap(BitmapFactory.decodeResource(  
  75.                                         getResources(), R.drawable.cccc), 100,100)));  
  76.                     }  
  77.                 } catch (Exception e) {  
  78.                     e.printStackTrace();  
  79.                 }  
  80.             }  
  81.         });  
  82.     }  
  83.   
  84.     public Bitmap Create2DCode(String str) throws WriterException {  
  85.         Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();  
  86.         hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);  
  87.         hints.put(EncodeHintType.CHARACTER_SET, "GBK");  
  88.         // hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");  
  89.         // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败  
  90.         BitMatrix matrix = new MultiFormatWriter().encode(str,  
  91.                 BarcodeFormat.QR_CODE, 500500, hints);  
  92.         int width = matrix.getWidth();  
  93.         int height = matrix.getHeight();  
  94.         // 二维矩阵转为一维像素数组,也就是一直横着排了  
  95.         int[] pixels = new int[width * height];  
  96.         for (int i = 0; i < pixels.length; i++) {  
  97.             pixels[i] = 0xffffffff;  
  98.         }  
  99.         for (int y = 0; y < height; y++) {  
  100.             for (int x = 0; x < width; x++) {  
  101.                 if (matrix.get(x, y)) {  
  102.                     pixels[y * width + x] = 0xff000000;  
  103.                 }  
  104.             }  
  105.         }  
  106.         Bitmap bitmap = Bitmap.createBitmap(width, height,  
  107.                 Bitmap.Config.ARGB_8888);  
  108.         // 通过像素数组生成bitmap,具体参考api  
  109.         bitmap.setPixels(pixels, 0, width, 00, width, height);  
  110.         return bitmap;  
  111.     }  
  112.   
  113.     public File GetCodePath(String name) {  
  114.         String EXTERN_PATH = null;  
  115.         if (Environment.getExternalStorageState().equals(  
  116.                 Environment.MEDIA_MOUNTED) == true) {  
  117.             EXTERN_PATH = android.os.Environment.getExternalStorageDirectory()  
  118.                     .getAbsolutePath() + "/";  
  119.             File f = new File(EXTERN_PATH);  
  120.             if (!f.exists()) {  
  121.                 f.mkdirs();  
  122.             }  
  123.         }  
  124.         return new File(EXTERN_PATH + name);  
  125.     }  
  126.   
  127.     /** 
  128.      * 图片两端所保留的空白的宽度 
  129.      */  
  130.     private int marginW = 20;  
  131.     /** 
  132.      * 条形码的编码类型 
  133.      */  
  134.     private BarcodeFormat barcodeFormat = BarcodeFormat.CODE_128;  
  135.   
  136.     /** 
  137.      * 生成条形码 
  138.      *  
  139.      * @param context 
  140.      * @param contents 
  141.      *            需要生成的内容 
  142.      * @param desiredWidth 
  143.      *            生成条形码的宽带 
  144.      * @param desiredHeight 
  145.      *            生成条形码的高度 
  146.      * @param displayCode 
  147.      *            是否在条形码下方显示内容 
  148.      * @return 
  149.      */  
  150.     public Bitmap creatBarcode(Context context, String contents,  
  151.             int desiredWidth, int desiredHeight, boolean displayCode) {  
  152.         Bitmap ruseltBitmap = null;  
  153.         if (displayCode) {  
  154.             Bitmap barcodeBitmap = encodeAsBitmap(contents, barcodeFormat,  
  155.                     desiredWidth, desiredHeight);  
  156.             Bitmap codeBitmap = creatCodeBitmap(contents, desiredWidth + 2  
  157.                     * marginW, desiredHeight, context);  
  158.             ruseltBitmap = mixtureBitmap(barcodeBitmap, codeBitmap, new PointF(  
  159.                     0, desiredHeight));  
  160.         } else {  
  161.             ruseltBitmap = encodeAsBitmap(contents, barcodeFormat,  
  162.                     desiredWidth, desiredHeight);  
  163.         }  
  164.   
  165.         return ruseltBitmap;  
  166.     }  
  167.   
  168.     /** 
  169.      * 生成显示编码的Bitmap 
  170.      *  
  171.      * @param contents 
  172.      * @param width 
  173.      * @param height 
  174.      * @param context 
  175.      * @return 
  176.      */  
  177.     protected Bitmap creatCodeBitmap(String contents, int width, int height,  
  178.             Context context) {  
  179.         TextView tv = new TextView(context);  
  180.         LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(  
  181.                 LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);  
  182.         tv.setLayoutParams(layoutParams);  
  183.         tv.setText(contents);  
  184.         tv.setHeight(height);  
  185.         tv.setGravity(Gravity.CENTER_HORIZONTAL);  
  186.         tv.setWidth(width);  
  187.         tv.setDrawingCacheEnabled(true);  
  188.         tv.setTextColor(Color.BLACK);  
  189.         tv.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),  
  190.                 MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));  
  191.         tv.layout(00, tv.getMeasuredWidth(), tv.getMeasuredHeight());  
  192.   
  193.         tv.buildDrawingCache();  
  194.         Bitmap bitmapCode = tv.getDrawingCache();  
  195.         return bitmapCode;  
  196.     }  
  197.   
  198.     /** 
  199.      * 生成条形码的Bitmap 
  200.      *  
  201.      * @param contents 
  202.      *            需要生成的内容 
  203.      * @param format 
  204.      *            编码格式 
  205.      * @param desiredWidth 
  206.      * @param desiredHeight 
  207.      * @return 
  208.      * @throws WriterException 
  209.      */  
  210.     protected Bitmap encodeAsBitmap(String contents, BarcodeFormat format,  
  211.             int desiredWidth, int desiredHeight) {  
  212.         final int WHITE = 0xFFFFFFFF;  
  213.         final int BLACK = 0xFF000000;  
  214.   
  215.         MultiFormatWriter writer = new MultiFormatWriter();  
  216.         BitMatrix result = null;  
  217.         try {  
  218.             result = writer.encode(contents, format, desiredWidth,  
  219.                     desiredHeight, null);  
  220.         } catch (WriterException e) {  
  221.             // TODO Auto-generated catch block  
  222.             e.printStackTrace();  
  223.         }  
  224.   
  225.         int width = result.getWidth();  
  226.         int height = result.getHeight();  
  227.         int[] pixels = new int[width * height];  
  228.         // All are 0, or black, by default  
  229.         for (int y = 0; y < height; y++) {  
  230.             int offset = y * width;  
  231.             for (int x = 0; x < width; x++) {  
  232.                 pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;  
  233.             }  
  234.         }  
  235.   
  236.         Bitmap bitmap = Bitmap.createBitmap(width, height,  
  237.                 Bitmap.Config.ARGB_8888);  
  238.         bitmap.setPixels(pixels, 0, width, 00, width, height);  
  239.         return bitmap;  
  240.     }  
  241.   
  242.     /** 
  243.      * 将两个Bitmap合并成一个 
  244.      *  
  245.      * @param first 
  246.      * @param second 
  247.      * @param fromPoint 
  248.      *            第二个Bitmap开始绘制的起始位置(相对于第一个Bitmap) 
  249.      * @return 
  250.      */  
  251.     protected Bitmap mixtureBitmap(Bitmap first, Bitmap second, PointF fromPoint) {  
  252.         if (first == null || second == null || fromPoint == null) {  
  253.             return null;  
  254.         }  
  255.         Bitmap newBitmap = Bitmap.createBitmap(  
  256.                 first.getWidth() + second.getWidth() + marginW,  
  257.                 first.getHeight() + second.getHeight(), Config.ARGB_4444);  
  258.         Canvas cv = new Canvas(newBitmap);  
  259.         cv.drawBitmap(first, marginW, 0null);  
  260.         cv.drawBitmap(second, fromPoint.x, fromPoint.y, null);  
  261.         cv.save(Canvas.ALL_SAVE_FLAG);  
  262.         cv.restore();  
  263.   
  264.         return newBitmap;  
  265.     }  
  266.   
  267.     /*** 仿微信二维码开始 ***/  
  268.     // 图片剪切  
  269.     public  Bitmap cutBitmap(Bitmap mBitmap, Rect r, Bitmap.Config config) {  
  270.         int width = r.width();  
  271.         int height = r.height();  
  272.         Bitmap croppedImage = Bitmap.createBitmap(width, height, config);  
  273.         Canvas cvs = new Canvas(croppedImage);  
  274.         Rect dr = new Rect(00, width, height);  
  275.         cvs.drawBitmap(mBitmap, r, dr, null);  
  276.         return croppedImage;  
  277.     }  
  278.   
  279.     /*** 
  280.      * 合并图片 
  281.      *  
  282.      * @param src 
  283.      * @param watermark 
  284.      * @return 
  285.      */  
  286.     private Bitmap createBitmap(Bitmap src, Bitmap watermark) {  
  287.         String tag = "createBitmap";  
  288.         Log.d(tag, "create a new bitmap");  
  289.         if (src == null) {  
  290.             return null;  
  291.         }  
  292.         int w = src.getWidth();  
  293.         int h = src.getHeight();  
  294.         int ww = watermark.getWidth();  
  295.         int wh = watermark.getHeight();  
  296.         // create the new blank bitmap  
  297.         Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图  
  298.         Canvas cv = new Canvas(newb);  
  299.   
  300.         // draw src into  
  301.         cv.drawBitmap(src, 00null);// 在 0,0坐标开始画入src  
  302.   
  303.         // 在src的中间画watermark  
  304.         cv.drawBitmap(watermark, w / 2 - ww / 2, h / 2 - wh / 2null);// 设置ic_launcher的位置  
  305.   
  306.         // save all clip  
  307.         cv.save(Canvas.ALL_SAVE_FLAG);// 保存  
  308.         // store  
  309.         cv.restore();// 存储  
  310.         return newb;  
  311.     }  
  312.   
  313.     /*** 
  314.      * 缩放图片 
  315.      *  
  316.      * @param src 
  317.      * @param destWidth 
  318.      * @param destHeigth 
  319.      * @return 
  320.      */  
  321.     private Bitmap zoomBitmap(Bitmap src, int destWidth, int destHeigth) {  
  322.         String tag = "lessenBitmap";  
  323.         if (src == null) {  
  324.             return null;  
  325.         }  
  326.         int w = src.getWidth();// 源文件的大小  
  327.         int h = src.getHeight();  
  328.         // calculate the scale - in this case = 0.4f  
  329.         float scaleWidth = ((float) destWidth) / w;// 宽度缩小比例  
  330.         float scaleHeight = ((float) destHeigth) / h;// 高度缩小比例  
  331.         Log.d(tag, "bitmap width is :" + w);  
  332.         Log.d(tag, "bitmap height is :" + h);  
  333.         Log.d(tag, "new width is :" + destWidth);  
  334.         Log.d(tag, "new height is :" + destHeigth);  
  335.         Log.d(tag, "scale width is :" + scaleWidth);  
  336.         Log.d(tag, "scale height is :" + scaleHeight);  
  337.         Matrix m = new Matrix();// 矩阵  
  338.         m.postScale(scaleWidth, scaleHeight);// 设置矩阵比例  
  339.         Bitmap resizedBitmap = Bitmap.createBitmap(src, 00, w, h, m, true);// 直接按照矩阵的比例把源文件画入进行  
  340.         return resizedBitmap;  
  341.     }  
  342.   
  343. }  


  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas./apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" android:background="#ffffff">  
  6.   
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="@string/hello" />  
  11.   
  12.     <Button  
  13.         android:id="@+id/button1"  
  14.         android:layout_width="match_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:text="条形码" />  
  17.   
  18.   
  19.     <Button  
  20.         android:id="@+id/button2"  
  21.         android:layout_width="match_parent"  
  22.         android:layout_height="wrap_content"  
  23.         android:text="二维码" />  
  24.   
  25.   
  26.     <RelativeLayout  
  27.         android:layout_width="match_parent"  
  28.         android:layout_height="match_parent" >  
  29.   
  30.   
  31.         <ImageView  
  32.             android:id="@+id/imageView1"  
  33.             android:layout_width="wrap_content"  
  34.             android:layout_height="wrap_content"  
  35.             android:layout_centerHorizontal="true"  
  36.             android:layout_centerVertical="true"  
  37.             android:scaleType="fitXY"  
  38.             android:src="@drawable/ic_launcher" />  
  39.   
  40.     </RelativeLayout>  
  41.   
  42. </LinearLayout>  


图片美工做下处理。貌似需要做一个描边。png透明背景

源码:

http://download.csdn.net/download/fuweiping/4690213

在加两个方法

  1. /*** 
  2.      * 缩放图片并加描边 
  3.      *  
  4.      * @param src 
  5.      * @param destWidth 
  6.      * @param destHeigth 
  7.      * @return 
  8.      */  
  9.     private Bitmap zoomBitmapBorder(Bitmap src, int destWidth, int destHeigth) {  
  10.         String tag = "lessenBitmap";  
  11.         if (src == null) {  
  12.             return null;  
  13.         }  
  14.         int w = src.getWidth();// 源文件的大小  
  15.         int h = src.getHeight();  
  16.         // calculate the scale - in this case = 0.4f  
  17.         float scaleWidth = ((float) destWidth - 4) / w;// 宽度缩小比例  
  18.         float scaleHeight = ((float) destHeigth - 4) / h;// 高度缩小比例  
  19.         Log.d(tag, "bitmap width is :" + w);  
  20.         Log.d(tag, "bitmap height is :" + h);  
  21.         Log.d(tag, "new width is :" + destWidth);  
  22.         Log.d(tag, "new height is :" + destHeigth);  
  23.         Log.d(tag, "scale width is :" + scaleWidth);  
  24.         Log.d(tag, "scale height is :" + scaleHeight);  
  25.         Matrix m = new Matrix();// 矩阵  
  26.         m.postScale(scaleWidth, scaleHeight);// 设置矩阵比例  
  27.         Bitmap resizedBitmap = Bitmap.createBitmap(src, 00, w, h, m, true);// 直接按照矩阵的比例把源文件画入进行  
  28.   
  29.         Bitmap newb = Bitmap.createBitmap(destWidth, destHeigth,  
  30.                 Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图  
  31.         Canvas cv = new Canvas(newb);  
  32.         //cv.drawColor(R.color.white);  
  33. cv.drawRGB(0,128,128);  
  34.         cv.drawBitmap(resizedBitmap, 22null);// 设置ic_launcher的位置  
  35.   
  36.         // save all clip  
  37.         cv.save(Canvas.ALL_SAVE_FLAG);// 保存  
  38.         // store  
  39.         cv.restore();// 存储  
  40.   
  41.         return getRoundedCornerBitmap(newb);  
  42.     }  
  43.   
  44.     /** 
  45.      * 图片圆角 
  46.      * @param bitmap 
  47.      * @return 
  48.      */  
  49.     public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {  
  50.         Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),  
  51.                 bitmap.getHeight(), Config.ARGB_8888);  
  52.         Canvas canvas = new Canvas(output);  
  53.         final int color = 0xff424242;  
  54.         final Paint paint = new Paint();  
  55.         final Rect rect = new Rect(00, bitmap.getWidth(), bitmap.getHeight());  
  56.         final RectF rectF = new RectF(rect);  
  57.         final float roundPx = 12;  
  58.         paint.setAntiAlias(true);  
  59.         canvas.drawARGB(0000);  
  60.         paint.setColor(color);  
  61.         canvas.drawRoundRect(rectF, roundPx, roundPx, paint);  
  62.         paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));  
  63.         canvas.drawBitmap(bitmap, rect, rect, paint);  
  64.         return output;  
  65.   
  66.     }  


http://blog.csdn.net/fuweiping/article/details/8115619

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约