2

There are several ways of retrieving ByteData from network image or file, however I haven't found one where an existing Image in memory (or cache) can be converted into ByteData.

Specifically referring to :

var resizedImage = ResizeImage(img.image, height: 28, width: 28);

For example, both the following answers assume there is a file:

How to load Image widgets from ByteData in Flutter

How to get a Flutter Uint8List from a Network Image?

There is a toByteData method from dart.ui, but that also requires the image to come from a raw data.

According to ResizeImage documentation, it's stored in cache, But I can't access it without using cache manager.

The cached image will be directly decoded and stored at the resolution defined by width and height. The image will lose detail and use less memory if resized to a size smaller than the native size.

I've used path_provider to get temporary directory, but it seems empty when resize image is executed. Is there anyway to convert image into ByteData without having the image in a path?

hydroweaver
  • 109
  • 9

1 Answers1

1

Try resolving the resized image's image provider:

  resizedImage.imageProvider
      .resolve(createLocalImageConfiguration(context))
      .addListener(ImageStreamListener((info, _) {
        var bingo = info.image.toByteData();
  }));
Richard Heap
  • 48,344
  • 9
  • 130
  • 112
  • Thanks, this provides the Uint8List, but, I get 'Could not instantiate image codec.' exception. On further examination, the original image list length is 28597 (28 Bytes) (800x600 pixels) whereas the resized one (28x28) pixels is 960000 (0.96 MB), so it looks like the resize function is not providing the correct image. I use the following : var resizedImage = ResizeImage(img.image, height: 28, width: 28); Not sure what the conversion problem is, but it's in the resizing. Thanks very much for the response though, but what does it mean to have a listener for resolver of an image provider? – hydroweaver Jan 14 '20 at 09:55
  • If all you want to do is make a thumbnail, look at the image package. Don't forget the optional param of toByteData - you likely want PNG, not the default of rgba. An image provider has to allow for async io and parsing of images, so it's an async idea. It can also deal with animated GIFs which have more than one frame. This is why you add a listener, to be notified when the image stream is ready. – Richard Heap Jan 14 '20 at 11:36
  • Right let me try doing that. The whole point was to take an image from memory or camera, resize it, so it can be consumed by a ML model for classification. I'll try to use toByteData parameters and also see the output for other files. Thanks again! – hydroweaver Jan 14 '20 at 12:25