I am using the camera
flutter lib and startImageStream
method of the controller
Every X ms I get one CameraImage
input and want to save this in file as jpg/png
I am using some code found online but it has 2 issues
- It is grayscaled and without any colors
- It is rotated 90 degree anti-clockwise
The code that I am currently using is
import 'package:camera/camera.dart';
import 'package:image/image.dart' as imglib;
Future<List<int>> convertImageToPng(CameraImage image) async {
imglib.Image? img;
if (image.format.group == ImageFormatGroup.yuv420) {
img = _convertYUV420(image);
} else if (image.format.group == ImageFormatGroup.bgra8888) {
img = _convertBGRA8888(image);
}
imglib.PngEncoder pngEncoder = imglib.PngEncoder();
// Convert to png
List<int> png = pngEncoder.encodeImage(img!);
return png;
}
// CameraImage BGRA8888 -> PNG
// Color
imglib.Image _convertBGRA8888(CameraImage image) {
return imglib.Image.fromBytes(
image.width,
image.height,
image.planes[0].bytes,
format: imglib.Format.bgra,
);
}
// CameraImage YUV420_888 -> PNG -> Image (compression:0, filter: none)
// Black
imglib.Image _convertYUV420(CameraImage image) {
var img = imglib.Image(image.width, image.height); // Create Image buffer
Plane plane = image.planes[0];
const int shift = (0xFF << 24);
// Fill image buffer with plane[0] from YUV420_888
for (int x = 0; x < image.width; x++) {
for (int planeOffset = 0;
planeOffset < image.height * image.width;
planeOffset += image.width) {
final pixelColor = plane.bytes[planeOffset + x];
// color: 0x FF FF FF FF
// A B G R
// Calculate pixel color
var newVal = shift | (pixelColor << 16) | (pixelColor << 8) | pixelColor;
img.data[planeOffset + x] = newVal;
}
}
return img;
}
method convertImageToPng
I need a cross-platform ios+android method to convert CameraImage to jpg/png with proper colors and without rotating.
_controller?.startImageStream(
(image) {
final asPng = await convertImageToPng(image);
// todo then I save this on disk or uploa
},
);
Any help will be appreciated.
2
Answers
After working for like one week I managed to got a function that converts
Yuv420
CameraImage
topng
with colors, BUT the image has bad rotation, is inverted upside down (I think -180 degrees)My improved COLORFUL function is. I still need to understand how to rotate properly the image
To capture and save images you can use as follows.
Then by your method:
Or as an alternative:
To rotate by the right side you can use this, passing bytedata’s As UintList:
And to get rotated image by passing the original you can use: