Android NoteX Q3:如何通过图片获取指定大小的bitmap?

一般通过图片获取其Bitmap的方法如下:

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.head);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
System.out.println("Bitmap weight = "+width+" Bitmap height "+height);
Bitmap bitmap1 = Bitmap.createBitmap(bitmap, width/3, height/4, bitmap.getWidth() /3, bitmap.getHeight() /2);
imageView.setImageBitmap(bitmap1);

但是以上方法只是’裁剪’,如果只是想要固定大小的而不裁剪呢?

/**
 * Creates a new bitmap, scaled from an existing bitmap, when possible. If the
 * specified width and height are the same as the current width and height of
 * the source bitmap, the source bitmap is returned and no new bitmap is
 * created.
 *
 * @param src       The source bitmap.
 * @param dstWidth  The new bitmap's desired width.
 * @param dstHeight The new bitmap's desired height.
 * @param filter    Whether or not bilinear filtering should be used when scaling the
 *                  bitmap. If this is true then bilinear filtering will be used when
 *                  scaling which has better image quality at the cost of worse performance.
 *                  If this is false then nearest-neighbor scaling is used instead which
 *                  will have worse image quality but is faster. Recommended default
 *                  is to set filter to 'true' as the cost of bilinear filtering is
 *                  typically minimal and the improved image quality is significant.
 * @return The new scaled bitmap or the source bitmap if no scaling is required.
 * @throws IllegalArgumentException if width is <= 0, or height is <= 0
 */
public static Bitmap createScaledBitmap(@NonNull Bitmap src, int dstWidth, int dstHeight,
        boolean filter) {
    Matrix m = new Matrix();

    final int width = src.getWidth();
    final int height = src.getHeight();
    if (width != dstWidth || height != dstHeight) {
        final float sx = dstWidth / (float) width;
        final float sy = dstHeight / (float) height;
        m.setScale(sx, sy);
    }
    return Bitmap.createBitmap(src, 0, 0, width, height, m, filter);
}

在sdk中可以发现以上的方法,是使用的matrix在scale层面来进行处理,从而达到指定尺寸大小的要求。

共同学习、探讨

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ganshenml

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值