欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android项目实战(五十四):zxing 生成二维码图片去除白色内边距的解决方案

程序员文章站 2023-01-13 12:53:24
目录:zxing->encoding->EncodingHandler类 中修改 createQRCode方法 ......

目录:zxing->encoding->encodinghandler类 中修改 createqrcode方法

   private static final int black = 0xff000000;
    private static final int white = 0xffffffff;

    public static bitmap createqrcode(string str,int widthandheight) throws writerexception {
        string contentstoencode = str;
        if (contentstoencode == null) {
            return null;
        }
        map<encodehinttype, object> hints = new enummap<>(encodehinttype.class);
        //hints.put(encodehinttype.character_set, encoding);
        hints.put(encodehinttype.margin, 0); /* default = 4 */
        multiformatwriter writer = new multiformatwriter();
        bitmatrix result;
        try {
            result = writer.encode(contentstoencode, barcodeformat.qr_code , widthandheight, widthandheight, hints);
        } catch (exception e) {
            // unsupported format
            e.printstacktrace();
            return null;
        }

        int width = result.getwidth();
        int height = result.getheight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = result.get(x, y) ? black : color.white;
            }
        }

        bitmap bitmap = bitmap.createbitmap(width, height,
                bitmap.config.argb_8888);
        bitmap.setpixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }