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

Bri*_*n J 11 java android exif android-gallery android-camera-intent

我正在尝试使用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; 




    }
Run Code Online (Sandbox Code Playgroud)

小智 5

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

    ExifInterface exif = new ExifInterface();
    exif.readExif(exifVar.getAbsolutePath());
    exif.setTagValue(ExifInterface.TAG_USER_COMMENT, mString);
    exif.forceRewriteExif(exifVar.getAbsolutePath())); 
Run Code Online (Sandbox Code Playgroud)

这里使用的 ExifInterface 是您刚刚添加的新接口。


Cha*_*lie 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());
Run Code Online (Sandbox Code Playgroud)

无关:

根据您庞大的进口清单:

import android.content.*;
Run Code Online (Sandbox Code Playgroud)

进口

android.content.Context,
android.content.DialogInterface and
android.content.Intent
Run Code Online (Sandbox Code Playgroud)

这使得你的代码变得更短。只是说