Android在外部存储上读写图片文件

Android的位图工具是Bitmap,App读写Bitmap可以使用性能更好的BufferedOutputStream和BufferedInputStream。

Android提供了BitmapFactory工具用于读取各种来源的图片,相关方法如下:

  • decodeResource:该方法可从资源文件中读取图片信息
  • decodeFile:该方法可将指定路径的图片读取到Bitmap对象
  • decodeStream:该方法从输入流中读取位图数据

写入

java 复制代码
  String fileName = System.currentTimeMillis() + ".png";
  path = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + File.separator + fileName;
  // 从指定的资源文件中获取位图对象
  Bitmap b1 = BitmapFactory.decodeResource(getResources(), R.drawable.meilv);
  // 把位图对象保存为图片文件
  FileUtil.saveImage(path, b1);

读取

java 复制代码
  Bitmap bitmap = FileUtil.readImage(path);
  iv_content.setImageBitmap(bitmap);

FileUtil

java 复制代码
    public static void saveImage(String path, Bitmap bitmap) {
        try (FileOutputStream fos = new FileOutputStream(path)) {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
java 复制代码
   public static Bitmap readImage(String path) {
        Bitmap bitmap = null;

        try (FileInputStream fis = new FileInputStream(path)) {
            bitmap = BitmapFactory.decodeStream(fis);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

案例代码

相关推荐
黑马源码库miui5208614 分钟前
JAVA成人用品商城系统源码微信小程序+h5+安卓+ios
android·java·微信小程序
h***34631 小时前
怎么下载安装yarn
android·前端·后端
一个平凡而乐于分享的小比特1 小时前
Linux、Debian、Yocto、Buildroot、Android系统详解
android·linux·操作系统·debian·yocto·buildroot
HackShendi1 小时前
Android全局监听音量按键事件
android
七夜zippoe1 小时前
基于MLC-LLM的轻量级大模型手机端部署实战
android·智能手机·架构·大模型·mlc-llm
darryrzhong1 小时前
GalleryPicker:一个基于 Android 官方 Photo Picker API 封装的现代图片/视频选择库
android·kotlin·github·相机
wangchen_01 小时前
MySQL在C/C++中的使用
android
天青Giser10 小时前
Android开发记录
android
子春一11 小时前
Flutter 与原生平台深度集成:打通 iOS 与 Android 的最后一公里
android·flutter·ios
小邓   ༽12 小时前
全场景Android测试:API、工具与案例,从TestCase到Mock类应用指南
android·android 测试·android 组件测试·mock 类·测试 api 应用·组件测试核心