標籤:
在android開發過程中經常會處理網狀圖片發送記憶體溢出,那麼怎麼解決這種問題?
思路:
下載到本地
通過網路擷取和檔案下載存放到手機中目錄
代碼:
// 擷取網路public InputStream GetHttpInfo(String urString, String fun, String parm)throws Exception {HttpURLConnection connection = (HttpURLConnection) new URL(urString).openConnection();connection.setRequestMethod(fun);connection.setConnectTimeout(11000);connection.setDoInput(true);connection.setDoOutput(true);connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");connection.setRequestProperty("Connection", "keep-alive");connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36");connection.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");OutputStream outputStream = connection.getOutputStream();outputStream.write(parm.getBytes());if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {return connection.getInputStream();}return null;}// 檔案下載public void DownLoadFiles(String filePath, String filename,InputStream inputStream) throws Exception {File file = new File(filePath);if (!file.exists()) {file.mkdirs();}FileOutputStream fileOutputStream = new FileOutputStream(new File(file,filename));byte[] arrs = new byte[1024];int len = 0;while ((len = inputStream.read(arrs)) != -1) {fileOutputStream.write(arrs, 0, len);}fileOutputStream.close();}
然後從本地檔案讀取到bitmap對象中
注意:需要在讀取去修改圖片品質可以通過下面兩個函數擷取修改高寬後品質bitmap對象:
public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth) {// 源圖片的寬度final int width = options.outWidth;int inSampleSize = 1;if (width > reqWidth) {// 計算出實際寬度和目標寬度的比率final int widthRatio = Math.round((float) width / (float) reqWidth);inSampleSize = widthRatio;}return inSampleSize;}public static Bitmap decodeSampledBitmapFromResource(String pathName,int reqWidth) {// 第一次解析將inJustDecodeBounds設定為true,來擷取圖片大小final BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true;BitmapFactory.decodeFile(pathName, options);// 調用上面定義的方法計算inSampleSize值options.inSampleSize = calculateInSampleSize(options, reqWidth);// 使用擷取到的inSampleSize值再次解析圖片options.inJustDecodeBounds = false;return BitmapFactory.decodeFile(pathName, options);}
此時bitmap品質已經發生改變了!
原文地址:http://sijienet.com/bbs/?leibie=showinfo&id=51
android 防止bitmap 記憶體溢出