您的位置:首页 > 理论基础 > 计算机网络

android网络获取图片并保存在本地和获取手机SD卡中的图片显示到ImageView上及利用代码删除图片

2014-12-07 17:39 996 查看
获取网络上的图片有三步:

一、设置连接网络的权限和写入读取SD卡的权限。二、网络访问获得数据流。 三、在SD卡中创建文件夹将数据流转成图片格式存储。

注意:response.getEntity().getContent()方法,而此方法只能调用一次。否则会报错:java.lang.IllegalStateException: Content has been consumed。

manifest.xml

赋予权限,注意:在<application...>application>前添加

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


MainActivity.java

获得网络图片的数据流

HttpGet header = new HttpGet("你服务器的图片地址");
//自定义的Cookie(服务器返回)
//header.setHeader("Cookie", "key");
HttpResponse headerresponse = httpclient.execute(header); //
// headerresponse.getEntity().getContent(); 只能用一次否则会报错Content has been consumed
InputStream headerin =
headerresponse.getEntity().getContent();// 服务器返回的数据
bitmap = BitmapFactory.decodeStream(headerin);
if (bitmap != null) {
saveBitmap(bitmap);// display image
}
headerin.close();


保存的位置:

/**
* 保存方法
*
* @throws IOException
*/
public void saveBitmap(Bitmap bitmap) throws IOException {
//更改的名字
String imageName="w"+".jpg";

String headPath=android.os.Environment.getExternalStorageDirectory()+
"/"+"msg"+"/"+"head";

File headDir=new File(headPath);
if(!headDir.exists()){
headDir.mkdirs();
}
System.out.println(headPath+"\n"+headDir);
FileOutputStream headFos=null;
File headFile=null;
try{
//重命名并保存
headFile=new File(headPath,imageName);
headFile.createNewFile();

headFos=new FileOutputStream(headFile);
bitmap.compress(CompressFormat.JPEG, 100, headFos);
headFos.flush();

}catch(Exception e){
e.printStackTrace();
}finally{
if(headFos!=null){
try {
headFos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}


扩展:把手机SD卡中的图片显示到ImageView上。

String headPath = android.os.Environment.getExternalStorageDirectory()
+ "/" + "msg" + "/" + "head/";
Bitmap bmpDefaultPic;

ImageView imgv_img = (ImageView) findViewById(R.id.imageView1);
bmpDefaultPic = BitmapFactory.decodeFile(
headPath +"图片名" + ".jpg", null);
imgv_img.setImageBitmap(bmpDefaultPic);


利用代码删除本地图片:

File file =new File(headPath+"/"+"图片名"+".JPG");
file.delete();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: