Android 图片存储到指定路径和相册的方法

我们在平常项目中,可能会存储一些头像,二维码之类的。这篇文章主要也是介绍自己在存储中会遇到的问题以及一些改进方案。

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);

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

效果如下所示:

微信公众号搜索 “ 程序精选 ” ,选择关注!
精选程序员所需精品干货内容!