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

案例代码

相关推荐
游戏开发爱好者88 小时前
iPhone HTTPS 抓包实战指南,移动端加密流量分析、代理解密失败排查与底层数据流捕获
android·ios·小程序·https·uni-app·iphone·webview
Lei活在当下14 小时前
【Perfetto从入门到精通】2. 使用 Perfetto 追踪/分析 APP 的 Native/Java 内存
android·性能优化·架构
愤怒的代码14 小时前
🔗 深度解析 SystemUI 进程间通信机制(一)
android·操作系统·app
RainyJiang15 小时前
聊聊协程里的 Semaphore:别让协程挤爆门口
android·kotlin
Dev7z17 小时前
在MySQL里创建数据库
android·数据库·mysql
invicinble17 小时前
mysql建立存数据的表(一)
android·数据库·mysql
似霰18 小时前
传统 Hal 开发笔记1----传统 HAL简介
android·hal
Zender Han19 小时前
Flutter Gradients 全面指南:原理、类型与实战使用
android·flutter·ios
火柴就是我19 小时前
Flutter Path.computeMetrics() 的使用注意点
android·flutter
モンキー・D・小菜鸡儿21 小时前
Android 系统TTS(文字转语音)解析
android·tts