作者:逍遥子 | 来源:互联网 | 2023-05-19 15:14
创建一个文件夹:1newFile(Environment.getExternalStorageDirectory().getPath()+File.separator+
创建一个文件夹 :
1 new File(Environment.getExternalStorageDirectory().getPath() + File.separator +
getPackageName() + "/naizi").mkdirs();//这里要加上“/” 如果不加上mkdirs() 不会创建出一个文件 而只是一个路径
2 new File(Environment.getExternalStorageDirectory().getPath() + File.separator +
getPackageName(),"naizi").mkdirs();
别忘了在mainfest加上读写权限 :
将网络图片的Url转化成Bitmap保存到本地:
将Url转换成bitmap
private Bitmap loadImage() {
URL url = null;
try {
url = new URL("http://d6.yihaodianimg.com/N03/M04/16/3D/CgQCs1N5MUiATsxVAADJLWXi5mk84700.jpg");
} catch (MalformedURLException e) {
e.printStackTrace();
}
InputStream inputStream = null;
HttpURLConnection cOnn= null;//打开链接
try {
cOnn= (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);//设置网络超时时间
conn.setDoInput(true);//打开输入流
int requestCode = conn.getResponseCode();
if (requestCode == HttpURLConnection.HTTP_OK) {
inputStream = conn.getInputStream();//获取输入流
}
} catch (IOException e) {
e.printStackTrace();
}
return BitmapFactory.decodeStream(inputStream);
在将拿到的bitmap保存到本地
http://zhidao.baidu.com/link?url=r_jdmN9tqv1rcZeYS7joa_gLcQ4mbqTPi69IKZO_z25jwfWMb0Y8BSgyVzbFrV758ViIaoqcZ4nWj6_1-QVkZzchbB8S1tWgBka7bvkcuia
这个链接可以很好的理解 BufferedOutputStream 和FileOutputStream
path =Environment.getExternalStorageDirectory().getPath() + File.separator +
getPackageName() + "/naizi"
private void saveBitmapToFile(Bitmap bitmap, String path) {
BufferedOutputStream bos = null;
File file = new File(path,UUID.random()+".jpg");
if (file != null) {
try {
bos = new BufferedOutputStream(new FileOutputStream(file));//这里file好像是指路径 "MABI"
bitmap.compress(Bitmap.CompressFormat.PNG, 90, bos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.flush();
bos.close();
bos = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
从本地读取图片
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
}
记住bitmap的回收 以防内存泄漏
bitmap.recylcer();
}