Android 地址或字串生成二維碼
阿新 • • 發佈:2019-01-31
首先新增jar包
生成bitmap方法,直接賦值即可
public static Bitmap createQRImage(String url, final int width, final int height) { try { // 判斷URL合法性 if (url == null || "".equals(url) || url.length() < 1) { return null; } Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType,String>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 影象資料轉換,使用了矩陣轉換 BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints); int[] pixels = new int[width * height]; // 下面這裡按照二維碼的演算法,逐個生成二維碼的圖片, // 兩個for迴圈是圖片橫列掃描的結果 for (int y = 0; y < height;y++) { for (int x = 0; x < width; x++) { if (bitMatrix.get(x, y)) { pixels[y * width + x] = 0xff000000; } else { pixels[y * width + x] = 0xffffffff; } } } // 生成二維碼圖片的格式,使用ARGB_8888 Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); Log.e("bit", "createQRImage: "+bitmap.toString()); return bitmap; } catch (WriterException e) { e.printStackTrace(); } return null; }
/** * 在二維碼中間新增Logo圖案 */ private static Bitmap addLogo(Bitmap src, Bitmap logo) { if (src == null) { return null; } if (logo == null) { return src; } //獲取圖片的寬高 int srcWidth = src.getWidth(); int srcHeight = src.getHeight(); int logoWidth = logo.getWidth(); int logoHeight = logo.getHeight(); if (srcWidth == 0 || srcHeight == 0) { return null; } if (logoWidth == 0 || logoHeight == 0) { return src; } //logo大小為二維碼整體大小的1/5 float scaleFactor = srcWidth * 1.0f / 5 / logoWidth; Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888); try { Canvas canvas = new Canvas(bitmap); canvas.drawBitmap(src, 0, 0, null); canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2); canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null); canvas.save(Canvas.ALL_SAVE_FLAG); canvas.restore(); } catch (Exception e) { bitmap = null; e.getStackTrace(); } return bitmap; }
jar包下載地址:點選開啟連結