在android開發過程當中常常會處理網絡圖片發送內存溢出,那麼怎麼解決這種問題?html
思路:java
下載到本地android
經過網絡獲取和文件下載存放到手機中目錄web
代碼:網絡
// 獲取網絡 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對象中app
注意:須要在讀取去修改圖片質量能夠經過下面兩個函數獲取修改高寬後質量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質量已經發生改變了!code
原文地址:http://sijienet.com/bbs/?leibie=showinfo&id=51xml