異步加載圖片以及Bitmap相關處理方法
私類:
// 異步更新Image private class GetImageTask extends AsyncTask<String, Void, Bitmap> { // 覆寫的方法,這個方法將在這個類的對象execute()的時候調用 protected Bitmap doInBackground(String... urls) { Bitmap bmp = null; Bitmap newBitmap = null; int bmWidth, bmHeight; try { bmp = FileUtil.getBitmapByPath(urls[0]);//本地圖片獲得Bitmap bmWidth = bmp.getWidth(); bmHeight = bmp.getHeight(); // 圖片過大就剪裁以下 if ((bmWidth > 240) || (bmHeight > 240)) { newBitmap = fileUtil.imageCropSquare(bmp);//從bitmap剪裁為正方形Bitmap } else { newBitmap = bmp; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return newBitmap; } @Override // 覆寫的方法,當耗時的操作執行完之后執行,這里就是把獲得的Bitmap更新到ImageView上 protected void onPostExecute(Bitmap result) { // TODO Auto-generated method stub super.onPostExecute(result); imgPostPic.setImageBitmap(result); }
getBitmapByPath本地圖片路徑獲得BitMap方法:
/** * 從本地路徑獲取、生成與原圖同樣大小的Bitmap,不作壓縮 * * @param path * @return */ public static Bitmap getBitmapByPath(String path) { if (path == null){ return null; } Bitmap bmTemp = null; if (bmTemp == null) { try { bmTemp = BitmapFactory.decodeFile(path); } catch (Exception e) { e.printStackTrace(); } catch (Error e) { e.printStackTrace(); } } return bmTemp; }
網絡圖片路徑獲得Bitmap的方法
/** * Android獲取網絡圖片轉換成Bitmap * * @return Bitmap */ private static final int IO_BUFFER_SIZE = 4 * 1024;// 設置緩沖區大小 public static Bitmap GetBitmapFromWeb(String url) { Bitmap bitmap = null; InputStream in = null; BufferedOutputStream out = null; try { System.out.println("GetLocalOrWebBitmap HEAD, url:" + url); in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE); final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE); copy(in, out); out.flush(); byte[] data = dataStream.toByteArray(); bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); data = null; System.out.println("GetLocalOrWebBitmap END"); return bitmap; } catch (IOException e) { e.printStackTrace(); return null; } } // 附加的copy函數 private static void copy(InputStream in, OutputStream out) throws IOException { byte[] b = new byte[IO_BUFFER_SIZE]; int read; while ((read = in.read(b)) != -1) { out.write(b, 0, read); } }
正方形Bitmap剪裁:
/** * 按正方形裁切圖片 */ public Bitmap imageCropSquare(Bitmap bitmap) { int w = bitmap.getWidth(); // 得到圖片的寬,高 int h = bitmap.getHeight(); int wh = w > h ? h : w;// 裁切后所取的正方形區域邊長 int retX = w > h ? (w - h) / 2 : 0;//基于原圖,取正方形左上角x坐標 int retY = w > h ? 0 : (h - w) / 2; //下面這句是關鍵 return Bitmap.createBitmap(bitmap, retX, retY, wh, wh, null, false); }
原創作者:http://www.rzrgm.cn/huangsheng/

浙公網安備 33010602011771號