A set of Node.js scripts to:
- Compress Images (including HEIC support) and optionally save size data to an Excel file.
- Upload Compressed Images to Dropbox and generate shared links, saving them to an Excel file.
- Prerequisites
- Installation
- Configuration
- Directory Structure
- Usage
- Scripts Overview
- Customization
- Troubleshooting
- License
- Node.js v14+
- npm (Node Package Manager)
- A valid Dropbox API access token (for the Dropbox upload script)
-
Clone the repository (or download the files) to your local machine:
git clone https://github.com/prakharaug/image-compressor-sharp.git cd image-compressor-sharp -
Install dependencies:
npm install
This will install:
- sharp (for image resizing & conversion)
- exceljs (for generating Excel files)
- heic-convert (for converting HEIC to PNG)
- dropbox and
node-fetch(for Dropbox SDK) - dotenv (for environment variable management)
-
Environment VariablesCreate a
.envfile in the project root containing your Dropbox access token:ACCESS_TOKEN=your_dropbox_access_token_here
ACCESS_TOKEN: Your Dropbox API access token (required bydropbox_upload.js).
-
Directory Names
- For image compression, the default input directory is
_Original_Images - The compressed images will be written to
_Compressed_Images - You can change these directory names directly in
compress_image_mp.jsif needed.
- For image compression, the default input directory is
-
Dropbox Base Folder In
dropbox_upload.js, set:// Base Dropbox folder where images will be uploaded const DROPBOX_BASE_FOLDER = '/2025 02 14';
Update
'/2025 02 14'to your desired Dropbox folder path.
your-repo-name/
│
├── _Original_Images/ # Place all original images (JPG, PNG, HEIC, etc.) here
│
├── _Compressed_Images/ # Will be created automatically by the compressor script
│ └── (subfolders / files) # Compressed .webp files will appear here
│
├── compress_image_mp.js # Script to recursively compress images + export Excel
├── dropbox_upload.js # Script to upload compressed images to Dropbox + export Excel
├── Image_Sizes.xlsx # (Generated after running compression; lists original vs. compressed sizes)
├── _Compressed_Images/
│ └── image_links.xlsx # Generated Excel with Dropbox shared links (after running the uploader)
│
├── .env # Your environment variables (e.g., ACCESS_TOKEN)
├── package.json
└── README.md # ← (this file)
Note: The compressor script will create the
_Compressed_Imagesfolder if it does not already exist. Likewise, the Dropbox script will placeimage_links.xlsxinside the_Compressed_Imagesfolder after uploading.
-
Prepare
- Place all source images (supported formats:
.jpg,.jpeg,.png,.webp,.heic) inside the_Original_Imagesdirectory. - Ensure
_Original_Imagesexists at the project root.
- Place all source images (supported formats:
-
Run the Compressor
node compress_image_mp.js
- The script will:
- Scan
_Original_Imagesrecursively (subfolders included). - Convert any
.heicfiles to PNG before compression. - Resize images so that they do not exceed 20 megapixels (configurable).
- Save compressed output as
.webpfiles to the mirrored directory structure inside_Compressed_Images. - Skip any files that are already compressed (by checking if the target
.webpexists). - Log progress to the console.
- Scan
- The script will:
-
Excel Report
- If
SAVE_EXCELis set totrueincompress_image_mp.js(default), anImage_Sizes.xlsxfile will be generated at the project root, containing:- File Name
- Original Size (Bytes)
- Compressed Size (Bytes)
- If
Prerequisite: Ensure you have already run the compressor script so that the
_Compressed_Imagesfolder exists and contains.webpfiles.
-
Configure
- Verify your Dropbox access token is set in
.env. - Adjust
DROPBOX_BASE_FOLDER(indropbox_upload.js) to your preferred Dropbox path.
- Verify your Dropbox access token is set in
-
Run the Dropbox Uploader
node dropbox_upload.js
- The script will:
- Recursively traverse
_Compressed_Images(including any subfolders). - Create corresponding folders inside Dropbox under the path specified by
DROPBOX_BASE_FOLDER. - Upload each compressed image, overwriting if it already exists.
- Generate a shared link (direct download) for each uploaded file.
- Accumulate an array of
{ FileName, Link }objects. - At the end, save these links to
image_links.xlsx(inside_Compressed_Images).
- Recursively traverse
- The script will:
-
Result
- After successful execution, you will have
image_links.xlsxinside_Compressed_Images/, which lists:- FileName: Full Dropbox path (lower‐cased).
- Link: A direct-download URL (
dl=1).
- After successful execution, you will have
-
Imports
sharp: Image processing (resize & conversion).fs&path: File system traversal.exceljs: Creating an Excel workbook.heic-convert: Converting.heic→ PNG.
-
Configuration Constants
const inputDir = '_Original_Images'; const outputDir = '_Compressed_Images'; const MAX_MEGAPIXELS = 20; // Maximum allowed megapixels before downscaling const OUTPUT_FORMAT = 'webp'; const QUALITY = 85; // WebP quality (0–100) const SAVE_EXCEL = true; // Toggle Excel report generation
-
Workflow
- Create
_Compressed_Imagesfolder if missing. processImages(inputDir, outputDir):- Recursively iterates through every file and subfolder in
_Original_Images. - Skips non-image files.
- Converts
.heic→ PNG buffer, then compresses/resizes (if needed) and saves as.webp. - Stores
{ fileName, originalSize, compressedSize }in an array.
- Recursively iterates through every file and subfolder in
- After processing, if
SAVE_EXCEListrue, callsaveToExcel(...)to createImage_Sizes.xlsx.
- Create
-
Error Handling
- Logs any errors per file, but continues processing other files.
-
Imports
Dropbox(fromdropboxSDK) &node-fetch.fs&path: File system traversal.exceljs: Creating an Excel workbook.dotenv: Reading environment variables.
-
Configuration Constants
const ACCESS_TOKEN = process.env.ACCESS_TOKEN; const dbx = new Dropbox({ accessToken: ACCESS_TOKEN, fetch }); const DROPBOX_BASE_FOLDER = '/2025 02 14'; // Base path in Dropbox const imagesFolder = '_Compressed_Images'; // Local folder to upload
-
Workflow
uploadImagesAndGenerateLinks(imagesFolder):- Verify
_Compressed_Imagesexists locally. - Call
processFolder(localFolder, dropboxFolder, imageLinks):- Ensure the corresponding Dropbox folder exists (creates if missing).
- Recursively upload files and subfolders:
- For each file:
uploadFile(localPath, dropboxPath)uploads (overwrite mode).getSharedLink(dropboxPath)retrieves (or creates) a direct-download shared link.- Accumulates
{ FileName: dropboxPath, Link }intoimageLinks.
- For each file:
- After all uploads, write
image_links.xlsx(inside_Compressed_Images) with columns:- FileName (Dropbox path)
- Link (direct download URL)
- Verify
-
Error Handling
- Any upload/folder-creation errors are logged to the console (with
error.message).
- Any upload/folder-creation errors are logged to the console (with
-
Adjust Quality / Resolution
- In
compress_image_mp.js, modify:const MAX_MEGAPIXELS = 20; // Maximum resolution threshold (in megapixels) const OUTPUT_FORMAT = 'webp'; const QUALITY = 85; // WebP output quality (0–100) const SAVE_EXCEL = true; // Set to `false` to skip generating Image_Sizes.xlsx
- You may also change
inputDirandoutputDirto your preferred folder names.
- In
-
Change Dropbox Folder Path
- In
dropbox_upload.js, update:const DROPBOX_BASE_FOLDER = '/2025 02 14';
- Use any valid Dropbox path (e.g.,
/MyApp/CompressedImages).
- In
-
Environment Variables
- You can store additional config in
.env(e.g., different Dropbox token or folder names) and adjust the code to read those values.
- You can store additional config in
-
Error: Cannot find module 'sharp'(or any dependency)- Run
npm installto ensure all dependencies are installed.
- Run
-
Missing
_Original_Imagesor_Compressed_Imagesdirectories- Make sure you have created
_Original_Imagesin the project root before runningcompress_image_mp.js. - The compressor script will auto-create
_Compressed_Images, but if your OS has permission restrictions, create it manually and grant write access.
- Make sure you have created
-
HEIC Conversion Failures
- Make sure
heic-convertis installed:npm install heic-convert
- Some HEIC files may have uncommon encodings; check that your
.heicimages are valid.
- Make sure
-
Dropbox Authentication Errors
- Ensure your
.envfile contains a validACCESS_TOKEN. - Confirm no trailing spaces or line breaks in the token.
- If you receive “Invalid access token” from Dropbox, generate a new token via the Dropbox App Console.
- Ensure your
-
Excel File Won’t Generate
- Verify
SAVE_EXCELis set totrue(for the compressor). - For Dropbox, ensure the script finished without errors, then look for
image_links.xlsxinside_Compressed_Images.
- Verify
This project is released under the MIT License. Feel free to modify and redistribute as needed.
Enjoy! If you encounter any issues or have suggestions for improvement, please open an issue or submit a pull request.