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

案例代码

相关推荐
冬奇Lab7 小时前
稳定性性能系列之六——Java异常与JE分析实战
android·性能优化·debug
爱装代码的小瓶子7 小时前
【c++进阶】c++11的魔法:从模板到可变模板.
android·开发语言·c++
lxysbly8 小时前
安卓MD模拟器下载指南2026
android
冬奇Lab9 小时前
Android反模式警示录:System.exit(0)如何制造546ms黑屏
android·性能优化·debug
少年执笔9 小时前
android新版TTS无法进行语音播报
android·java
2501_946244789 小时前
Flutter & OpenHarmony OA系统底部导航栏组件开发指南
android·javascript·flutter
chen_mangoo9 小时前
Android10低电量无法打开相机
android·linux·驱动开发·嵌入式硬件
洞见不一样的自己9 小时前
Kotlin的inline、noinline、crossinline全面分析
android
idealzouhu9 小时前
【Android】深入浅出 JNI
android·开发语言·python·jni
2501_944446009 小时前
Flutter&OpenHarmony字体与排版设计
android·javascript·flutter