温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android中怎么将图片存储到指定路径

发布时间:2021-06-28 16:34:07 来源:亿速云 阅读:262 作者:Leah 栏目:移动开发

本篇文章为大家展示了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);

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

效果如下所示:

Android中怎么将图片存储到指定路径

5.另外,虽然有吐司提示用户存储路径,但是也会找不到。其实,在用真机测试(不带SD卡),图片存储在手机自带内存==》ememed ==》图片所在。

6.存储SD卡,这类操作往往需要权限。所以,不要忘记在AndroidManifest中配置权限:

   <uses-permission android:name="android.permission.WRITE_SETTINGS" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.READ_OWNER_DATA" />

上述内容就是Android中怎么将图片存储到指定路径,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI