Image Compressor Script
A command-line Dart script to recursively scan a directory for JPG and PNG image files, display them in a tree structure, and then resize and compress them to a specified output directory.
Features
- Recursively scans a source directory (defaults to
assets/
). - Identifies
.jpg
,.jpeg
, and.png
image files. - Presents the found image files in a clear tree-like structure.
- Requires user confirmation before starting the compression process.
- Resizes images to a specified width and height.
- Compresses JPG images with a configurable quality setting.
- Supports PNG images (resized, but PNG is a lossless format, so quality setting applies only to JPG).
- Saves compressed images to an output directory (defaults to
output/
), preserving the original subfolder structure.
Getting started
Prerequisites
- Ensure you have the Dart SDK installed.
- This script requires the
image
andpath
packages.
Installation
-
Save the provided Dart code (from the previous turn) into a file, e.g.,
compress_script.dart
, within your project directory (like the root of your Flutter project if you intend to compress its assets). -
Create a
pubspec.yaml
file in the same directory if you don't have one. -
Add the necessary dependencies to your
pubspec.yaml
:dependencies: image: ^4.1.7 # Use the latest version path: ^1.8.0 # Use the latest version
-
Run
dart pub get
in your terminal from the directory containingpubspec.yaml
andcompress_script.dart
.
Usage
-
Run the script using the Dart VM:
dart run flutter_assets_compresser
-
The script will scan the directory specified by the
inputDir
variable (defaulting to./assets
). -
It will print a tree structure showing all found JPG and PNG image files.
-
You will be prompted to confirm if you want to compress the found images.
-
Type
y
and press Enter to proceed with the compression. Type anything else to cancel. -
The compressed images will be saved to the directory specified by the
outputDir
variable (defaulting to./output
), maintaining their relative paths from the input directory.
You can modify the inputDir
, outputDir
, width
, height
, and quality
variables directly in the compress_script.dart
file to customize the behavior.
// Example configuration section in compress_script.dart
void main(List<String> arguments) async {
// --- Configuration ---
const String inputDir = 'assets'; // Directory to scan
const String outputDir = 'compressed_images'; // Directory to save output
const int quality = 75; // Desired JPEG quality (0 to 100)
// ... rest of the script
}