獲取網上圖片壓縮顯示

從網上獲取圖片並顯示比較容易,只需要通過http獲取輸入流,然後解碼輸入流即可,但是有些圖片還是比較大,在解碼顯示之前需要壓縮,

壓縮方式都一樣,計算設置採樣率大小即可;

但是在獲取圖片寬高的時候會先讀取一次圖片數據,採用流的話這次已經把數據讀走了,所以在後面再真正解碼圖片的時候始終是null;

解決辦法就是將輸入流轉爲字節數組保存下來,對這個數組進行操作,問題得到解決,模塊代碼如下:

public static Bitmap decodeNetWork(String fileUrl, int width, int height)
	{
		if(fileUrl == null || !fileUrl.startsWith(Constant.HTTP_TAG))
			return null;
		
		URL url = null;
		try
		{
			url = new URL(fileUrl);
		} catch (MalformedURLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		HttpURLConnection conn = null;
		InputStream inputStream = null;
		Bitmap bm1 = null;
		try
		{
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true); 
			conn.connect(); 
			inputStream = conn.getInputStream(); 
			
			final BitmapFactory.Options options = new BitmapFactory.Options();
			/*只加載基礎信息,並不真正解碼圖片*/
			options.inJustDecodeBounds = true;
			
			byte[] data = MyFileUtils.getBytes(inputStream);
			bm1 = BitmapFactory.decodeByteArray(data, 0, data.length, options);
			if (options.outWidth < 1 || options.outHeight < 1) 
			{
				return null;
			}
			int[] size = calculateSize(options.outWidth, options.outHeight, width, height);
			/*計算縮放率*/
			options.inSampleSize = getSampleSize(options, size[0], size[1]);
			options.inPreferredConfig = Bitmap.Config.RGB_565;
			options.inPurgeable = true;
			options.inInputShareable = true;
			options.inJustDecodeBounds = false;
			
			bm1 = BitmapFactory.decodeByteArray(data, 0, data.length, options);
			conn.disconnect();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (OutOfMemoryError e) 
		{
		}
		
		try
		{
			if(inputStream != null)
				inputStream.close();
		} 
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bm1;
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章