在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格式保存在内部存储中,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!
新闻热点
疑难解答