温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android中将Bitmap对象以PNG格式保存在内部存储中的方法

发布时间:2020-08-28 05:14:38 来源:脚本之家 阅读:658 作者:Tail。 栏目:移动开发

在Android中进行图像处理的任务时,有时我们希望将处理后的结果以图像文件的格式保存在内部存储空间中,本文以此为目的,介绍将Bitmap对象的数据以PNG格式保存下来的方法。

1、添加权限

由于是对SD card进行操作,必不可少的就是为你的程序添加读写权限,需要添加的内容如下:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>

对这两个权限进行简要解释如下:

"android.permission.MOUNT_UNMOUNT_FILESYSTEMS"-->允许挂载和反挂载文件系统可移动存储
"android.permission.WRITE_EXTERNAL_STORAGE"-->模拟器中sdcard中创建文件夹的权限

2、保存图片的相关代码

代码比较简单,在这里存储位置是写的绝对路径,大家可以通过使用Environment获取不同位置路径。

Tips:在使用该函数的时候,记得把文件的扩展名带上。

private void saveBitmap(Bitmap bitmap,String bitName) throws IOException
  {
    File file = new File("/sdcard/DCIM/Camera/"+bitName);
    if(file.exists()){
      file.delete();
    }
    FileOutputStream out;
    try{
      out = new FileOutputStream(file);
      if(bitmap.compress(Bitmap.CompressFormat.PNG, 90, out))
      {
        out.flush();
        out.close();
      }
    }
    catch (FileNotFoundException e)
    {
      e.printStackTrace();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }

PS:下面看下android中Bitmap对象怎么保存为文件

Bitmap类有一compress成员,可以把bitmap保存到一个stream中。

例如:

public void saveMyBitmap(String bitName) throws IOException { 
  File f = new File("/sdcard/Note/" + bitName + ".png"); 
  f.createNewFile(); 
  FileOutputStream fOut = null; 
  try { 
      fOut = new FileOutputStream(f); 
  } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
  } 
  mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut); 
  try { 
      fOut.flush(); 
  } catch (IOException e) { 
      e.printStackTrace(); 
  } 
  try { 
      fOut.close(); 
  } catch (IOException e) { 
      e.printStackTrace(); 
  } 
} 

总结

以上所述是小编给大家介绍的Android中将Bitmap对象以PNG格式保存在内部存储中,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI