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);
}
相关推荐
KevinWang_3 小时前
Android Hilt 依赖注入
android
古法安卓3 小时前
Android-深入理解 Android 回调(Callback)机制
android·性能优化·android studio
古法安卓3 小时前
Android-车机 GNSS 定位数据接收问题排查
android·java·android studio
猿小猴子4 小时前
主流 Agent 之 「Zed」和 「ZCode」 介绍
ide·ai·agent·zed·zhipu·ade·zcode
FungLeo5 小时前
Flutter 吸顶分组列表实战:语义桶分组 + 点击头平滑滚动
android·flutter
阿巴斯甜6 小时前
Android 自定义权限
android
FungLeo6 小时前
Flutter 超长 StatefulWidget 拆分术:part of + extension on State 实战
android·flutter·dart
小王C语言8 小时前
MySQL 数据类型:数值类型、字符串类型、日期和时间类型、enum 和 set、find_in_set 查询
android·数据库·mysql
我命由我123458 小时前
Android 控件 - CardView(快速实现圆角)
android·java·java-ee·kotlin·android studio·android-studio·android runtime
码云数智-园园8 小时前
Android 全方位性能优化合集
android·性能优化