生成二維碼方法(中文可用)
此方法解決了中文生成二維碼解析是亂碼的問題,如果不是中文的話可以簡單的使用一下方式
1 /** 2 * 用字符串生成二維碼 3 * 4 * @param str 5 * @author zhouzhe@lenovo-cw.com 6 * @return 7 * @throws WriterException 8 */ 9 public Bitmap Create2DCode(String str) throws WriterException { 10 // new String(obj.getText().getBytes("ISO-8859-1"),"GBK") 11 // 生成二維矩陣,編碼時指定大小,不要生成了圖片以后再進行縮放,這樣會模糊導致識別失敗 12 BitMatrix matrix = new MultiFormatWriter().encode(str, 13 BarcodeFormat.QR_CODE, 250, 250); 14 int width = matrix.getWidth(); 15 int height = matrix.getHeight(); 16 // 二維矩陣轉為一維像素數組,也就是一直橫著排了 17 int[] pixels = new int[width * height]; 18 for (int y = 0; y < height; y++) { 19 for (int x = 0; x < width; x++) { 20 if (matrix.get(x, y)) { 21 pixels[y * width + x] = 0xff000000; 22 } 23 } 24 } 25 Bitmap bitmap = Bitmap.createBitmap(width, height, 26 Bitmap.Config.ARGB_8888); 27 // 通過像素數組生成bitmap,具體參考api 28 bitmap.setPixels(pixels, 0, width, 0, 0, width, height); 29 return bitmap; 30 31 }
解決中文亂碼的問題
1 /** 2 * 用字符串生成二維碼 3 * 4 * @param str 5 * @author zhouzhe@lenovo-cw.com 6 * @return 7 * @throws WriterException 8 */ 9 public Bitmap Create2DCode(String str) throws WriterException { 10 // new String(obj.getText().getBytes("ISO-8859-1"),"GBK") 11 // 生成二維矩陣,編碼時指定大小,不要生成了圖片以后再進行縮放,這樣會模糊導致識別失敗 12 BitMatrix matrix = new MultiFormatWriter().encode(new String(str.getBytes("UTF-8"),"ISO-8859-1"), 13 BarcodeFormat.QR_CODE, 250, 250); 14 int width = matrix.getWidth(); 15 int height = matrix.getHeight(); 16 // 二維矩陣轉為一維像素數組,也就是一直橫著排了 17 int[] pixels = new int[width * height]; 18 for (int y = 0; y < height; y++) { 19 for (int x = 0; x < width; x++) { 20 if (matrix.get(x, y)) { 21 pixels[y * width + x] = 0xff000000; 22 } 23 } 24 } 25 Bitmap bitmap = Bitmap.createBitmap(width, height, 26 Bitmap.Config.ARGB_8888); 27 // 通過像素數組生成bitmap,具體參考api 28 bitmap.setPixels(pixels, 0, width, 0, 0, width, height); 29 return bitmap; 30 31 }

浙公網安備 33010602011771號