获取Bitmap
1.将文件转化成Bitmap
|
public static final float DISPLAY_WIDTH = 200;
public static final float DISPLAY_HEIGHT = 200;
/**
* 从path中获取图片信息
* @param path
* @return
*/
private Bitmap decodeBitmap(String path){
BitmapFactory.Options op = new BitmapFactory.Options();
op.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(path, op);
int wRatio = (int)Math.ceil(op.outWidth/DISPLAY_WIDTH);
int hRatio = (int)Math.ceil(op.outHeight/DISPLAY_HEIGHT);
if(wRatio > 1 && hRatio > 1){
if(wRatio > hRatio){
op.inSampleSize = wRatio;
}else{
op.inSampleSize = hRatio;
}
}
op.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(path, op);
return bmp;
}
|
在通过BitmapFactory.decodeFile(String path)方法将突破转成Bitmap时,遇到大一些的图片,我们经常会遇到OOM(Out Of Memory)的问题。所以用到了我们上面提到的BitmapFactory.Options这个类。
|
public boolean inJustDecodeBounds
|
If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.
如果inJustDecodeBounds(boolean flag)的参数是true,则不返回bitmap,但是能获取bitmap的宽和高(op.outWidth和op.outWidth) 。
设置该属性能够实现图片的压缩
2.Bitmap对象也可以通过Stream二进制流获取
|
Bitmap bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);
|
3.View转化为Bitmap
|
public static Bitmap convertViewToBitmap(View view){
view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache();
view.setDrawingCacheEnabled(false);
return bitmap;
}
|
或者
|
public static Bitmap getBitmapFromView(View view)
{
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
|
或者
|
public static Bitmap convertViewToBitmap(View view, int bitmapWidth, int bitmapHeight){
Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
view.draw(new Canvas(bitmap));
return bitmap;
}
|