How to convert an image to hexadecimal?

Asked

Viewed 1,597 times

0

Hello, I wonder how to convert an image that is on my memory card in 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 out so she can understand the image and print it out needs to be in hexadecimal format.

  • Look, there’s a gambit. If you have a project open in the Sublime Text 2 editor and in this project there is an image, if you click it, it shows the image Hex.

  • Are you sure it needs to be sent in hexadecimal? You could add the relevant instruction in the printer manual (and/or model) to make the question more complete?

2 answers

1

First you must convert it to an array of bytes, then convert that array of bytes to hexadecimal.

Check if 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

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 that byte array to hexadecimal.

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

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

        return sb.toString();
    }

In short you should proceed to these steps:

String imagem=...;

byte[] imagem_byte=ler_ficheiro(imagem);

if(imagem_byte!=null)
{   
   String imagem_hex=bytesToHex(imagem_byte);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.