引用:http://www.linuxidc.com/Linux/2011-06/37233.htm

1.java代码,下载图片的主程序

先实现显示图片,然后点击下载图片按钮,执行下载功能。

从网络上取得的图片,生成Bitmap时有两种方法,一种是先转换为byte[],再生成bitmap;一种是直接用InputStream生成bitmap。

  1. publicclassAndroidTest2_3_3extendsActivity{
  2. privatefinalstaticStringTAG="AndroidTest2_3_3";
  3. privatefinalstaticStringALBUM_PATH
  4. =Environment.getExternalStorageDirectory()+"/download_test/";
  5. privateImageViewimageView;
  6. privateButtonbtnSave;
  7. privateProgressDialogmyDialog=null;
  8. privateBitmapbitmap;
  9. privateStringfileName;
  10. privateStringmessage;
  11. @Override
  12. protectedvoidonCreate(BundlesavedInstanceState){
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.main);
  15. imageView=(ImageView)findViewById(R.id.imgSource);
  16. btnSave=(Button)findViewById(R.id.btnSave);
  17. StringfilePath="http://hi.csdn.net/attachment/201105/21/134671_13059532779c5u.jpg";
  18. fileName="test.jpg";
  19. try{
  20. ////////////////取得的是byte数组,从byte数组生成bitmap
  21. byte[]data=getImage(filePath);
  22. if(data!=null){
  23. bitmap=BitmapFactory.decodeByteArray(data,0,data.length);//bitmap
  24. imageView.setImageBitmap(bitmap);//displayimage
  25. }else{
  26. Toast.makeText(AndroidTest2_3_3.this,"Imageerror!",1).show();
  27. }
  28. ////////////////////////////////////////////////////////
  29. //********取得的是InputStream,直接从InputStream生成bitmap***********/
  30. bitmap=BitmapFactory.decodeStream(getImageStream(filePath));
  31. if(bitmap!=null){
  32. imageView.setImageBitmap(bitmap);//displayimage
  33. }
  34. //********************************************************************/
  35. Log.d(TAG,"setimage...");
  36. }catch(Exceptione){
  37. Toast.makeText(AndroidTest2_3_3.this,"Newworkerror!",1).show();
  38. e.printStackTrace();
  39. }
  40. //下载图片
  41. btnSave.setOnClickListener(newButton.OnClickListener(){
  42. publicvoidonClick(Viewv){
  43. myDialog=ProgressDialog.show(AndroidTest2_3_3.this,"保存图片","图片正在保存中,请稍等...",true);
  44. newThread(saveFileRunnable).start();
  45. }
  46. });
  47. }
  48. /**
  49. *Getimagefromnewwork
  50. *@parampathThepathofimage
  51. *@returnbyte[]
  52. *@throwsException
  53. */
  54. publicbyte[]getImage(Stringpath)throwsException{
  55. URLurl=newURL(path);
  56. HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
  57. conn.setConnectTimeout(5*1000);
  58. conn.setRequestMethod("GET");
  59. InputStreaminStream=conn.getInputStream();
  60. if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
  61. returnreadStream(inStream);
  62. }
  63. returnnull;
  64. }
  65. /**
  66. *Getimagefromnewwork
  67. *@parampathThepathofimage
  68. *@returnInputStream
  69. *@throwsException
  70. */
  71. publicInputStreamgetImageStream(Stringpath)throwsException{
  72. URLurl=newURL(path);
  73. HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
  74. conn.setConnectTimeout(5*1000);
  75. conn.setRequestMethod("GET");
  76. if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
  77. returnconn.getInputStream();
  78. }
  79. returnnull;
  80. }
  81. /**
  82. *Getdatafromstream
  83. *@paraminStream
  84. *@returnbyte[]
  85. *@throwsException
  86. */
  87. publicstaticbyte[]readStream(InputStreaminStream)throwsException{
  88. ByteArrayOutputStreamoutStream=newByteArrayOutputStream();
  89. byte[]buffer=newbyte[1024];
  90. intlen=0;
  91. while((len=inStream.read(buffer))!=-1){
  92. outStream.write(buffer,0,len);
  93. }
  94. outStream.close();
  95. inStream.close();
  96. returnoutStream.toByteArray();
  97. }
  98. /**
  99. *保存文件
  100. *@parambm
  101. *@paramfileName
  102. *@throwsIOException
  103. */
  104. publicvoidsaveFile(Bitmapbm,StringfileName)throwsIOException{
  105. FiledirFile=newFile(ALBUM_PATH);
  106. if(!dirFile.exists()){
  107. dirFile.mkdir();
  108. }
  109. FilemyCaptureFile=newFile(ALBUM_PATH+fileName);
  110. BufferedOutputStreambos=newBufferedOutputStream(newFileOutputStream(myCaptureFile));
  111. bm.compress(Bitmap.CompressFormat.JPEG,80,bos);
  112. bos.flush();
  113. bos.close();
  114. }
  115. privateRunnablesaveFileRunnable=newRunnable(){
  116. @Override
  117. publicvoidrun(){
  118. try{
  119. saveFile(bitmap,fileName);
  120. message="图片保存成功!";
  121. }catch(IOExceptione){
  122. message="图片保存失败!";
  123. e.printStackTrace();
  124. }
  125. messageHandler.sendMessage(messageHandler.obtainMessage());
  126. }
  127. };
  128. privateHandlermessageHandler=newHandler(){
  129. @Override
  130. publicvoidhandleMessage(Messagemsg){
  131. myDialog.dismiss();
  132. Log.d(TAG,message);
  133. Toast.makeText(AndroidTest2_3_3.this,message,Toast.LENGTH_SHORT).show();
  134. }
  135. };
  136. }

2.main.xml文件,只有一个button和一个ImageView

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:Android="http://schemas.android.com/apk/res/android"
  3. Android:orientation="vertical"
  4. Android:layout_width="fill_parent"
  5. Android:layout_height="fill_parent"
  6. >
  7. <Button
  8. Android:id="@+id/btnSave"
  9. Android:layout_width="wrap_content"
  10. Android:layout_height="wrap_content"
  11. Android:text="保存图片"
  12. />
  13. <ImageView
  14. Android:id="@+id/imgSource"
  15. Android:layout_width="wrap_content"
  16. Android:layout_height="wrap_content"
  17. Android:adjustViewBounds="true"
  18. />
  19. </LinearLayout>

3.在mainfest文件中增加互联网权限和写sd卡的权限

  1. <uses-permissionAndroid:name="android.permission.INTERNET"/>
  2. <uses-permissionAndroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  3. <uses-permissionAndroid:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

预览图:

更多相关文章

  1. Android之SharedPreference轻量级数据存储
  2. imageview 自适应各种屏幕尺寸
  3. Android中加载PNG图片时出现错误----No resource found
  4. Android中Math常用的方法,包括pow、abs、round、floor、rint、ran
  5. Android加载png图片时出错
  6. 继承Application实现Android数据共享
  7. 常用方法(2)------根据图片的url路径获得Bitmap对象
  8. android 2.2 视频和图片的缩略图处理
  9. Android(安卓)ImageView ScaleTypes介绍

随机推荐

  1. Android应用开发——系统自带样式Android
  2. Android(安卓)SDK Android(安卓)NDK 官方
  3. TextView 的点击事件
  4. 系统自带样式Android:theme
  5. Android(安卓)设置文字水平滚动
  6. 安卓动态时间获取
  7. 系统自带样式Android:theme
  8. Android(安卓)TextView 超出长度显示省略
  9. android中自带的主题(theme)
  10. android中自带的样式