如何在Android中将exif数据写入图像?

12

我正在尝试使用exif接口在Android应用程序中将User_CommentTAG_GPS写入捕获的图像中,但出现问题的是当我在图库中查看图像的详细信息时,标签似乎没有被添加到图像中。

似乎标签未被写入捕获的图像,因为文件路径可能不正确。我认为这可能是因为我已将标签写入了错误的图像路径。

是否有人知道我写入标签的方式是否有问题?

以下是按照@Charlie更改后保存exif数据的代码:

private File getOutputPhotoFile() throws IOException {
          File directory = new File(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES), getPackageName());
          if (!directory.exists()) {
            if (!directory.mkdirs()) {
              Log.e(TAG, "Failed to create storage directory.");
              return null;
            }
          }


          String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());

          File[] files = directory.listFiles();

          File exifVar =  new File(directory.getPath(), "IMG_" + timeStamp + ".jpg");
          if(files.length!=0) {
              File newestFile = files[files.length-1];
              exifVar =  new File(directory.getPath() + File.separator + newestFile.getName());
          }

          String mString = "Generic Text..";     
          ExifInterface exif = new ExifInterface(exifVar.getAbsolutePath());
          exif.setAttribute("UserComment", mString);
          exif.saveAttributes();


          exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE,
            String.valueOf(latituteField.toString()));

          exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, 
            String.valueOf(longitudeField.toString()));

          exif.saveAttributes();

          return exifVar; 




    }

为什么你要多次调用exif.saveAttributes?我认为这会每次都创建一个新的图像。只是好奇。 - wkhatch
有可能,我已经有一段时间没有在这个项目上工作了。我想问题可能在于数据被保存到一个名为“exif”的临时图像中,但从未写入原始图像。 - Brian Var
3个回答

5

首先需要将位于谷歌exif的文件复制到您的项目中,然后使用以下代码:

    ExifInterface exif = new ExifInterface();
    exif.readExif(exifVar.getAbsolutePath());
    exif.setTagValue(ExifInterface.TAG_USER_COMMENT, mString);
    exif.forceRewriteExif(exifVar.getAbsolutePath())); 

这里使用的ExifInterface是您刚刚添加的新版本。


1
最好能够指定变量“exifi”的数据类型和初始化。 - Deva

2

您正在使用 exifVar.toString()。这将仅返回文件名,而不是图像的路径。由于您的应用程序可能不在带有图片的文件夹中,因此您应该使用exifVar.getAbsolutePath()

如果您没有在运行程序时同时拍摄照片,则路径将不正确。请改用以下代码:

File[] files = directory.listFiles();

if(files.length==0) {
    // No images available
    return;
}

File newestFile = files[files.length-1];

File exifVar =  new File(directory.getPath() + File.separator + newestFile.getName());

题外话:

根据您的大量导入列表:

import android.content.*;

导入

android.content.Context,
android.content.DialogInterface and
android.content.Intent

那样就能让你的代码更短。只是这么说而已。

以上更改后,图像详细信息仍未添加exif数据,您有任何想法吗? - Brian Var

0

请确保您设置了SD卡的写入权限(静态和动态), 此外,对于Android 10,您需要设置以下内容: android:requestLegacyExternalStorage="true"

到清单应用程序中


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接