生成二维码图片,并将图片转换成POS机能打印的byte[]类型

来源:互联网 发布:cms二次开发 编辑:程序博客网 时间:2024/06/02 11:02

首先是生成二维码图片:(这里我是用的zxing框架)

 /**     * 生成二维码 要转换的地址或字符串,可以是中文     *     * @param url     * @param width     * @param height     * @return     */    public 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);            return bitmap;        } catch (WriterException e) {            e.printStackTrace();        }        return null;    }

然后就是将Bitmap类型的二维码图片转换成byte[]类型:

 private static byte[] genBitmapCode(Bitmap bm, boolean doubleWidth, boolean doubleHeight) {        int w = bm.getWidth();        int h = bm.getHeight();        if(w > MAX_BIT_WIDTH)            w = MAX_BIT_WIDTH;        int bitw = ((w+7)/8)*8;        int bith = h;        int pitch = bitw / 8;        byte[] cmd = {0x1D, 0x76, 0x30, 0x00, (byte)(pitch&0xff), (byte)((pitch>>8)&0xff), (byte) (bith&0xff), (byte) ((bith>>8)&0xff)};        byte[] bits = new byte[bith*pitch];        // 倍宽        if(doubleWidth)            cmd[3] |= 0x01;        // 倍高        if(doubleHeight)            cmd[3] |= 0x02;        for (int y = 0; y < h; y++) {            for (int x = 0; x < w; x++) {                int color = bm.getPixel(x, y);                if ((color&0xFF) < 128) {                    bits[y * pitch + x/8] |= (0x80 >> (x%8));                }            }        }        ByteBuffer bb = ByteBuffer.allocate(cmd.length+bits.length);        bb.put(cmd);        bb.put(bits);        return bb.array();    }
0 0
原创粉丝点击