首页 > 解决方案 > 保存到图库 - Android

问题描述

在 Android 上保存到画廊时,我遇到了一个奇怪的(而且奇怪的是)问题。

一点背景知识:我正在开发的应用程序需要能够将图像保存到画廊,这在之前已经很好地讨论过。但是,这个项目有一个特定的要求,我需要能够用特定的日期/时间标记它。

我已经尝试了几种方法来让它正常工作,到目前为止我最好的方法是一种解决方法。

我目前正在做的是生成图像,将其保存到文件中并在 EXIF 数据中设置创建日期。然后我打开 Google Photos 应用程序,它会显示在图库中,显示正确的日期和时间,并且位于图库中的正确位置。

但是,问题在于它不会自动显示在任何其他图库软件中(例如,给定设备可能附带的 OEM 图库应用程序),也不会显示 Google 照片应用程序是否在节省时间;它必须关闭并重新启动才能显示。

现在,如果我运行媒体扫描,它会忽略 EXIF 数据,并且图像显示为最后创建的图像。

这是我目前正在使用的代码:

    static class InsertImageObj{
        public String url;
        public long id;
    }
    public static InsertImageObj insertImage(Bitmap source,
                                           String title, long time) {
        String path = createDirectoryAndSaveFile(source, title, time);

        String stringUrl = path;
        InsertImageObj retVal = new InsertImageObj();
        retVal.url = stringUrl;
        return retVal;
    }

    private static String createDirectoryAndSaveFile(Bitmap imageToSave, String fileName, long dateTime) { 
        File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); //DCIM = Digital Camera Image. This is where camera photos go!
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File file = new File(directory, fileName);
        if (file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(file);
            imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            ExifInterface ei = new ExifInterface(file.getAbsolutePath());
            ei.setAttribute(ExifInterface.TAG_DATETIME, convertToExifDateTime(dateTime));
            ei.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, convertToExifDateTime(dateTime));
            ei.setAttribute(ExifInterface.TAG_DATETIME_DIGITIZED, convertToExifDateTime(dateTime));
            ei.saveAttributes();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }
    private static String convertToExifDateTime(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.getDefault());
        return sdf.format(new Date(timestamp));
    }

我还尝试setLastModified在文件上运行(不起作用,操作系统权限或其他),并MediaScannerConnection在保存后使用实例扫描单个文件。然而,后者会导致系统忽略 Exif 数据中的日期/时间标签。ContentResolver我还尝试通过实例将图像插入图库并设置DATE_ADDEDandDATE_TAKEN字段,再次无济于事。

我在这里错过了什么非常非常明显的东西吗?

标签: android

解决方案


您需要将图像保存在媒体商店提供程序中

使用此功能

public static void imageToGallery(Context context, String fileName) {
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());  
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
    values.put(MediaStore.MediaColumns.DATA, fileName);
    context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}

因此,保存图像后,调用imageToGallery.


推荐阅读