当前位置: 首页 > article >正文

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

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

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

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

写入

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

读取

  Bitmap bitmap = FileUtil.readImage(path);
  iv_content.setImageBitmap(bitmap);

FileUtil

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

案例代码


http://www.kler.cn/news/321724.html

相关文章:

  • 【python】range 语句
  • NLP 生成式任务核心梳理
  • react通过下拉框选择多个,并展示在下方的方式
  • 看Threejs好玩示例,学习创新与技术(React-three-fiber)
  • 【C++篇】从零实现 C++ Vector:深度剖析 STL 的核心机制与优化
  • SpringCloud源码:客户端分析(二)- 客户端源码分析
  • ArduSub程序学习(11)--EKF实现逻辑①
  • [AI问答] Auto-sklearn和Auto-Keras对比
  • Ubuntu20.04.6 环境下docker设置proxy
  • SpringBoot-Starter2.7.3自动装配Redisson升级版本运行时的问题
  • 自动驾驶技术:人工智能驾驶的未来
  • tauri程序加载本地图片或者文件在前端页面展示
  • ModStartCMS v8.9.0 图片上传优化,富文本编辑器修复
  • Spring Boot 实战:使用观察者模式实现实时库存管理
  • localectl 命令:系统语言、键盘布局和区域设置
  • CORE 中间件、wwwroot
  • C++11中引入的thread
  • 正向科技|格雷母线定位系统的设备接线安装示范
  • 脚手架是什么?详细版+通俗易懂版!!!!!!
  • DNS与host文件
  • 职业技能大赛-自动化测试笔记(PageObject)分享-4
  • 如何将自定义支付网关与 WooCommerce Checkout 区块集成
  • HarmonyOS---权限和http/Axios网络请求
  • 处理 VA02修改行项目计划行(SCHEDULE LINES )报错:不可能确定一个消耗帐户
  • count(1)、count(*) 与 count(列名) 的区别
  • zabbix“专家坐诊”第257期问答
  • 19、网络安全合规复盘
  • C++ | Leetcode C++题解之第440题字典序的第K小数字
  • 【HDP】zookeeper未授权漏洞修复
  • C语言课程设计题目四:实验设备管理系统设计