安卓连接蓝牙打印机如何打印图片bitmap?

作者站长头像
站长
· 阅读数 8

打印机打印bitmap的指令是 BITMAP x,y,width,height,mode,bitmap data, 那么将图片转为bitmap后, 如何使用呢

回复
1个回答
avatar
test
2024-06-30
BluetoothDevice device = ... // 获取到的蓝牙设备
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); // 创建一个BluetoothSocket来连接设备
socket.connect(); // 连接到设备

OutputStream outStream = socket.getOutputStream(); // 获取OutputStream来发送数据

Bitmap bitmap = ... // 你的Bitmap对象
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();

// 构造打印指令
String command = String.format("BITMAP 0,0,%d,%d,1,", bitmap.getWidth(), bitmap.getHeight());
byte[] commandData = command.getBytes();

// 发送打印指令
outStream.write(commandData);
outStream.write(bitmapdata);

在打印图片时候,要把Bitmap转换为打印机可以识别的数据格式

把Bitmap转换为点阵图数据:

public byte[] bitmapToBytes(Bitmap bitmap) {
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    byte[] imgbuf = new byte[width * height / 8];
    int[] pixels = new int[width * height];
    bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            int pixel = pixels[y * width + x];
            if (Color.red(pixel) == 0) {
                imgbuf[(y * width + x) / 8] |= (0x80 >> (x % 8));
            }
        }
    }
    return imgbuf;
}

然后,用ESC/POS指令来打印点阵图:

public void printBitmap(OutputStream outStream, Bitmap bitmap) throws IOException {
    byte[] imgbuf = bitmapToBytes(bitmap);
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    byte[] command = new byte[] { 0x1D, 0x76, 0x30, 0x00,
            (byte) (width / 8), (byte) (width / 8 >> 8),
            (byte) (height), (byte) (height >> 8) };
    outStream.write(command);
    outStream.write(imgbuf);
    outStream.write(new byte[] { 0x0A, 0x0A });
}

最后,用这个方法:

BluetoothDevice device = ... // 获取蓝牙设备
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); // 创建一个BluetoothSocket来连接设备
socket.connect(); // 连接到设备

OutputStream outStream = socket.getOutputStream(); // 获取OutputStream来发送数据

Bitmap bitmap = ... // Bitmap对象

printBitmap(outStream, bitmap);
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容