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

案例代码

相关推荐
时光呀时光慢慢走9 分钟前
MAUI 开发安卓 MQTT 客户端:实现远程控制 (完整源码 + 避坑指南)
android·物联网·mqtt·c#
成都大菠萝28 分钟前
2-2-44 快速掌握Kotlin-函数类型操作
android
有位神秘人1 小时前
Android中获取设备里面的音频文件
android
2501_915918412 小时前
使用 HBuilder 上架 iOS 应用时常见的问题与应对方式
android·ios·小程序·https·uni-app·iphone·webview
farewell-Calm2 小时前
01_Android快速入门
android
helloCat2 小时前
记录CI/CD自动化上传AppGallery遇到的坑
android·前端·api
WordPress学习笔记3 小时前
wordpress根据页面别名获取该页面的链接
android·wordpress
2501_916007473 小时前
iOS 崩溃日志的分析方法,将崩溃日志与运行过程结合分析
android·ios·小程序·https·uni-app·iphone·webview
浅箬4 小时前
Taro3的H5项目在Android、IOS 中因为兼容性问题导致的白屏问题
android·团队开发·taro
技术摆渡人4 小时前
Android 全栈架构终极指南:从 Linux 内核、Binder 驱动到 Framework 源码实战
android·linux·架构