当前位置: 移动技术网 > IT编程>移动开发>Android > Android中将Bitmap对象以PNG格式保存在内部存储中的方法

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

2019年07月24日  | 移动技术网IT编程  | 我要评论

win8系统怎么用,永州采购,极限挑战停播原因

在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格式保存在内部存储中,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网