我想使用ImageReader中的图像字节数组来构造用于条形码扫描的FirebaseVisionImageMetadata对象(作为ML Kit的一部分)。我正在使用Camera2 API,并按照this PR支持帧预览。Size sz = chooseOptimalSize();mCallbackImageDataReader = ImageReader.newInstance(sz.getWidth(), sz.getHeight(), ImageFormat.YV12, 1); mCallbackImageDataReader.setOnImageAvailableListener(reader -> { byte[] data = getByteDataFromImageReader(reader); if (data != null) { //rotation compensation calculation not shown mCallback.onPreviewFrame(data, reader.getImageFormat(), reader.getWidth(), reader.getHeight(), rotationCompensation); } }, null);@Nullableprivate byte[] getByteDataFromImageReader(@NonNull ImageReader reader) { byte[] data = null; try (Image image = reader.acquireNextImage()) { Image.Plane[] planes = image.getPlanes(); if (planes.length > 0) { ByteBuffer buffer = planes[0].getBuffer(); data = new byte[buffer.remaining()]; buffer.get(data); } } return data;}但是,当我将结果格式传递给FirebaseVisionImageMetadata生成器时,出现以下错误:final FirebaseVisionImageMetadata meta = new FirebaseVisionImageMetadata.Builder() .setFormat(format) //exception thrown here .setWidth(width) .setHeight(height) .setRotation(rotation) .build();java.lang.IllegalArgumentException at com.google.android.gms.common.internal.Preconditions.checkArgument(Unknown Source:5) at com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata$Builder.setFormat(Unknown Source:13)我传递给ImageReader的格式是ImageReader.YV12,因为FirebaseVisionImageMetadata仅接受NV21或YV12,但是由于ImageReader不接受NV21,所以我留下了。当我使用这种格式时(如上所示),相机将以黑屏启动。我也尝试过传递YV12,但这会导致与ImageReader.YUV_420_888相同的IllegalArgumentException。我的猜测是我可能必须将字节数组转换为其他格式,或转换为其他格式(?)。任何帮助,将不胜感激。资料来源:https://github.com/google/cameraview/pull/123/commits/f90580b1891c3edf91b4a254219d08b01110afcehttps://developer.android.com/reference/android/graphics/ImageFormat.html?hl=BG#YUV_420_888 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 我想到了。我需要使用reader.acquireNextImage();mCallbackImageDataReader.setOnImageAvailableListener(reader -> { try (Image image = reader.acquireNextImage()) { if (image != null) { //compute rotationCompensation mCallback.onPreviewFrame(image, rotationCompensation); } } }, null); (adsbygoogle = window.adsbygoogle || []).push({}); 10-06 02:07