android网络图片的下载
16lz
2021-01-23
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 }
更多相关文章
- android 开启本地相册选择图片并返回显示
- Android中WebView如何加载JavaScript脚本
- Android 异步任务加载图片代码
- android 开发上传图片遇到返回 FileNotFoundException
- Android ListView(Selector 背景图片 全选 Checkbox等按钮)
- android 加载模式
- Android中的Picasso实现圆角图片
- Android 设置图片的四个角 为圆角
- Android lint 删除无用图片文件和配置文件