Android实现下载图片并保存到SD卡中


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

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

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

  1. public class AndroidTest2_3_3 extends Activity {   
  2.     private final static String TAG = "AndroidTest2_3_3";   
  3.     private final static 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.        
  12.        
  13.     @Override  
  14.     protected void onCreate(Bundle savedInstanceState) {   
  15.         super.onCreate(savedInstanceState);   
  16.         setContentView(R.layout.main);   
  17.            
  18.         imageView = (ImageView)findViewById(R.id.imgSource);   
  19.         btnSave = (Button)findViewById(R.id.btnSave);   
  20.            
  21.         String filePath = "http://hi.csdn.net/attachment/201105/21/134671_13059532779c5u.jpg";   
  22.         fileName = "test.jpg";   
  23.            
  24.         try {   
  25.             //////////////// 取得的是byte数组, 从byte数组生成bitmap   
  26.             byte[] data = getImage(filePath);         
  27.             if(data!=null){         
  28.                 bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap         
  29.                 imageView.setImageBitmap(bitmap);// display image         
  30.             }else{         
  31.                 Toast.makeText(AndroidTest2_3_3.this"Image error!"1).show();         
  32.             }   
  33.             ////////////////////////////////////////////////////////   
  34.   
  35.             //******** 取得的是InputStream,直接从InputStream生成bitmap ***********/   
  36.             bitmap = BitmapFactory.decodeStream(getImageStream(filePath));   
  37.             if (bitmap != null) {   
  38.                 imageView.setImageBitmap(bitmap);// display image   
  39.             }   
  40.             //********************************************************************/   
  41.             Log.d(TAG, "set image ...");   
  42.         } catch (Exception e) {      
  43.             Toast.makeText(AndroidTest2_3_3.this,"Newwork error!"1).show();      
  44.             e.printStackTrace();      
  45.         }      
  46.   
  47.            
  48.         // 下载图片   
  49.         btnSave.setOnClickListener(new Button.OnClickListener(){   
  50.             public void onClick(View v) {   
  51.                 myDialog = ProgressDialog.show(AndroidTest2_3_3.this"保存图片""图片正在保存中,请稍等..."true);   
  52.                 new Thread(saveFileRunnable).start();   
  53.         }   
  54.         });   
  55.     }   
  56.   
  57.     /**    
  58.      * Get image from newwork    
  59.      * @param path The path of image    
  60.      * @return byte[]  
  61.      * @throws Exception    
  62.      */     
  63.     public byte[] getImage(String path) throws Exception{      
  64.         URL url = new URL(path);      
  65.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();      
  66.         conn.setConnectTimeout(5 * 1000);      
  67.         conn.setRequestMethod("GET");      
  68.         InputStream inStream = conn.getInputStream();      
  69.         if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){      
  70.             return readStream(inStream);      
  71.         }      
  72.         return null;      
  73.     }      
  74.      
  75.     /**    
  76.      * Get image from newwork    
  77.      * @param path The path of image    
  78.      * @return InputStream  
  79.      * @throws Exception    
  80.      */  
  81.     public InputStream getImageStream(String path) throws Exception{      
  82.         URL url = new URL(path);      
  83.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();      
  84.         conn.setConnectTimeout(5 * 1000);      
  85.         conn.setRequestMethod("GET");   
  86.         if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){      
  87.             return conn.getInputStream();         
  88.         }      
  89.         return null;    
  90.     }   
  91.     /**    
  92.      * Get data from stream   
  93.      * @param inStream    
  94.      * @return byte[]  
  95.      * @throws Exception    
  96.      */     
  97.     public static byte[] readStream(InputStream inStream) throws Exception{      
  98.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();      
  99.         byte[] buffer = new byte[1024];      
  100.         int len = 0;      
  101.         while( (len=inStream.read(buffer)) != -1){      
  102.             outStream.write(buffer, 0, len);      
  103.         }      
  104.         outStream.close();      
  105.         inStream.close();      
  106.         return outStream.toByteArray();      
  107.     }    
  108.   
  109.     /**  
  110.      * 保存文件  
  111.      * @param bm  
  112.      * @param fileName  
  113.      * @throws IOException  
  114.      */  
  115.     public void saveFile(Bitmap bm, String fileName) throws IOException {   
  116.         File dirFile = new File(ALBUM_PATH);   
  117.         if(!dirFile.exists()){   
  118.             dirFile.mkdir();   
  119.         }   
  120.         File myCaptureFile = new File(ALBUM_PATH + fileName);   
  121.         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));   
  122.         bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);   
  123.         bos.flush();   
  124.         bos.close();   
  125.     }   
  126.        
  127.     private Runnable saveFileRunnable = new Runnable(){   
  128.         @Override  
  129.         public void run() {   
  130.             try {   
  131.                 saveFile(bitmap, fileName);   
  132.                 message = "图片保存成功!";   
  133.             } catch (IOException e) {   
  134.                 message = "图片保存失败!";   
  135.                 e.printStackTrace();   
  136.             }   
  137.             messageHandler.sendMessage(messageHandler.obtainMessage());   
  138.         }   
  139.                
  140.     };   
  141.        
  142.     private Handler messageHandler = new Handler() {   
  143.         @Override  
  144.         public void handleMessage(Message msg) {   
  145.             myDialog.dismiss();   
  146.             Log.d(TAG, message);   
  147.             Toast.makeText(AndroidTest2_3_3.this, message, Toast.LENGTH_SHORT).show();   
  148.         }   
  149.     };   
  150. }  

下载进度条的可以参考我的另外一个帖子:Android更新下载进度条

  • 1
  • 2
  • 下一页

相关内容