首页 > 代码库 > android网络图片的下载
android网络图片的下载
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 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。