What is the Dart image package?
The Dart Image package is a library that enables the loading, saving, and processing of images in various file formats.
Both server and web applications can utilize the library because it is wholly developed in the Dart language and does not rely on dart:io. However, it won’t perform as quickly as a native library since the library was created entirely in the Dart language and is not executed natively.
Image formats
The following are the image formats that are supported:
-
Read/Write:
- PNG / Animated APNG
- JPEG
- Targa
- GIF / Animated GIF
- PVR(PVRTC)
- ICO
- BMP
-
Read Only:
- WebP / Animated WebP
- TIFF
- Photoshop PSD
- OpenEXR
-
Write Only:
- CUR
How to use the image package
For Dart:
- Run
dart pub add imageon the terminal.
For Flutter:
-
Run
flutter pub add imageon the terminal. -
Or, add to your package’s
pubspec.yamlfile.
dependencies:
image: ^3.2.2
- Import the package to your file.
import 'package:image/image.dart';
Code example
The following example shows how to use the image package to load a JPEG, resize it, and save it as a PNG in Dart.
# This file configures the static analysis results for your project (errors, # warnings, and lints). # # This enables the 'recommended' set of lints from `package:lints`. # This set helps identify many issues that may lead to problems when running # or consuming Dart code, and enforces writing Dart using a single, idiomatic # style and format. # # If you want a smaller set of lints you can change this to specify # 'package:lints/core.yaml'. These are just the most critical lints # (the recommended set includes the core lints). # The core lints are also what is used by pub.dev for scoring packages. include: package:lints/recommended.yaml # Uncomment the following section to specify additional rules. # linter: # rules: # - camel_case_types # analyzer: # exclude: # - path/to/excluded/files/** # For more information about the core and recommended set of lints, see # https://dart.dev/go/core-lints # For additional information about configuring this file, see # https://dart.dev/guides/language/analysis-options
Code explanation
- Line 1–2: We import the needed libraries.
- Line 7: We use the method
decodeJpg()from theimagepackage, read the JPG image from the file, and save a result to a variable calledimage. - Line 10: We resize the image and save the result to a variable named
thumbnail. - Line 13: Finally, we save the
thumbnailas aPNGusing theencodePng()from theimagepackage.
Note: To see the
thumbnail-bg.pngfile, we have to enterlsin the terminal.
Free Resources