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

案例代码

相关推荐
程序员陆业聪2 小时前
你的 Android App 可能白白损失了 35% 的性能——R8 全模式配置详解
android
海兰7 小时前
【实战】MCP 服务在 Nacos 中注册状态分析与优化
android·java·github·银行系统·银行ai
bearpping7 小时前
MySQL压缩版安装详细图解
android·mysql·adb
代码改善世界8 小时前
【matlab初阶】matlab入门知识
android·java·matlab
huwuhang10 小时前
支付宝 APP 谷歌商店版 googleplay版最新
android
User_芊芊君子10 小时前
别再乱用 ArrayList 了!这 4 个隐藏坑,90% 的 Java 开发者都踩过
android·java·数据库
冬天vs不冷10 小时前
为什么 Java 不让 Lambda 和匿名内部类修改外部变量?final 与等效 final 的真正意义
android·java·开发语言
hogenlaw12 小时前
Stream流
android·java·开发语言
常利兵13 小时前
解锁Kotlin:数据类与密封类的奇妙之旅
android·开发语言·kotlin
sunfdf14 小时前
无需密码即可解锁 Android 手机的 5 种方法
android·智能手机