I'm working with Flutter camera package to take a picture from camera and now I'm trying to show an image that has been cropped from that taken picture. I use image package to crop the picture. As you can see in following code, I call the copyCrop function that return img.Image
data type:
import 'package:image/image.dart' as img;
final XFile imageFile = await _controller.takePicture();
final bytes = await imageFile.readAsBytes();
final uncroppedImage = img.decodeImage(bytes);
final cropPosition = overlayKey.globalPaintBounds;
final img.Image croppedImage =
img.copyCrop(
uncroppedImage,
cropPosition.left.toInt(),
cropPosition.top.toInt(),
cropPosition.width.toInt(),
cropPosition.height.toInt());
I'm having problem with showing the cropped image to Image widget in Flutter. As you can see that the img.Image data type isn't the same data type with Image from Flutter. Then I tried to convert it to Uint8List then load it to the widget using Image.memory.
final croppedImageBytes = croppedImage.getBytes(); // return Uint8List
...
// somewhere else
Image.memory(croppedImageBytes);
However it gives me an error like this:
E/FlutterJNI(20985): Failed to decode image
E/FlutterJNI(20985): android.graphics.ImageDecoder$DecodeException: Failed to create image decoder with message 'unimplemented'Input contained an error.
E/FlutterJNI(20985): at android.graphics.ImageDecoder.nCreate(Native Method)
E/FlutterJNI(20985): at android.graphics.ImageDecoder.access$200(ImageDecoder.java:173)
E/FlutterJNI(20985): at android.graphics.ImageDecoder$ByteBufferSource.createImageDecoder(ImageDecoder.java:250)
E/FlutterJNI(20985): at android.graphics.ImageDecoder.decodeBitmapImpl(ImageDecoder.java:1863)
E/FlutterJNI(20985): at android.graphics.ImageDecoder.decodeBitmap(ImageDecoder.java:1856)
E/FlutterJNI(20985): at io.flutter.embedding.engine.FlutterJNI.decodeImage(FlutterJNI.java:524)
======== Exception caught by image resource service ================================================
The following _Exception was thrown resolving an image codec:
Exception: Invalid image data
When the exception was thrown, this was the stack:
#0 _futurize (dart:ui/painting.dart:5886:5)
#1 ImageDescriptor.encoded (dart:ui/painting.dart:5741:12)
#2 instantiateImageCodecFromBuffer (dart:ui/painting.dart:2092:60)
#3 PaintingBinding.instantiateImageCodecFromBuffer (package:flutter/src/painting/binding.dart:153:15)
#4 MemoryImage._loadAsync (package:flutter/src/painting/image_provider.dart:1090:20)
<asynchronous suspension>
====================================================================================================
But, whenever I load the image directly using Uint8List (without cropping), it still works fine. Is there any solutions to solve this?
I've finally found the solution to this problem. I just have to encode the bytes first before loading it in Image.memory (from Flutter). Here is the snippet.