Android控件使用篇Android专题android技术

Bitmap概念解读、基本工具类使用、高斯模糊

2021-04-02  本文已影响0人  千夜零一

Bitmap介绍

Bitmap,拆分来读,意为位图。

Bitmap是Android系统中的图像处理的最重要类之一。用它可以获取图像文件信息,进行图像剪切、旋转、缩放等操作,并可以指定格式保存图像文件。其中包含未压缩的图像信息:长、宽、颜色等。

Tips:同一张图片,放在不同目录下,会生成不同大小的Bitmap。Bitmap的长度和宽度越大,占用的内存就越大
Bitmap主要包含:颜色属性和格式属性。

效果

Bitmap应用.jpeg

用法

工具类:实现图片基本的对象类型转换和尺寸操作

/**
 * @data on 4/1/21 4:35 PM
 * @auther KC
 * @describe 采用Bitmap格式对图片进行操作的工具类
 */
public class BitmapUtil {

    private BitmapUtil(){}

    /**
     * 根据资源id获取指定大小的Bitmap对象
     * @param context   应用程序上下文
     * @param id        资源id
     * @param height    高度
     * @param width     宽度
     * @return
     */
    public static Bitmap getBitmapFromResource(Context context, int id, int height, int width){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//只读取图片,不加载到内存中
        BitmapFactory.decodeResource(context.getResources(), id, options);
        options.inSampleSize = calculateSampleSize(height, width, options);
        options.inJustDecodeBounds = false;//加载到内存中
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);
        return bitmap;
    }

    /**
     * 根据文件路径获取指定大小的Bitmap对象
     * @param path      文件路径
     * @param height    高度
     * @param width     宽度
     * @return
     */
    public static Bitmap getBitmapFromFile(String path, int height, int width){
        if (TextUtils.isEmpty(path)) {
            throw new IllegalArgumentException("参数为空,请检查你选择的路径:" + path);
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//只读取图片,不加载到内存中
        BitmapFactory.decodeFile(path, options);
        options.inSampleSize = calculateSampleSize(height, width, options);
        options.inJustDecodeBounds = false;//加载到内存中
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        return bitmap;
    }

    /**
     * 获取指定大小的Bitmap对象
     * @param bitmap    Bitmap对象
     * @param height    高度
     * @param width     宽度
     * @return
     */
    public static Bitmap getThumbnailsBitmap(Bitmap bitmap, int height, int width){
        if (bitmap == null) {
            throw new IllegalArgumentException("图片为空,请检查你的参数");
        }
        return ThumbnailUtils.extractThumbnail(bitmap, width, height);
    }

    /**
     * 将Bitmap对象转换成Drawable对象
     * @param context   应用程序上下文
     * @param bitmap    Bitmap对象
     * @return  返回转换后的Drawable对象
     */
    public static Drawable bitmapToDrawable(Context context, Bitmap bitmap){
        if (context == null || bitmap == null) {
            throw new IllegalArgumentException("参数不合法,请检查你的参数");
        }
        Drawable drawable = new BitmapDrawable(context.getResources(), bitmap);
        return drawable;
    }

    /**
     * 将Drawable对象转换成Bitmap对象
     * @param drawable  Drawable对象
     * @return  返回转换后的Bitmap对象
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable == null) {
            throw new IllegalArgumentException("Drawable为空,请检查你的参数");
        }
        Bitmap bitmap =
                Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                        drawable.getIntrinsicHeight(),
                        drawable.getOpacity() != PixelFormat.OPAQUE? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * 将Bitmap对象转换为byte[]数组
     * @param bitmap    Bitmap对象
     * @return      返回转换后的数组
     */
    public static byte[] bitmapToByte(Bitmap bitmap){
        if (bitmap == null) {
            throw new IllegalArgumentException("Bitmap为空,请检查你的参数");
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * 计算所需图片的缩放比例
     * @param height    高度
     * @param width     宽度
     * @param options   options选项
     * @return
     */
    private static int calculateSampleSize(int height, int width, BitmapFactory.Options options) {
        int realHeight = options.outHeight;
        int realWidth = options.outWidth;
        int heigthScale = realHeight / height;
        int widthScale = realWidth / width;
        if (widthScale > heigthScale) {
            return widthScale;
        } else {
            return heigthScale;
        }
    }
}

高斯模糊工具类:对图片做模糊处理,不关心图片尺寸

/**
 * @data on 4/1/21 5:53 PM
 * @auther KC
 * @describe Bitmap更多工具用法
 */
public class BitmapUtils {
    /**
     * 高斯模糊
     *
     * @param context
     * @param source
     * @param radius
     * @return
     */
    public static Bitmap rsBlur(Context context, Bitmap source, int radius) {

        Bitmap inputBmp = source;
        //(1)
        RenderScript renderScript = RenderScript.create(context);

        // Allocate memory for Renderscript to work with
        //(2)
        final Allocation input = Allocation.createFromBitmap(renderScript, inputBmp);
        final Allocation output = Allocation.createTyped(renderScript, input.getType());
        //(3)
        // Load up an instance of the specific script that we want to use.
        ScriptIntrinsicBlur scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
        //(4)
        scriptIntrinsicBlur.setInput(input);
        //(5)
        // Set the blur radius
        scriptIntrinsicBlur.setRadius(radius);
        //(6)
        // Start the ScriptIntrinisicBlur
        scriptIntrinsicBlur.forEach(output);
        //(7)
        // Copy the output to the blurred bitmap
        output.copyTo(inputBmp);
        //(8)
        renderScript.destroy();

        return inputBmp;
    }
}

工具类在Activity中的应用

class Kotlin08 : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin08)

        //调整图片的尺寸
        val bitmap1 = BitmapUtil.getBitmapFromResource(this,R.mipmap.user_img,200,200)
        ivImageView2.setImageBitmap(bitmap1)

        //对bitmap对象再操作
        val bitmap2 = BitmapUtil.getThumbnailsBitmap(bitmap1,1200,900)
        ivImageView3.setImageBitmap(bitmap2)

        //对图片做高斯模糊
        val bitmap3 = BitmapUtils.rsBlur(this,bitmap1,10)
        gsImageView.setImageBitmap(bitmap3)
    }
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".display.Kotlin08"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/ivImageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/ivImageView1"
            android:src="@mipmap/user_img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <ImageView
            android:id="@+id/gsImageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>

    <ImageView
        android:id="@+id/ivImageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

学习链接

Google官网介绍链接:https://developer.android.com/topic/performance/graphics
YouTube的视频讲解也挺好的,推荐大家看看~

Bitmap.png
上一篇下一篇

猜你喜欢

热点阅读