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

案例代码

相关推荐
清空mega1 小时前
第15章 综合项目——网上订餐系统
android
f***45322 小时前
基于SpringBoot和PostGIS的各省与地级市空间距离分析
android·前端·后端
珹洺3 小时前
Java-Spring入门指南(三十一)Android意图(Intent)
android·java·spring
b***9105 小时前
【SpringBoot3】Spring Boot 3.0 集成 Mybatis Plus
android·前端·后端·mybatis
q***73555 小时前
删除文件夹,被提示“需要来自 TrustedInstaller 的权限。。。”的解决方案
android·前端·后端
Android系统攻城狮6 小时前
Android内核进阶之获取当前PCM周期snd_pcm_lib_period_bytes:用法实例(九十三)
android·pcm·android内核·音频进阶·alsa音频
源码君miui520866 小时前
JAVA国际版同城服务同城信息同城任务发布平台APP源码Android + IOS
android·java·ios
FrameNotWork7 小时前
Android Repo Manifest 文件详解(基于 Redroid 定制示例)
android
沐怡旸8 小时前
【底层机制】Android OTA更新系统:原理与应用深度解析
android·面试
q***31149 小时前
【Springboot3+vue3】从零到一搭建Springboot3+vue3前后端分离项目之后端环境搭建
android·前端·后端