Printing an Image using a Bluetooth Thermal Printer From an Android App?

一个人想着一个人 提交于 2019-11-30 07:27:37
private byte[] printbyte = {(byte)0x1B,(byte)0x2A,(byte)0x6F,(byte)0x63} 

File file = new File(Environment.getExternalStorageDirectory + File.seprator()+"file_name");
FileInputStream fin = new FileInputStream(file);
byte imageContent[] = new byte[(int)file.length()];
fin.read(imageContent);

byte [] width  = hexToBuffer(Integer.toHexString(your_width));
byte [] height = hexToBuffer(Integer.toHexString(your_height));

byte[] imageToPrint = new byte[printbyte.lenght()+imageContent.lenght()+width.lenght()+height.lenght()];

  System.arraycopy(imagetoprint,0,printbyte,0,printbyte.lenght());
  System.arraycopy(imagetoprint,printbyte.lenght(),width ,0,width.lenght());
  System.arraycopy(imagetoprint,width.lenght(),height,0,height.lenght());  
  System.arraycopy(imagetoprint,height.lenght(),imageContent,0,imageContent.lenght()); 

  mmOutputStream.write(imagetoprint);  

Hex to Buffer method -

public static byte[] hexToBuffer(String hexString)
    throws NumberFormatException {
    int length = hexString.length();
    byte[] buffer = new byte[(length + 1) / 2];
    boolean evenByte = true;
    byte nextByte = 0;
    int bufferOffset = 0;

    if ((length % 2) == 1) {
        evenByte = false;
    }

    for (int i = 0; i < length; i++) {
        char c = hexString.charAt(i);
        int nibble; // A "nibble" is 4 bits: a decimal 0..15

        if ((c >= '0') && (c <= '9')) {
            nibble = c - '0';
        } else if ((c >= 'A') && (c <= 'F')) {
            nibble = c - 'A' + 0x0A;
        } else if ((c >= 'a') && (c <= 'f')) {
            nibble = c - 'a' + 0x0A;
        } else {
            throw new NumberFormatException("Invalid hex digit '" + c +
                "'.");
        }

        if (evenByte) {
            nextByte = (byte) (nibble << 4);
        } else {
            nextByte += (byte) nibble;
            buffer[bufferOffset++] = nextByte;
        }

        evenByte = !evenByte;
    }

    return buffer;
}
Mneckoee

I have a thermal printer with bluetooth and Usb connection, if your printer support ESC/POS command search for its commands on internet, for print raster image you should send this:

[Name] Print raster bit image
[Format] ASCII GS v 0 m xL xH yL yH d1...dk
         Hex 1D 76 30 m xL xH yL yH d1...dk
         Decimal 29 118 48 m xL xH yL yH d1...dk
[Range] 0£ m£ 3, 48£ m £ 51
0£ xL£ 255
0£ xH£ 255
0£ yL£ 255
0£ d£ 255
k=(xL+ xH*256)*(yL+yH*256)

Follow your printer guidelines, it is may be different from others.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!