Search code examples
javaandroidexif

How to use function "getAttribute" to extract byte array from img with exif in Android?


I am a newbie in JAVA programing.

And I want to use android.media.ExifInterface to save and restore some byte Array as exif information.

  String str = new String(byteArray);//save
  exif.setAttribute(ExifInterface.TAG_MAKER_NOTE, str);
  exif.saveAttributes();

  String str =exif.getAttribute(ExifInterface.TAG_MAKER_NOTE);//restore
  if(str != null)
  {
    byte[] byteArray = str.getBytes(); 
  }

Firstly I use String(byte[]) to convert byte[] to String. Then I use the function setAttribute(String tag, String value) to save the String with the tag TAG_MAKER_NOTE. And when I want to extract the byteArray,I would use getAttribute(String tag) to get the corresponding string.

But I find the function getAttribute(String tag) can't work correctly if the saved byte array is as below:

 byte[] byteArray = new byte[]{ 1,2,3,4,0,0,5,6};

The returned string only contains {1,2,3,4}. It lose the data after 0 .The length of string is 4 while the saved string is normal. Maybe the string regards 0 as the end ?

And I want to know is there any solution to extract the whole byte array ? Whithout 3rd library is better.


Solution

  • Instead of using new String(byteArray) to convert to String, use a base64 encoded string. The code would look like this:

    byte[] byteArray = new byte[]{1, 2, 3, 4, 0, 0, 5, 6};
    String str = Base64.getEncoder().encodeToString(byteArray);
    System.out.println(str);
    byte[] result = Base64.getDecoder().decode(str);
    System.out.println(Arrays.toString(result));