標籤:android des style blog http color os io
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 stream23 * 24 * @param inStream25 * @return byte[]26 * @throws Exception27 */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 bm44 * @param fileName45 * @throws IOException46 */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 url65 * @return66 */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 }