MediaStore.Images.保存图片时生成两张图片的问题 并且在oppo手机上时间是1970-01-01 08:00:00

在Android开发中,使用MediaStore.Images保存图片时遇到一个问题,即会生成两张图片,并且在OPPO手机上图片时间显示为1970年1月1日8:00:00。文章介绍了两种正确的解决方法,包括使用方式一和Kotlin语言的工具类ImageUtil。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MediaStore.Images.保存图片时生成两张图片的问题 并且在oppo手机上时间是1970-01-01 08:00:00

正确方式如下

使用方式一


        private void saveImage(String originFilePath) {
   
            File appDir =
                    new File(Environment.getExternalStorageDirectory().getPath() + "/leikebaijing/images");
            if (!appDir.exists()) appDir.mkdirs();
            String fileName;
            long dateTaken = System.currentTimeMillis();
            if (originFilePath.contains("/")) {
   
                fileName = originFilePath.substring(originFilePath.lastIndexOf("/") + 1);
            } else {
   
                fileName = dateTaken + "jpg";
            }
            File file = new File(appDir, fileName);
            if (!file.exists()) {
   
                try {
   
                    file.createNewFile();
                } catch (IOException e) {
   
                    e.printStackTrace();
                }
            }
            if (file.exists()) {
   
                MediaStoreLocal.insertImage(getContentResolver(), ImageUtil.getBitmapFormPath(file.getAbsolutePath()), fileName, null);
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(file);
                intent.setData(uri);
                sendBroadcast(intent);
                ToastUtil.toastShortMessage("图片已保存");
            } else {
   
                ToastUtil.toastShortMessage("图片已过期或不存在");
            }
        }

使用方式二 kotlin语言

  
    /**
     * 保存图片到图库
     */
    private fun saveImageToGallery(context: Context, bmp: Bitmap) {
   
        // 首先保存图片
        var appDir = File(
            Environment.getExternalStorageDirectory(),
            "myqr"
        )
        if (!appDir.exists()) {
   
            appDir.mkdir()
        }
        val fileName = System.currentTimeMillis().toString() + ".jpg"
        val file = File(appDir, fileName)
//        try {
   
//            val fos = FileOutputStream(file)
//            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos)
//            fos.flush()
//            fos.close()
//        } catch (e: FileNotFoundException) {
   
//            e.printStackTrace()
//        } catch (e: IOException) {
   
//            e.printStackTrace()
//        }
        MediaStoreLocal.insertImage(context.getContentResolver(), bmp, fileName, null)
        val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        val uri: Uri = Uri.fromFile(file)
        intent.setData(uri)
        context.sendBroadcast(intent)

        Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show()
    }

工具类


package com.tencent.qcloud.tim.uukit.utils;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 来自系统 {@link   MediaStore.Images.Media}
 * 使用下面方式在oppo手机上会有1970的问题
 * MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), fileName, null);
 */
public class MediaStoreLocal {
   
    private final static String TAG = "MediaStoreLocal";
    public static final String AUTHORITY = "media";
    private static final String CONTENT_AUTHORITY_SLASH = "content://" + AUTHORITY + "/";

    /**
     * The content:// style URI for the "primary" external storage
     * volume.
     */
    public static final Uri EXTERNAL_CONTENT_URI =
            getContentUri("external");

    /**
     * Get the content:// style URI for the image media table on the
     * given volume.
     *
     * @param volumeName the name of the volume to get the URI for
     * @return the URI to the image media table on the given volume
     */
    public static Uri getContentUri(String volumeName) {
   
        return Uri.parse(CONTENT_AUTHORITY_SLASH + volumeName +
                "/images/media");
    }

    /**
     * Insert an image and create a thumbnail for it.
     *
     * @param cr          The content resolver to use
     * @param source      The stream to use for the image
     * @param title       The name of the image
     * @param description The description of the image
     * @return The URL to the newly created image, or <code>null</code> if the image failed to be stored
     * for any reason.
     */
    public static final String insertImage(ContentResolver cr, Bitmap source, String title, String description) {
   
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, title);
        values.put(MediaStore.Images.Media.DISPLAY_NAME, title);
        values.put(MediaStore.Images.Media.DESCRIPTION, description);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        // Add the date meta data to ensure the image is added at the front of the gallery
        values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());

        Uri url = null;
        String stringUrl = null;    /* value to be returned */

        try {
   
            url = cr.insert(EXTERNAL_CONTENT_URI, values);

            if (source != null) {
   
                OutputStream imageOut = cr.openOutputStream(url);
                try {
   
                    source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
                } finally {
   
                    imageOut.close();
                }

                long id = ContentUris.parseId(url);
                // Wait until MINI_KIND thumbnail is generated.
                Bitmap m
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值