android网络图片的下载
1 /** 2 * Get image from newwork 3 * 4 * @param path 5 * The path of image 6 * @return byte[] 7 * @throws Exception 8 */ 9 public byte[] getImage(String path) throws Exception { 10 URL url = new URL(path); 11 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 12 conn.setConnectTimeout(5 * 1000); 13 conn.setRequestMethod("GET"); 14 InputStream inStream = conn.getInputStream(); 15 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { 16 return readStream(inStream); 17 } 18 return null; 19 } 20 21 /** 22 * Get data from stream 23 * 24 * @param inStream 25 * @return byte[] 26 * @throws Exception 27 */ 28 public static byte[] readStream(InputStream inStream) throws Exception { 29 ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 30 byte[] buffer = new byte[1024]; 31 int len = 0; 32 while ((len = inStream.read(buffer)) != -1) { 33 outStream.write(buffer, 0, len); 34 } 35 outStream.close(); 36 inStream.close(); 37 return outStream.toByteArray(); 38 } 39 40 /** 41 * 保存文件 42 * 43 * @param bm 44 * @param fileName 45 * @throws IOException 46 */ 47 public void saveFile(byte[] data, String fileName) throws IOException { 48 File dirFile = new File(Constant.PATH_PIC); 49 if (!dirFile.exists()) { 50 dirFile.mkdir(); 51 } 52 File myCaptureFile = new File(Constant.PATH_PIC + fileName); 53 BufferedOutputStream bos = new BufferedOutputStream( 54 new FileOutputStream(myCaptureFile)); 55 Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); 56 bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos); 57 bos.flush(); 58 bos.close(); 59 } 60 61 /** 62 * 加载本地图片 63 * 64 * @param url 65 * @return 66 */ 67 public static Bitmap getLoacalBitmap(String url) { 68 try { 69 FileInputStream fis = new FileInputStream(url); 70 return BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片 71 72 } catch (FileNotFoundException e) { 73 e.printStackTrace(); 74 return null; 75 } 76 }
原文:http://www.cnblogs.com/fanrenke/p/3894620.html