Bitmap操作

从资源中拿到Bitmap对象并显示

从资源中的drawable对象中获取位图的方法如下

//拿到资源
BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.mm01);
//获取位图对象
Bitmap bitmap = bd.getBitmap();
//获取位图的宽高
int w = bitmap.getWidth();
int h = bitmap.getHeight();
//显示位图
iv2.setImageBitmap(bitmap);

截取图片并保存

//从bitmap图片,截取坐标为(100,100)、宽高为(200,200)的新位图
Bitmap partCopy = Bitmap.createBitmap(bitmap, 100, 100, 200, 200);
//保存位图到path
private void saveBitmap(Bitmap bitmap, String path) {
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(path);
        //已压缩的方式保存位图,压缩范围0-100,100为等比例保存不压缩
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
        fos.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (null != fos) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

获取图片缩略图

如果要显示的图片太大,远远超出手机屏幕大小,强行加载可能造成内存溢出,此时,可以使用缩略图来显示该图。

//获取图片缩略图
private Bitmap getSmallBitmap(String path, int maxWidth, int maxHeight) {
    //解码位图的配置对象
    BitmapFactory.Options options = new BitmapFactory.Options();
    //设置缩略图模式
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    //开启宽高解析模式,只解析原图的宽高
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);
    //此模式下,可以在不加载像素到内存的情况下得到原图的宽高
    int width = options.outWidth;
    int height = options.outHeight;
    //计算宽高在各自方向上的缩略倍数
    int zoomOutWidth = (int) Math.ceil((float) width / maxWidth);
    int zoomOutHeight = (int) Math.ceil((float) height / maxHeight);
    //只有缩略倍数大于1,即图片大于手机屏幕,才有必要进行缩略;
    //宽高方向哪个缩略倍数大,就取大的缩略倍数作为整个原图的缩略倍数
    if (zoomOutWidth > 1 || zoomOutHeight > 1) {
        if (zoomOutWidth > zoomOutHeight) {
            options.inSampleSize = zoomOutWidth;
        } else {
            options.inSampleSize = zoomOutHeight;
        }
    }
    //关闭宽高解析模式
    options.inJustDecodeBounds = false;
    //按计算的缩略比例来解码原图,即:从原图中按缩略比提取像素点
    Bitmap smallBitmap = BitmapFactory.decodeFile(path, options);
    return smallBitmap;
}

猜你喜欢

转载自blog.csdn.net/yeby_yugo/article/details/80598424