• android 下载保存图片


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

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

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

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

    1. publicclassAndroidTest2_3_3 extends Activity {   
    2. privatefinalstatic String TAG = "AndroidTest2_3_3";   
    3. privatefinalstatic String ALBUM_PATH    
    4.             = Environment.getExternalStorageDirectory() + "/download_test/";   
    5. private ImageView imageView;   
    6. private Button btnSave;   
    7. private ProgressDialog myDialog = null;   
    8. private Bitmap bitmap;   
    9. private String fileName;   
    10. private String message;   
    11. @Override
    12. protectedvoid onCreate(Bundle savedInstanceState) {   
    13. super.onCreate(savedInstanceState);   
    14.         setContentView(R.layout.main);   
    15.         imageView = (ImageView)findViewById(R.id.imgSource);   
    16.         btnSave = (Button)findViewById(R.id.btnSave);   
    17.         String filePath = "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);// display image       
    25.             }else{         
    26.                 Toast.makeText(AndroidTest2_3_3.this"Image error!"1).show();         
    27.             }   
    28. //////////////////////////////////////////////////////// 
    29. //******** 取得的是InputStream,直接从InputStream生成bitmap ***********/ 
    30.             bitmap = BitmapFactory.decodeStream(getImageStream(filePath));   
    31. if (bitmap != null) {   
    32.                 imageView.setImageBitmap(bitmap);// display image 
    33.             }   
    34. //********************************************************************/ 
    35.             Log.d(TAG, "set image ...");   
    36.         } catch (Exception e) {      
    37.             Toast.makeText(AndroidTest2_3_3.this,"Newwork error!"1).show();      
    38.             e.printStackTrace();      
    39.         }      
    40. // 下载图片 
    41.         btnSave.setOnClickListener(new Button.OnClickListener(){   
    42. publicvoid onClick(View v) {   
    43.                 myDialog = ProgressDialog.show(AndroidTest2_3_3.this"保存图片""图片正在保存中,请稍等..."true);   
    44. new Thread(saveFileRunnable).start();   
    45.         }   
    46.         });   
    47.     }   
    48. /**   
    49.      * Get image from newwork   
    50.      * @param path The path of image   
    51.      * @return byte[] 
    52.      * @throws Exception   
    53.      */
    54. publicbyte[] getImage(String path) throws Exception{      
    55.         URL url = new URL(path);      
    56.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();      
    57.         conn.setConnectTimeout(5 * 1000);      
    58.         conn.setRequestMethod("GET");      
    59.         InputStream inStream = conn.getInputStream();      
    60. if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){      
    61. return readStream(inStream);      
    62.         }      
    63. returnnull;      
    64.     }      
    65. /**   
    66.      * Get image from newwork   
    67.      * @param path The path of image   
    68.      * @return InputStream 
    69.      * @throws Exception   
    70.      */
    71. public InputStream getImageStream(String path) throws Exception{      
    72.         URL url = new URL(path);      
    73.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();      
    74.         conn.setConnectTimeout(5 * 1000);      
    75.         conn.setRequestMethod("GET");   
    76. if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){      
    77. return conn.getInputStream();         
    78.         }      
    79. returnnull;    
    80.     }   
    81. /**   
    82.      * Get data from stream  
    83.      * @param inStream   
    84.      * @return byte[] 
    85.      * @throws Exception   
    86.      */
    87. publicstaticbyte[] readStream(InputStream inStream) throws Exception{      
    88.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();      
    89. byte[] buffer = newbyte[1024];      
    90. int len = 0;      
    91. while( (len=inStream.read(buffer)) != -1){      
    92.             outStream.write(buffer, 0, len);      
    93.         }      
    94.         outStream.close();      
    95.         inStream.close();      
    96. return outStream.toByteArray();      
    97.     }    
    98. /** 
    99.      * 保存文件 
    100.      * @param bm 
    101.      * @param fileName 
    102.      * @throws IOException 
    103.      */
    104. publicvoid saveFile(Bitmap bm, String fileName) throws IOException {   
    105.         File dirFile = new File(ALBUM_PATH);   
    106. if(!dirFile.exists()){   
    107.             dirFile.mkdir();   
    108.         }   
    109.         File myCaptureFile = new File(ALBUM_PATH + fileName);   
    110.         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));   
    111.         bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);   
    112.         bos.flush();   
    113.         bos.close();   
    114.     }   
    115. private Runnable saveFileRunnable = new Runnable(){   
    116. @Override
    117. publicvoid run() {   
    118. try {   
    119.                 saveFile(bitmap, fileName);   
    120.                 message = "图片保存成功!";   
    121.             } catch (IOException e) {   
    122.                 message = "图片保存失败!";   
    123.                 e.printStackTrace();   
    124.             }   
    125.             messageHandler.sendMessage(messageHandler.obtainMessage());   
    126.         }   
    127.     };   
    128. private Handler messageHandler = new Handler() {   
    129. @Override
    130. publicvoid handleMessage(Message msg) {   
    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. <?xml version="1.0" encoding="utf-8"?>  
    2. <LinearLayout xmlns: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-permission Android:name="android.permission.INTERNET" />    
    2. <uses-permission Android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
    3.    <uses-permission Android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  

    预览图:

  • 相关阅读:
    封装和参数调用(格式修改)
    今天休息
    2018.1.9内部类
    2018.1.8转型
    环境变量
    环境变量
    计算机的高级语言
    常用的设计模式
    常用的设计模式
    【python3】中 elif 的使用
  • 原文地址:https://www.cnblogs.com/sode/p/2293387.html
Copyright © 2020-2023  润新知