toImgImage method
Image
toImgImage(
- CameraImage cameraImage
Converts the raw camera image into a platform-appropriate image format.
On Android, the YUV420 format is converted into a standard image format. On iOS, the BGRA8888 format is handled with padding removal if needed. Throws an exception if the camera format is unsupported.
Implementation
img.Image toImgImage(CameraImage cameraImage) {
if (Platform.isAndroid) {
return _yuv420ToImage(cameraImage);
}
if (Platform.isIOS) {
final plane = cameraImage.planes[0];
final int width = cameraImage.width;
final int height = cameraImage.height;
final int bytesPerRow = plane.bytesPerRow;
final Uint8List bytes = plane.bytes;
// Check if row padding exists on iOS and remove if necessary
final bool hasPadding = bytesPerRow != width * 4;
if (!hasPadding) {
final Uint8List cleanBytes = Uint8List.fromList(bytes);
return img.Image.fromBytes(
width: width,
height: height,
bytes: cleanBytes.buffer,
order: img.ChannelOrder.bgra,
);
}
// Handle row padding by stripping it out
final Uint8List cleanBytes = Uint8List(width * height * 4);
int dstIdx = 0;
for (int y = 0; y < height; y++) {
final int rowStart = y * bytesPerRow;
final int rowBytes = width * 4;
cleanBytes.setRange(dstIdx, dstIdx + rowBytes, bytes, rowStart);
dstIdx += rowBytes;
}
return img.Image.fromBytes(
width: width,
height: height,
bytes: cleanBytes.buffer,
order: img.ChannelOrder.bgra,
);
}
throw Exception('Camera format not supported: ${cameraImage.format.group}');
}