头几天遇到一个问题:在安卓开发应用中保存图片到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();
}
}
} catch (FileNotFoundException e) {
photoFile.delete();
e.printStackTrace();
} catch (IOException e) {
photoFile.delete();
e.printStackTrace();
} finally{
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
下面是保存图片byte流的代码,这样sd卡就会有一个名为image1的文件。
public static byte[] bitmapToBytes(Bitmap bm) {
byte[] bytes = null;
if (bm != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
bytes = baos.toByteArray();
}
return bytes;
}
public static void savePhotoToSDCardByte(Bitmap photoBitmap,String path,String photoName){
if (checkSDCardAvailable()) {
File dir = new File(path);
if (!dir.exists()){
dir.mkdirs();
}
if(photoBitmap !=null)
{
byte[] byteArray = bitmapToBytes(photoBitmap);
File photoFile = new File(path , photoName);
FileOutputStream fileOutputStream = null;
BufferedOutputStream bStream = null;
try {
fileOutputStream = new FileOutputStream(photoFile);
bStream = new BufferedOutputStream(fileOutputStream);
bStream.write(byteArray);
} catch (FileNotFoundException e) {
photoFile.delete();
e.printStackTrace();
} catch (IOException e) {
photoFile.delete();
e.printStackTrace();
} finally{
try {
bStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}//(photoBitmap !=null)
}
}