Android Studio开发之路(十二)image、byte[]、mat、Bitmap几种格式互转合集

一、知识点

  1. Camerax中的
    imageCapture用例默认的image格式是JPEG,
    而ImageAnalysis用例默认的image格式是YUV_420_888.

二、ImageAnalysis用例中ImageProxy转mat

YUV转Mat

三、imageCapture中image专byte[]

如下边代码,

c 复制代码
//拍照,保存到内存
private void takephoto(){

  imageCapture.takePicture(ContextCompat.getMainExecutor(this),new ImageCapture.OnImageCapturedCallback() {
            @Override
            public void onCaptureSuccess(ImageProxy image) {
                ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                byte[] data = new byte[buffer.capacity()];
                buffer.get(data);
                //判断是否正确的转为了jpeg格式的字节数组
                if (isJpeg(data)) {
                    //继续操作
                }
                image.close();
            }
            
  });
}
//判断获取的图像是否是jpeg格式
    private boolean isJpeg(byte[] data) {
        if (data == null || data.length < 2) {
            return false;
        }
        // JPEG 文件的开头两个字节应该是 0xFF, 0xD8
        return data[0] == (byte)0xFF && data[1] == (byte)0xD8;
    }

四、byte[]转mat, 与mat转byte[]

c 复制代码
public void byteMat(byte[] data){
     int width=image.getWidth();
     int height=image.getHeight();
     //byte[]转mat
     Mat mat = Imgcodecs.imdecode(new MatOfByte(data), Imgcodecs.IMREAD_COLOR);

     // 使用Imgcodecs.imencode将Mat对象编码为JPEG格式byte[]
     MatOfByte matbuffer = new MatOfByte();                    
     boolean result = Imgcodecs.imencode("a.jpg", mat, matbuffer);
     // 检查是否成功编码
      if (result) {
          // 获取编码后的字节数组
          byte[] jpegBytes = matbuffer.toArray();
          //byte[]转mat
          Mat mat2 = Imgcodecs.imdecode(new MatOfByte(jpegBytes), Imgcodecs.IMREAD_COLOR);
        }
}

五、byte[]转bitmap, mat转bitmap

c 复制代码
public void bitMap(byte[] data, Mat new_img){
    //byte转bitmap,这个有一点问题就是转之后的bitmap方向不正
     Bitmap bit=BitmapFactory.decodeByteArray(data, 0, data.length);
    
    //mat转bitmap
    Bitmap mbitmap = Bitmap.createBitmap(new_img.width(), new_img.height(), Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(new_img,mbitmap);
}
相关推荐
WarPigs5 分钟前
Visual Studio笔记
ide·笔记·visual studio
Java 码农9 分钟前
MySQL EXPLAIN 详解与优化指南
android·mysql·adb
仟濹19 分钟前
IDEA 软件下载 + 安装 | 操作步骤
java·ide·intellij-idea
schinber1 小时前
使用pycharm自带debug模式运行flask时报错
ide·pycharm·flask
ithicker3 小时前
Pycharm+Deepseek结合使用Continue插件无法返回中文产生乱码
ide·python·pycharm
stevenzqzq5 小时前
Android Hilt 入门教程_传统写法和Hilt写法的比较
android
wuwu_q5 小时前
用通俗易懂方式,详细讲讲 Kotlin Flow 中的 map 操作符
android·开发语言·kotlin
_李小白5 小时前
【Android FrameWork】第五天:init加载RC文件
android
2501_916007476 小时前
手机使用过的痕迹能查到吗?完整查询指南与步骤
android·ios·智能手机·小程序·uni-app·iphone·webview
黄毛火烧雪下6 小时前
React Native (RN)项目在web、Android和IOS上运行
android·前端·react native