Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Web: How Do You Compress an Image/File?

Flutter Web is currently in beta, so there's a lack of available info/resources on how to do this.

I could not find any flutter packages compatible with web to do this. Any tips?

Here's my code:

uploadImage() async {
File file;
FileReader fileReader = FileReader();
InputElement uploadInput = FileUploadInputElement();
uploadInput.click();
uploadInput.onChange.listen((event) {
  file = uploadInput.files.first;
  fileReader.readAsDataUrl(file);
  fileReader.onLoadEnd.listen((event) {
    if (file.type == "image/jpg" || file.type == "image/jpeg" || file.type == "image/png") {
      String base64FileString = fileReader.result.toString().split(',')[1];

      //COMPRESS FILE HERE

      setState(() {
        userImgFile = file;
        userImageByteMemory = base64Decode(base64FileString);
      });
    } else {
      CustomAlerts().showErrorAlert(context, "Image Upload Error", "Please Upload a Valid Image");
    }
  });
});
}
like image 963
Mukai Selekwa Avatar asked Mar 17 '20 19:03

Mukai Selekwa


People also ask

How do I compress images in flutter?

Use image_picker package: You can use the built-in imageQuality property of ImagePicker to compress the image. This property takes a value between 0 and 100 and represents a percentage of the quality of the original image.

How do I compress a PNG file in flutter?

dart'; //if the origin image is PNG, it doesn't work var compressImageData = await FlutterImageCompress. compressWithFile( //returns Future<List<int>> image_path, minWidth: 50, minHeight: 50, quality: 100, format: CompressFormat. png //e.g. compress to PNG );


1 Answers

Well I have spend days trying to figure it out. Here is what you need to understand. There is no proper library/package which can compress image in flutter web at the time I am writing this.So I end up using javascript code in my project.
Don't worry it is not too much of work.You can also read my blog for complete example.

Here is what you need to do.
1. Add browser image compresser(to compress image) cdn,filesaver(save image) cdn in your flutter web index.html file
also create new js file name app.js and import it too.

<script type="text/javascript"
          src="https://cdn.jsdelivr.net/npm/[email protected]/dist/browser-image-compression.js"></script>
  <script src="http://cdn.jsdelivr.net/g/filesaver.js"></script>
  <script src="app.js" defer></script>

2. Now that import is done update app.js as below

function compressAndDownloadImage(base64) {
        var url = base64;

        fetch(url)
            .then(res => res.blob())
            .then(blob => {
                var imageFile = blob;
                console.log('originalFile instanceof Blob', imageFile instanceof Blob); // true
                console.log(`originalFile size ${imageFile.size / 1024 / 1024} MB`);

                var options = {
                    maxSizeMB: 0.2,//right now max size is 200kb you can change
                    maxWidthOrHeight: 1920,
                    useWebWorker: true
                }
                imageCompression(imageFile, options)
                    .then(function (compressedFile) {
                        console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
                        console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB
                        console.log(compressedFile);
                        saveAs(new Blob([compressedFile], { type: "image/jpeg" }), Math.floor(Date.now() / 1000) + '.jpeg');
                        return uploadToServer(compressedFile); // write your own logic
                    })
                    .catch(function (error) {
                        console.log(error.message);
                    });
            })

    }

3. Okay now you are ready to call this function whereever you need to compress image call this dart function from anywhere

import 'dart:js' as js; //import first
//call compressAndDownloadImage with base64 image you want to compress
var base64data="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
js.context.callMethod(
            'compressAndDownloadImage', ['$base64data']);

UPDATE
If you wish to upload file to server via dart. then send the file to dart and send to server/firebase from there.
To send the compress file to flutter add this line of code.

window.parent.postMessage(compressedFile, "*");

And also to receive in flutter make sure you have this listener function.
import 'dart:html' as html;

window.addEventListener("message", (event) {
  html.MessageEvent event2 = event;
  html.Blob blob = event2.data;
  print(blob.type); // you can do whatever you want in dart
});

Note
This will work only in flutter web. if you run in mobile you will get 'dart:js' or 'dart:html' compile error. You can fix this by import base on platform.
Hope it help someone, Thanks

like image 60
codingwithtashi Avatar answered Dec 09 '22 22:12

codingwithtashi