如何将/assets/image.png 转换为 byte[] ?
我试过那样(基于在 SO 上找到的解决方案):
public void printimage(View view) {
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("logo_print.png");
byte[] bytesLogo = IOUtils.toByteArray(inputStream);
int ret = printer.printImage(bytesLogo);
if (ret < 0) {
Toast(context, "printimage fail");
}
Toast(context, "image printed :)");
}
catch (IOException e){
Log.e("message: ", e.getMessage());
Toast(context, "printimage: convert image to Bytes fail");
}
}
printImage — 在包中声明如下:
public class Cprinter {
public native int printImage(byte[] bytes);
}
但是应用程序在打印 printimage() 时崩溃,错误是“找不到 native 方法:android.pt.Cprinter.printImage:([B)I”
我已将字节转换为字符串 (bytesLogo.toString()),每次执行此命令都会返回不同的结果:“[B@40d7c798”、“[B@40d848e0”、“[B@40d59ff0”等.
目的: 我有一个带有内部收据打印机的安卓设备。供应商提供了用于为设备开发自己的软件的库 (libfile.so) 和示例源。打印简单的文本没问题,但我在打印图像( Logo )时遇到了麻烦。
Here is the vendors` tiny documentation.
p.s:我是Java新手。
最佳答案
试试这个
InputStream inputStream = getAssets().open("logo_print.png");
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
byte file[] = output.toByteArray();
字节数组包含
1B 2A n ml mh converted data 1B 4A 00
1B 2A -- begin the block
n - printing mode
a) Q110 support 4 kinds of printing modes,as follow:
n=0x21: 24-point double-density;
n=0x20: 24-point single-density;
n=0x01: 8-point double-density;
n=0x00: 8-point single-density;
b) NXP only support n=0x21: 24-point double-density;
converted data
1B 4A 00 end the block and execute print (print start)
像聪明人一样
byte[0] = 0x1B;
byte[1] = 0x2A;
byte[2] = 0x21; // 24-point double-density;
and so on...
关于java - 将/assets/image.png 转换为 byte[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36198637/