project-light.in
  • Home
  • Privacy Policy
  • Contact Us
  • Guest Post – Write For Us
  • Sitemap
project-light.in

How to Crop and Compress Images in Dart/Flutter

  • Jeffery Williams
  • January 28, 2022
Total
0
Shares
0
0
0

In this article, I’ll cover the basics on how to crop and compress images in Dart/Flutter.

The “compress image flutter” is a tutorial that explains how to crop and compress images in Dart/Flutter.

When we wish to reduce bandwidth by deleting superfluous picture sections, we need to crop images in applications. For example, we want to post a thumbnail that isn’t too enormous in size but yet has good quality.

How-to-Crop-and-Compress-Images-in-DartFlutter

So we start searching for Flutter plugins to crop photos, and there are a lot of them, so why am I writing this? Because I’m talking about cropping photographs without a user interface in the background. We don’t always ask users to trim their images; there are situations when we need to do it without their help.

To modify photos in a number of file formats, we’ll utilize image, a dart package. We already have copyCrop(), copyCropCircle(), copyResize(), and copyResizeCropSquare() in this package, but we may need to Crop in the middle as well. Let’s start with a Crop in the middle.

Calculate the cropping rectangle.

Android Crop Center of Bitmap - Stack Overflow

First we need to Calculate the cropping rectangle. of desired aspect ratio. We want the crop rectangle to always be inside the original image. We are trying to get similar result as in Image widget with fit: BoxFit.cover.


Rectangle getCropRect({ required int sourceWidth, required int sourceHeight, required double aspectRatio, }) { var left = 0; var top = 0; var width = sourceWidth; var height = sourceHeight; if (aspectRatio < sourceWidth / sourceHeight) { width = (sourceHeight * aspectRatio).toInt(); left = (sourceWidth – width) ~/ 2; } else if (aspectRatio > sourceWidth / sourceHeight) { height = sourceWidth ~/ aspectRatio; top = (sourceHeight – height) ~/ 2; } return Rectangle(left, top, width, height); }

PHP is the programming language (php)

Crop in the middle

Now we can use this to Crop in the middle the image. Don’t forget to import image package.

as img, import ‘package:image/image.dart’

JavaScript is the programming language used in this project (javascript)

final rect = getCropRect(sourceWidth: source.width, sourceHeight: source.height, aspectRatio: aspectRatio); return img.copyCrop(source, rect.left, rect.top, rect.width, rect.height); return img.copyCrop(source, rect.left, rect.top, rect.width, rect.height); return img.copyC

PHP is the programming language (php)

Resize

That was simple, but don’t we also want to downsize the picture and make it smaller?

final cropped = centerCrop(src, aspectRatio); final cropped = cropAndResize(img.Image source, double aspectRatio, int width) img.copy = resized croppedResized; resize(cropped, width: width, interpolation: img.Interpolation.average,); resize(cropped, width: width, interpolation: img.Interpolation.average,); resize(cropped, width: width, interpolation:

PHP is the programming language (php)

What if the size of your input picture is less than the size of the intended image? The supplied picture will be upscaled. If you don’t want this, just change the code as follows:

img.Image cropAndResize(img.Image src, double aspectRatio, int width) { final cropped = centerCrop(src, aspectRatio); final croppedResized = img.copyResize( cropped, width: width, interpolation: img.Interpolation.average, ); if (cropped.width <= width) { return cropped; } return croppedResized; }

PHP is the programming language (php)

You may choose the interpolation method that best suits your needs. I chose average since it works well when the picture is scaled down by a big amount. For further information, see the GitHub issue here. https://github.com/brendan-duncan/image/issues/23

Combining all of these techniques

Future cropAndResizeFile({ required File file, required double aspectRatio, required int width, int quality = 100, }) async { final tempDir = await getTemporaryDirectory(); final destPath = path.join( tempDir.path, path.basenameWithoutExtension(file.path) + ‘_compressed.jpg’, ); return compute<_CropResizeArgs, File>( _cropAndResizeFile, _CropResizeArgs( sourcePath: file.path, destPath: destPath, aspectRatio: aspectRatio, width: width, quality: quality, )); } class _CropResizeArgs { String sourcePath; String destPath; double aspectRatio; int width; int quality; _CropResizeArgs({ required this.sourcePath, required this.destPath, required this.aspectRatio, required this.width, required this.quality, }); } Future _cropAndResizeFile(_CropResizeArgs args) async { final image = await img.decodeImage(await File(args.sourcePath).readAsBytes()); if (image == null) throw Exception(‘Unable to decode image from file’); final croppedResized = cropAndResize(image, args.aspectRatio, args.width); final jpegBytes = img.encodeJpg(croppedResized, quality: args.quality); final croppedImageFile = await File(args.destPath).writeAsBytes(jpegBytes); return croppedImageFile; }

JavaScript is the programming language used in this project (javascript)

You may be wondering why _CropResizeArgs is being used. It’s used to send information to the calculate function. What’s the point of utilizing the calculate function? The app will jank if you execute resource-intensive tasks on the main isolate. If you are unfamiliar with the phrase jank, it is simply latency and unresponsiveness. When selecting a picture, jank will result in a blank screen after you have selected your image. It’s because when you choose a picture, the main isolate must do all of the image decoding, cropping, scaling, and encoding. More information on them may be found at https://dart.dev/guides/language/concurrency. https://docs.flutter.dev/cookbook/networking/background-parsing https://docs.flutter.dev/cookbook/networking/background-parsing.

Use it

final _pickedFile = await picker.pickImage(source: ImageSource.gallery,); if (_pickedFile == null) return; final length = await _pickedFile!.length() / 1024; log(‘Picked File Size in KB $length’); await cropAndResize; await cropAndResize; await cropAndResize; await cropAndResize; await cropAndResize; await cropAndResize; await cropAnd File(file: File( pickedFile!.path), aspectRatio: 1.6, width: 800, quality: 80,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, then((value) async _croppedFile = value; final length = await value; then((value) async _croppedFile = value; final length = await value child: const length() / 1024; log(‘Compressed File Size in KB $length’); ); (Text(‘Pick a picture’),))))))))))))))))

JavaScript is the programming language used in this project (javascript)

Changing aspect ratio, width and quality we can get Crop in the middleped image with given quality and compression. We can also resize (maintaining aspect ratio) and compress images with image picker plugin. I didn’t use it here because I got terribly bad quality image after resizing and compressing. Also each time we decode and re-encode jpeg some data will be lost and it cause degraded image quality. To avoid this we decode the original image once and do all the stuffs then re-encode it to final image.

Flutter is a cross-platform mobile app development framework that has the ability to compress images. Flutter can also crop and resize images. This article will teach you how to do these things in Flutter. Reference: flutter compress base64.

Frequently Asked Questions

How do I compress images in Flutter?

A: In Flutter, you can import an image from your computer and use the slider to adjust its size. You could also take a screenshot of the app and write it directly onto your phones storage card for backup purposes.

How do I compress multiple images in Flutter?

A: You can use the mixin.image_compressor plugin, which does not require Flutter to be installed in order for you to use it.

How do I cut an image in Flutter?

A: To cut an image, go to your images folder and find the one you want. Press ctrl+c to copy it, then press Cmd + V on Mac or Ctrl +V on Windows (this opens a new browser tab) to paste it into Flutter.

Related Tags

  • dart image compression
  • flutter compress image before upload
  • flutter crop image programmatically
  • image picker image quality flutter
  • ios image compression library
Total
0
Shares
Share 0
Tweet 0
Pin it 0
Jeffery Williams

Previous Article

Is Microsoft Teams still supporting 365 accounts on Windows 11?

  • Jeffery Williams
  • January 28, 2022
View Post
Next Article

End-to-End encryption expands to include Messenger Chats

  • Jeffery Williams
  • January 28, 2022
View Post
Table of Contents
  1. Calculate the cropping rectangle.
  2. Crop in the middle
  3. Resize
  4. Combining all of these techniques
  5. Use it
    1. Frequently Asked Questions
Featured
  • 1
    How to Update DOOGEE X5 Max to Android 7.0 Nougat Stock ROM
    • April 30, 2022
  • 2
    6 Best Cheapest 4k Projectors 2022
    • April 28, 2022
  • 3
    All You Need To Know [Guide 2022]
    • April 25, 2022
  • 4
    How to Configure a Static IP Address on Alpine Linux
    • April 25, 2022
  • 5
    Sync.com vs Microsoft OneDrive (2022)
    • April 24, 2022
Must Read
  • 1
    How to Organize Virtual Events
  • 2
    How to Cancel Fashion Nova Order? [Step By Step Guide]
  • 3
    Simple Trick to Download and Use Adobe Illustrator for Free. [Working]
project-light.in
  • Home
  • Privacy Policy
  • Contact Us
  • Guest Post – Write For Us
  • Sitemap
Stay Updated Always.

Input your search keywords and press Enter.