将/assets/image.png 转换为 byte[] [英] Convert /assets/image.png to byte[]

查看:92
本文介绍了将/assets/image.png 转换为 byte[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将/assets/image.png 转换为 byte[] ?

How to convert /assets/image.png to byte[] ?

我已经尝试过(基于在 SO 上找到的解决方案):

I've tried like that (based on solution found on 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 — 在包中声明如下:

printImage — is declared in package like this:

public class Cprinter {
    public native int printImage(byte[] bytes);
}

但应用程序在打印 printimage() 时崩溃,错误是未找到本机方法:android.pt.Cprinter.printImage:([B)I"

But application crashes on print printimage(), error is "Native method not found: android.pt.Cprinter.printImage:([B)I"

我已将字节转换为字符串 (bytesLogo.toString()),此命令的每次执行都会返回不同的结果:[B@40d7c798"、[B@40d848e0"、[B@40d59ff0"、&等

I've converted byte to string (bytesLogo.toString()), every execution of this command returns different results: "[B@40d7c798", "[B@40d848e0", "[B@40d59ff0", & etc.

目的:我有一个带有内部收据打印机的 android 设备.供应商提供了用于开发自己的设备软件的库 (libfile.so) 和示例源.打印简单的文本是可以的,但我在打印图像(徽标)时遇到了麻烦.

Purpose: I have an android device with internal printer of receipts. Vendor has provided library (libfile.so) and sample source for developing own software for device. Printing Simple text is OK, but i have a troubles with printing of an Image (logo).

这里是供应商的小文档.

ps:我是 Java 新手.

p.s:I'm newbie in 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...

这篇关于将/assets/image.png 转换为 byte[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆