如何在Android中使用函数“ getAttribute”从带有exif的img中提取字节数组?

时间:2018-09-18 08:16:17

标签: java android exif

我是Java编程的新手。

我想使用android.media.ExifInterface来保存和恢复一些字节数组作为exif信息。

  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(); 
  }

首先,我使用String(byte[])byte[]转换为String。 然后,我使用函数setAttribute(String tag, String value)保存带有标签TAG_MAKER_NOTE的字符串。 当我要提取byteArray时,我将使用getAttribute(String tag)来获取相应的字符串。

但是我发现如果保存的字节数组如下所示,功能getAttribute(String tag)无法正常工作:

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

返回的字符串仅包含{1,2,3,4}。 0之后丢失数据。字符串的长度为4,而保存的字符串正常。也许字符串以0为结尾?

我想知道是否有解决方案来提取整个字节数组? Whithout 3rd库更好。

1 个答案:

答案 0 :(得分:1)

使用base64编码的字符串代替使用new String(byteArray)转换为String。代码如下:

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