头几天遇到一个问题:在安卓开发应用中保存图片到SD卡,并且 用户在图库中搜到,类似于缓存的那种形式。最开始的第一想法是改一下后缀名,例如把一个图片保存为image1.txt,这样保存当然没问题,但在应用中读取中就不行了,后来也没研究为什么不能正常读取,毕竟这种办法太土鳖了。。。
今天有空上网搜了一下,发现使用byte流保存到SD卡就可以满足我的需求。下面我把正常保存图片文件的代码和保存图片byte流的代码都贴出来,方便大家共同学习参考。
假设我的图片的名字为 image1。
正常保存图片文件的代码(例如image1.png):
public static void savePhotoToSDCard(Bitmap photoBitmap,String path,String photoName){
if (checkSDCardAvailable()) {
File dir = new File(path);
if (!dir.exists()){
dir.mkdirs();
}
File photoFile = new File(path , photoName + ".png");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(photoFile);
if (photoBitmap != null) {
if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {
fileOutputStream.flush();
// fileOutputStream.close();