实现Java Bitmap转Byte数组

1. 流程

步骤 描述
1 加载Bitmap图片
2 将Bitmap转为Byte数组

2. 代码实现

步骤1:加载Bitmap图片

// 加载Bitmap图片
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);

这段代码通过BitmapFactory.decodeResource()方法加载资源中的图片,并将其保存在bitmap对象中。

步骤2:将Bitmap转为Byte数组

// 将Bitmap转为Byte数组
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

这段代码使用Bitmap.compress()方法将bitmap对象压缩为PNG格式的字节流,并将其保存在byteArray数组中。

类图

classDiagram
    class Bitmap {
        + decodeResource()
        + compress()
    }
    class BitmapFactory {
        + decodeResource()
    }
    class ByteArrayOutputStream {
        + toByteArray()
    }

序列图

sequenceDiagram
    participant Developer
    participant BitmapFactory
    participant Bitmap
    participant ByteArrayOutputStream

    Developer ->> BitmapFactory: 加载Bitmap图片
    BitmapFactory ->> Bitmap: decodeResource()
    Developer ->> Bitmap: 将Bitmap转为Byte数组
    Bitmap ->> ByteArrayOutputStream: compress()
    ByteArrayOutputStream ->> ByteArrayOutputStream: toByteArray()

通过以上步骤和代码,你可以实现Java中Bitmap图片转为Byte数组的功能。希望这篇文章对你有所帮助,加油!