Android 使用 mime 类型 GIF 保存 MediaStore 图像

Android save MediaStore image with mime type GIF

虽然此代码成功创建了一张图像,该图像也出现在 phone 的图库中,但扩展名是“.jpg”而不是“.gif”。

    File gifFile; // gif file stored in Context.getFilesDir()

    final ContentValues contentValues = new ContentValues();
    contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, "Image" + System.currentTimeMillis());
    contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/gif");

    // Create a new gif image using MediaStore
    final Uri gifContentUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
    // Open a writable stream pointing to the new file created by MediaStore
    OutputStream outputStream = context.getContentResolver().openOutputStream(gifContentUri, "w");
    // Copy the original file from the app private data folder to the file created by MediaStore
    IOUtils.copyFile(new FileInputStream(gifFile), outputStream);

输出文件由 MediaStore 在 Pictures 文件夹中创建。如果我手动将输出文件的扩展名更改为 gif,gif 动画将在 Android 图库中播放。

我觉得我遗漏了一个小细节才能正常工作

删除了 DISPLAY_NAME 行。

添加contentValues.put(MediaStore.MediaColumns.DATA, "/storage/emulated/0/Pictures/Image." + System.currentTimeMillis() + ".gif");

如果子目录存在,它会转到图片目录的子目录contentValues.put(MediaStore.MediaColumns.DATA, "/storage/emulated/0/Pictures/Mine/Image." + System.currentTimeMillis() + ".gif");

对于 Android Q,DATA 列没有用。

String displayName = "Image." + System.currentTimeMillis() + ".gif";
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName);

会在那里做。