how to convert uint8list to png in dart using package:image.dart and manipulate the picture later on?

134 Views Asked by At

I use 'package:image/image.dart' to manipulate pictures in dart, the goal is to

  1. download picture from url
  2. encode it from Uint8list to other format -> example PNG
  3. ad some rectangle (its about object recognition I have starting position x,y and height and width)
  4. convert it to Uint8list and return

unfortunately I can't pass stage 2 (see logs below), tried multiple times with different conversations func etc. and always get null :( any help?

ps. I can't use dart:ui package so, please post solutions with Image package etc.

import 'package:image/image.dart' as img_package;

    Future<Uint8List> getPictureWithFrame() async {
      http.Response response = await http.get(
        Uri.parse(EXAMPLE_URL),
      );
      Uint8List imageUint8Encoded = response.bodyBytes;
      print("#### step1 ${imageUint8Encoded.runtimeType}");
      img_package.Image? imagePNG =
          img_package.PngDecoder().decode(imageUint8Encoded);
      print("#### step2 ${imagePNG}");
    
      return imageUint8Encoded;
    }

output

flutter: #### step1 Uint8List
flutter: #### step2 null
1

There are 1 best solutions below

0
On

It looks like your PNG is an invalid format. This code works fine - try it:

  final uri = Uri.parse(
    'https://sample-videos.com/img/Sample-png-image-100kb.png',
  );
  final response = await http.get(uri);
  final i2 = PngDecoder().decode(response.bodyBytes);
  print(i2); // prints: Image(272, 170, uint8, 4)