How to convert an image to hexadecimal?

0

Hello, I would like to know how to convert an image that is on my memory card into hexadecimal.

I have an application that prints a receipt through a thermal printer, it prints some information like date, time, name, value, etc.

And I need in the header to print the company logo.

The printer I use to print for it to understand the image and to be able to print it the image must be in hexadecimal format.

    
asked by anonymous 29.05.2014 / 19:06

2 answers

1

First you must convert it to an array of bytes, then convert this byte array to hex.

Make sure this function helps you:

final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for ( int j = 0; j < bytes.length; j++ ) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

Check the discussion here

    
01.07.2014 / 13:52
0

First you should read the file (image) and convert it to an array of bytes:

public byte[] ler_ficheiro(String path)
{
    File file = new File(path);
    if (file.exists())
    {
      FileInputStream fis = new FileInputStream(file);
      byte[] data = new byte[(int) file.length()];
      fis.read(data);
      fis.close();
      return data;

    } else
    {
       return null;
    }
}

Then convert this byte array to hex.

private String bytesToHex(byte[] bytes)
    {
        StringBuffer sb = new StringBuffer();

        for (byte b : bytes)
        {
            sb.append(String.format("%02X", b));
        }

        return sb.toString();
    }

In summary you should proceed to these steps:

String imagem=...;

byte[] imagem_byte=ler_ficheiro(imagem);

if(imagem_byte!=null)
{   
   String imagem_hex=bytesToHex(imagem_byte);
}
    
08.09.2014 / 17:07