Convert /assets/image.png to byte[]

Viewed 8681

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

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 — is declared in package like this:

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

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

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

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

Here is the vendors` tiny documentation.

p.s:I'm newbie in Java.

4 Answers

This works for any type of file in the asset folder

InputStream is = getAssets().open("image.png");
byte[] fileBytes=new byte[is.available()];
is.read( fileBytes);
is.close();
Related