Android 中常常需要对图片进行缩放裁剪等处理,这里简单的介绍一下这两种处理方式的方法
1.裁剪
/** * Returns an immutable bitmap from the specified subset of the source * bitmap. The new bitmap may be the same object as source, or a copy may * have been made. It is initialized with the same density and color space * as the original bitmap. * * @param source The bitmap we are subsetting * @param x The x coordinate of the first pixel in source * @param y The y coordinate of the first pixel in source * @param width The number of pixels in each row * @param height The number of rows * @return A copy of a subset of the source bitmap or the source bitmap itself. * @throws IllegalArgumentException if the x, y, width, height values are * outside of the dimensions of the source bitmap, or width is <= 0, * or height is <= 0 */ public static Bitmap createBitmap(@NonNull Bitmap source, int x, int y, int width, int height) { return createBitmap(source, x, y, width, height, null, false); }
将图片转换为Bitmap对象,具体如何转换可以到BitmapFactory中查找。将转换了的bitmap对象传入方法中,x为从横轴上开始裁剪的开始位置,y为从纵轴上开始裁剪的开始位置,width为需要裁剪的宽度,height为需要裁剪的高度。然后这个方法返回的就是你裁剪的图片
2.缩放
public Bitmap resizeImage(Bitmap bitmap, int w, int h) { Bitmap BitmapOrg = bitmap; int width = BitmapOrg.getWidth(); int height = BitmapOrg.getHeight(); int newWidth = w; int newHeight = h; float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); // if you want to rotate the Bitmap // matrix.postRotate(45); Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width, height, matrix, true); return resizedBitmap; }
缩放通过矩阵Matrix来实现,首先获取原始Bitmap的宽高,然后通过你传入的宽高来计算缩放的比率,将比率设置给矩阵,然后通过系统提供的api来实现缩放。