-
-
Save mgalgs/4c4fe4027f0606e68a044ac7ea0fa8d9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// imgLib -> Image package from https://pub.dartlang.org/packages/image | |
import 'package:image/image.dart' as imglib; | |
import 'package:camera/camera.dart'; | |
imglib.Image convertCameraImagetoImage(CameraImage image) { | |
try { | |
if (image.format.group == ImageFormatGroup.yuv420) { | |
return _convertYUV420(image); | |
} else if (image.format.group == ImageFormatGroup.bgra8888) { | |
return _convertBGRA8888(image); | |
} | |
return null; | |
} catch (e) { | |
print(">>>>>>>>>>>> ERROR:" + e.toString()); | |
} | |
return null; | |
} | |
Future<List<int>> convertCameraImagetoPng(CameraImage image) async { | |
try { | |
imglib.PngEncoder pngEncoder = new imglib.PngEncoder(); | |
// Convert to png | |
List<int> png = pngEncoder.encodeImage(convertCameraImagetoImage(image)); | |
return png; | |
} catch (e) { | |
print(">>>>>>>>>>>> ERROR:" + e.toString()); | |
} | |
return null; | |
} | |
// 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 (compresion: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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment