生成二维码方法(中文可用)
此方法解决了中文生成二维码解析是乱码的问题,如果不是中文的话可以简单的使用一下方式
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 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步