Drawable d = getResources().getDrawable(R.drawable.icon);
Resources 轉 Bitmap
Bitmap mBitmap = BitmapFactory.decodeResource(this.getResources(),
R.drawable.test_image);
Drawable 轉 Bitmap
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
Bitmap 轉 Drawable
Drawable d = new BitmapDrawable(getResources(), bitmap);
使用 Bitmap 更改長寬
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
使用 Bitmap 使兩張圖片置中
private Bitmap mergeBitmap(Bitmap firstBitmap, Bitmap secondBitmap) {
Bitmap bitmap = Bitmap.createBitmap(firstBitmap.getWidth(), firstBitmap.getHeight(),
firstBitmap.getConfig());
Canvas canvas = new Canvas(bitmap);
int firstWidth = firstBitmap.getWidth();
int firstHeight = firstBitmap.getHeight();
int secondWidth = secondBitmap.getWidth();
int secondHeight = secondBitmap.getHeight();
canvas.drawBitmap(firstBitmap, new Matrix(), null);
canvas.drawBitmap(secondBitmap, firstWidth/2-secondWidth/2,
firstHeight/2-secondHeight/2, null);
return bitmap;
}
使用 Bitmap 旋轉圖片
private Bitmap rotateImage(Bitmap bitmap, float rotate){
Matrix matrix = new Matrix();
matrix.setRotate(rotate);
return Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
參考資料 : How to convert a Drawable to a Bitmap?
沒有留言:
張貼留言