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);
}
相关推荐
1024小神7 分钟前
Vscode/Cursor中的Prettier插件格式化降级操作
ide·vscode·编辑器
Digitally24 分钟前
如何将文件从 iPhone 传输到 Android
android·ios·iphone
a31582380643 分钟前
Android修改调试屏幕的选择方向
android·adb·屏幕旋转
超级数据查看器1 小时前
超级数据查看器 更新日志(包含的功能)
android·java·数据库·sqlite·安卓
AiFlutter1 小时前
Flutter-Android不能通过apply script方法应用Gradle插件
android·flutter
2501_915106321 小时前
iOS 抓包工具实战实践指南,围绕代理抓包、数据流抓包和拦截器等常见工具
android·ios·小程序·https·uni-app·iphone·webview
恋猫de小郭1 小时前
Flutter 又迎大坑修改?iOS 26 键盘变化可能带来大量底层改动
android·flutter·ios·kotlin
102400241 小时前
vscode无法选择conda虚拟环境下的解释器
ide·vscode·conda
e***98571 小时前
PHP下载站开发全攻略
android
胖虎11 小时前
从一个自定义的下载Dialog,说清 Android 自定义弹窗的关键点。
android·dialog·gitee·自定义弹窗