私类:
// 异步更新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); }