关于Bitmap相关的一些总结
如何从当前View获取到Bitmap
v.setDrawingCacheEnabled(true);
v.buildDrawingCache();
Bitmap bitmap = v.getDrawingCache();
如何从TextureView中获取Bitmap
mTextureView.getBitmap();
如何压缩Bitmap
压缩成适配目标宽、高的Bitmap
/**
* get a scaled bitmap from a file located in path, adjust to destWidth and destHeight
* @param path the bitmap's file location
* @param destWidth destination width
* @param destHeight destination height
* @return a scaled bitmap
*/
public static Bitmap getScaledBitmap(String path, int destWidth, int destHeight){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
float srcWidth = options.outWidth;
float srcHeight = options.outHeight;
int inSampleSize = 1;
if (srcHeight > destHeight || srcWidth > destWidth){
float heightScale = srcHeight / destHeight;
float widthScale = srcWidth / destWidth;
inSampleSize = Math.round(heightScale > widthScale ? heightScale : widthScale);
}
options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
return BitmapFactory.decodeFile(path, options);
}
如何将Bitmap与byte[]相互转换
从Bitmap到byte[]
int bytes = bmp.getByteCount();
ByteBuffer buf = ByteBuffer.allocate(bytes);
bmp.copyPixelsToBuffer(buf);
byte[] byteArray = buf.array();
从byte[]到Bitmap
Bitmap stitchBmp = Bitmap.createBitmap(width, height, type);
stitchBmp.copyPixelsFromBuffer(ByteBuffer.wrap(byteArray));
imageView.setImageBitmap(stitchBmp);