Android BitmapUtil图片工具类

✍️作者简介:沫小北/码农小北(专注于Android、Web、TCP/IP等技术方向)

🐳博客主页:沫小北/码农小北 开源中国稀土掘金51cto博客博客园知乎简书慕课网CSDN

🔔如果文章对您有一定的帮助请👉关注✨、点赞👍、收藏📂、评论💬。

🔥如需转载请参考【转载须知】

Android BitmapUtil 图片的工具类,它提供了许多常用的方法来处理和操作 Bitmap 图片。这些方法包括更改透明度、缩放图片、保存图片到相册、压缩图片、获取 Bitmap 大小等等。通过这个工具类,你可以更加方便地处理 Bitmap 图片,以满足你的各种需求。

BitmapUtil 使用实例

在这个实例中,我们展示了如何使用 BitmapUtil 类的各种方法来处理和操作 Bitmap 图片。你可以根据这个示例中的代码来了解如何使用 BitmapUtil 类中的各种功能。

java 复制代码
 // 1. 将Drawable转换为Bitmap
 Drawable drawable = getResources().getDrawable(R.drawable.example_image);
 Bitmap bitmapFromDrawable = BitmapUtil.drawableToBitmap(drawable);

 // 2. 将Bitmap转换为字节数组
 byte[] bytesFromBitmap = BitmapUtil.bitmapToBytes(bitmapFromDrawable);

 // 3. 从View获取Bitmap
 View rootView = findViewById(android.R.id.content);
 Bitmap bitmapFromView = BitmapUtil.getBitmapFromView(rootView);

 // 4. 按比例压缩Bitmap
 // 请确保您有一个有效的Bitmap对象
 Bitmap compressedBitmap = BitmapUtil.compressByScale(bitmapFromDrawable, 100, 100);

 // 5. 获取Bitmap大小
 int bitmapSize = BitmapUtil.getBitmapBytes(bitmapFromDrawable);

 // 6. 从本地路径获取Bitmap
 String filePath = "your_file_path";
 Bitmap bitmapFromPath = BitmapUtil.getBitmapFromLocalPath(filePath);

 // 7. 保存Bitmap到文件
 String savePath = "your_save_file_path";
 BitmapUtil.saveBitmapFile(bitmapFromDrawable, savePath);

 // 8. 释放Bitmap资源
 BitmapUtil.recycle(bitmapFromDrawable);

BitmapUtil 工具类

这个版本的 BitmapUtil 类包含了许多常用的 Bitmap 操作,可以满足你大部分的需求。如果你有其他特定的功能需求,也可以在此基础上进一步添加。

java 复制代码
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;

import androidx.annotation.NonNull;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class BitmapUtil {
    public static final int BITMAP_MAX_SIZE = 200; //kb

    private BitmapUtil() {
        // 私有构造函数
    }

    /**
     * 更改 bitmap 透明度
     *
     * @param srcBitmap 原始 bitmap
     * @param alpha     透明度
     * @param isRecycle 是否释放原图
     * @return 更改透明度后的 bitmap
     */
    public static Bitmap toAlpha(Bitmap srcBitmap, int alpha, boolean isRecycle) {
        Paint paint = new Paint();
        paint.setAlpha(alpha);
        Bitmap descBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(descBitmap);
        c.drawBitmap(srcBitmap, 0, 0, paint);
        if (isRecycle) {
            recycle(srcBitmap);
        }
        return descBitmap;
    }

    /**
     * 缩放图片
     *
     * @param bitmap      原始 bitmap
     * @param scaleWidth  缩放宽度
     * @param scaleHeight 缩放高度
     * @return 缩放后的 bitmap
     */
    public static Bitmap createBitmap(Bitmap bitmap, float scaleWidth, float scaleHeight) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    }

    /**
     * 保存图片到相册
     *
     * @param context 应用程序上下文
     * @param bmp     需要保存的 bitmap
     */
    public static void saveImageToGallery(Context context, Bitmap bmp) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "COAL");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = "coal_" + System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        MediaScannerConnection.scanFile(context, new String[]{file.toString()}, null, null);
    }

    /**
     * 根据 Bitmap 转换成 Uri
     *
     * @param context 应用程序上下文
     * @param inImage 需要转换的 bitmap
     * @return 转换后的 Uri
     */
    public static Uri bitmapToUri(Context context, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

    /**
     * Drawable 转换成 bitmap
     *
     * @param drawable 需要转换的 drawable
     * @return 转换后的 bitmap
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ?
                Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }
    
    /**
     * bitmap 转换成 byte
     *
     * @param bitmap
     * @return 转换后的 byte
     */
    public static byte[] bitmapToBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        return stream.toByteArray();
    }

    /**
     * 从View获取Bitmap
     *
     * @param view 文件路径
     * @return  返回 bitmap
     */
    public static Bitmap getBitmapFromView(View view) {
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }
    
    /**
     * 按比例大小压缩Bitmap
     *
     * @param srcBitmap 文件路径
     * @param targetWidth 设置宽度
     * @param targetHeight 设置高度
     * @return  返回 bitmap
     */
    public static Bitmap compressByScale(Bitmap srcBitmap, int targetWidth, int targetHeight) {
        return Bitmap.createScaledBitmap(srcBitmap, targetWidth, targetHeight, true);
    }

    /**
     * 质量压缩图片
     *
     * @param image 需要压缩的 bitmap
     * @return 压缩后的图片 byte 数组
     */
    public static byte[] compressImageByte(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        while (baos.toByteArray().length / 1024 > BITMAP_MAX_SIZE) {
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
            options -= 10;
        }
        return baos.toByteArray();
    }

    /**
     * 获取 bitmap 大小
     *
     * @param bitmap 目标 bitmap
     * @return bitmap 的大小
     */
    public static int getBitmapBytes(Bitmap bitmap) {
        int result = bitmap.getByteCount();
        if (result < 0) {
            throw new IllegalStateException("Negative size: " + bitmap);
        }
        return result;
    }

    /**
     * 释放 bitmap 资源
     *
     * @param bitmap 需要释放的 bitmap
     */
    public static void recycle(Bitmap bitmap) {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
    }

    /**
     * 根据图片路径获取 bitmap
     *
     * @param context  应用程序上下文
     * @param filePath 图片文件路径
     * @return 对应的 bitmap
     */
    public static Bitmap getBitmapByUrl(@NonNull Context context, String filePath) {
        File file = new File(filePath);
        Uri uri = Uri.fromFile(file);
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * bitmap 转文件
     *
     * @param bitmap   需要转换的 bitmap
     * @param filePath 文件路径
     */
    public static void saveBitmapFile(Bitmap bitmap, String filePath) {
        File file = new File(filePath);
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 本地图片转化为Bitmap
     *
     * @param filePath 文件路径
     * @return  返回 bitmap
     */
    public static Bitmap getBitmapFromLocalPath(String filePath) {
        return BitmapFactory.decodeFile(filePath);
    }
}

无论是哪个阶段,坚持努力都是成功的关键。不要停下脚步,继续前行,即使前路崎岖,也请保持乐观和勇气。相信自己的能力,你所追求的目标定会在不久的将来实现。加油!

本文使用 文章同步助手 同步

相关推荐
言之。15 分钟前
Kotlin快速入门
android·开发语言·kotlin
为什么不问问神奇的海螺呢丶19 分钟前
n9e categraf redis监控配置
前端·redis·bootstrap
云飞云共享云桌面20 分钟前
推荐一些适合10个SolidWorks设计共享算力的服务器硬件配置
运维·服务器·前端·数据库·人工智能
符哥200840 分钟前
Android 权限分类说明
android
大模型玩家七七1 小时前
安全对齐不是消灭风险,而是重新分配风险
android·java·数据库·人工智能·深度学习·安全
李少兄1 小时前
MySQL 中为时间字段设置默认当前时间
android·数据库·mysql
刘联其1 小时前
.net也可以用Electron开发跨平台的桌面程序了
前端·javascript·electron
韩曙亮1 小时前
【jQuery】jQuery 选择器 ④ ( jQuery 筛选方法 | 方法分类场景 - 向下找后代、向上找祖先、同级找兄弟、范围限定查找 )
前端·javascript·jquery·jquery筛选方法
前端 贾公子1 小时前
Node.js 如何处理 ES6 模块
前端·node.js·es6
pas1361 小时前
42-mini-vue 实现 transform 功能
前端·javascript·vue.js