Android 相册图片存储

1. 存储步骤

1.首先是长按保存:这个可以去参照网络上的,无非是自己先要拼接好一个文件路径。注意:IO流只能帮忙建文件,但是不能帮忙建目录(路径)。

        // 先拼接好一个路径:在内存卡/或是手机内存上做好文件夹
        String filePath = Environment.getExternalStorageDirectory()+savePath;
        File localFile = new File(filePath);
        if (!localFile.exists()) {
            localFile.mkdir();
        }

2.引导具体的文件名和路径:

//拼接好文件路径和名称
        File finalImageFile = new File(localFile, System.currentTimeMillis() + ".jpg");
        if (finalImageFile.exists()) {
            finalImageFile.delete();
        }
        try {
            finalImageFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

3.文件的读取:

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(finalImageFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        if (bitmap == null) {
            Toast.makeText(this, "图片不存在", 0).show();
            return;
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        try {
            fos.flush();
            fos.close();
            Toast.makeText(this, "图片保存在:"+ finalImageFile.getAbsolutePath(), 0).show();
        } catch (IOException e) {
            e.printStackTrace();
        }

4.对于图片,我们也希望存储在固定路径之后,希望也可以在相册中查看该图片。这是可以利用一个广播告诉相册有图片更新。

        //发广播告诉相册有图片需要更新,这样可以在图册下看到保存的图片了
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(finalImageFile);
        intent.setData(uri);
        sendBroadcast(intent);

通过以上步骤: 我们可以在指定路径的文件夹和相册中查看存储好的图片了。

效果如下所示:

这里写图片描述

2. 获取原生路径

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容