skip to Main Content

I want to resize an image. But I get the following error in img.copyResize(image, width: 120)

The argument type ‘Future<Image?>’ can’t be assigned to the parameter type ‘Image’.

import 'dart:io';
import 'package:image/image.dart' as img;
import 'package:image_picker/image_picker.dart';

  Future resizeImage() async {
    final XFile? pickedImage =
        await ImagePicker().pickImage(source: ImageSource.gallery);
    if (pickedImage != null) {
      var image = img.decodeImageFile(pickedImage.path);
      var thumbnail = img.copyResize(image, width: 120);
    }
  }

2

Answers


  1. The problem you are experiencing it’s probably because your variable "image" can be null… To fix this, if you are 100% sure this variable will have always some data, you can do the following:

    var image = img.decodeImageFile(pickedImage!.path); // Adding "!"
    var thumbnail = img.copyResize(image!, width: 120); // Adding "!"
    

    Although I’m not sure because there’s not that much information given

    Login or Signup to reply.
  2. decodeImageFile(String path, {int? frame}) function of package image: ^4.1.3 is future that returns nullable Image. Await it then null check.

    Solution

    if (pickedImage != null) {
        var image = await img.decodeImageFile(pickedImage.path);
        if (image != null) {
          var thumbnail = img.copyResize(image, width: 120);
        }
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search