1.我们需要获取我们的软件的根目录。我们可以使用Context.getFilesDir()来获取到软件的根目录,并且我需要保存到我们的images文件下方。
/**
* Bitmap 帮助类之一
*/
class BitmapUtils {
/**
* Save Bitmap
*
* @param name file name
* @param bm picture to save
*/
static void saveBitmap(String name, Bitmap bm, Context mContext) {
Log.d("Save Bitmap", "Ready to save picture");
//指定我们想要存储文件的地址
String TargetPath = mContext.getFilesDir() + "/images/";
Log.d("Save Bitmap", "Save Path=" + TargetPath);
//判断指定文件夹的路径是否存在
if (!FileUtils.fileIsExist(TargetPath)) {
Log.d("Save Bitmap", "TargetPath isn't exist");
} else {
//如果指定文件夹创建成功,那么我们则需要进行图片存储操作
File saveFile = new File(TargetPath, name);
try {
FileOutputStream saveImgOut = new FileOutputStream(saveFile);
// compress - 压缩的意思
bm.compress(Bitmap.CompressFormat.JPEG, 80, saveImgOut);
//存储完成后需要清除相关的进程
saveImgOut.flush();
saveImgOut.close();
Log.d("Save Bitmap", "The picture is save to your phone!");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
2.我们在这个方法中传入指定的存储路径,然后判断是否存在,如果存在我们需要创建我们的指定目录,然后返回我们的创建结果。这样我们的对目录的操作就基本完成了。
/**
* 判断指定目录的文件夹是否存在,如果不存在则需要创建新的文件夹
* @param fileName 指定目录
* @return 返回创建结果 TRUE or FALSE
*/
static boolean fileIsExist(String fileName)
{
//传入指定的路径,然后判断路径是否存在
File file=new File(fileName);
if (file.exists())
return true;
else{
//file.mkdirs() 创建文件夹的意思
return file.mkdirs();
}
}
网友评论