首页 > 代码库 > android网络获取图片并保存在本地
android网络获取图片并保存在本地
获取网络上的图片有三步:
一、设置连接网络的权限和写入读取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(); } } } }
android网络获取图片并保存在本地
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。