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

案例代码

相关推荐
zgyhc20503 小时前
【Android Audio】dumpsys media.metrics分析
android
nono牛3 小时前
Android Binder 详解与实践指南
android·binder
小镇学者4 小时前
【PHP】PHP WebShell(网页木马)分析
android·开发语言·php
2501_916007475 小时前
iOS 压力测试的工程化体系,构建高强度、多维度、跨工具协同的真实负载测试流程
android·ios·小程序·uni-app·cocoa·压力测试·iphone
毕设源码-钟学长6 小时前
【开题答辩全过程】以 浮生馆汉服租赁管理系统为例,包含答辩的问题和答案
android·java·tomcat
louisgeek7 小时前
Android NDK 开发中的崩溃排查
android
2501_915921438 小时前
iOS 开发者工具推荐,构建从调试到性能优化的多维度生产力工具链(2025 深度工程向)
android·ios·性能优化·小程序·uni-app·iphone·webview
Chrison_mu9 小时前
Android项目背景动效-Kotlin
android·开发语言·kotlin
曾经的三心草10 小时前
JavaEE初阶-多线程2
android·java·java-ee
v***56511 小时前
Spring Cloud Gateway
android·前端·后端