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

案例代码

相关推荐
暗碳4 分钟前
安卓usb摄像头/采集卡专用软件
android
李少兄5 分钟前
在 Linux 中精准查找名为 `xxx` 的文件或目录路径
android·linux·adb
2501_916008897 分钟前
App 上架服务行业的实际工作流程与工具选择 从人工代办到跨平台自动化的转变
android·运维·ios·小程序·uni-app·自动化·iphone
zhimingwen16 分钟前
macOS 上安装与配置apksigner (读取APK签名的工具)
android·macos· sha-1
Jomurphys21 分钟前
设计模式 - 享元模式 Flyweight Pattern
android·设计模式·享元模式
Jomurphys22 分钟前
设计模式 - 组合模式 Composite Pattern
android·设计模式·组合模式
.豆鲨包25 分钟前
【Android】深入理解Window和WindowManager
android·java
pandarking1 小时前
[CTF]攻防世界:ez_curl
android·web安全·网络安全
hjlgs9 小时前
framework修改快速验证
android
游戏开发爱好者810 小时前
iOS 开发者的安全加固工具,从源码到成品 IPA 的多层防护体系实践
android·安全·ios·小程序·uni-app·cocoa·iphone