Android生成二维码及添加logo

来源:互联网 发布:java date 上午下午 编辑:程序博客网 时间:2024/06/13 00:23
    @Override    public Bitmap generateBitmap(String content, int width, int height) {        QRCodeWriter qrCodeWriter = new QRCodeWriter();        Map<EncodeHintType, String> hints = new HashMap<>();        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//默认//        hints.put(EncodeHintType.MARGIN, "1");//无白色边框        try {            BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);            int[] pixels = new int[width * height];            for (int i = 0; i < height; i++) {                for (int j = 0; j < width; j++) {                    if (encode.get(j, i)) {                        pixels[i * width + j] = 0x00000000;                    } else {                        pixels[i * width + j] = 0xffffffff;                    }                }            }            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);        } catch (WriterException e) {            e.printStackTrace();        }        return null;    }    @Override    public Bitmap addLogo(Bitmap qrBitmap, Bitmap logoBitmap) {        int qrBitmapWidth = qrBitmap.getWidth();        int qrBitmapHeight = qrBitmap.getHeight();        int logoBitmapWidth = logoBitmap.getWidth();        int logoBitmapHeight = logoBitmap.getHeight();        Bitmap blankBitmap = Bitmap.createBitmap(qrBitmapWidth, qrBitmapHeight, Bitmap.Config.ARGB_8888);        Canvas canvas = new Canvas(blankBitmap);        canvas.drawBitmap(qrBitmap, 0, 0, null);        canvas.save(Canvas.ALL_SAVE_FLAG);        float scaleSize = 1.0f;        while ((logoBitmapWidth / scaleSize) > (qrBitmapWidth / 3.5) || (logoBitmapHeight / scaleSize) > (qrBitmapHeight / 3.5)) {            scaleSize *= 2;        }        float sx = 1.0f / scaleSize;        canvas.scale(sx, sx, qrBitmapWidth / 2, qrBitmapHeight / 2);        canvas.drawBitmap(logoBitmap, (qrBitmapWidth - logoBitmapWidth) / 2, (qrBitmapHeight - logoBitmapHeight) / 2, null);        canvas.restore();        return blankBitmap;    }

0 0
原创粉丝点击