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

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


回答:

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);

以上是 安卓连接蓝牙打印机如何打印图片bitmap? 的全部内容, 来源链接: utcz.com/p/945255.html

回到顶部