miker.blog

PNG Compress and Base64 Conversion CLI Tool

Introduction

This is a command-line interface (CLI) tool I designed for Mac users who need to quickly compress PNG images and convert them to Base64 encoding. It's particularly useful for web developers and designers looking to optimize images for web use, reduce file sizes, and prepare images for inline embedding in CSS or HTML.

The Complete Script

Let's start by looking at the entire script:

Detailed Breakdown

Bash Component

  1. Shebang: #!/bin/bash specifies that this is a bash script.

  2. ASCII Art: The script includes a fun ASCII art of what appears to be a computer or robot.

  3. Homebrew Installation:

    This line installs the required tools (pngquant and base64) using Homebrew without updating Homebrew itself.

Perl Component

The main functionality is written in Perl, utilizing the Term::ANSIColor module for colorful output.

  1. Initialization:

    • $|++; enables autoflush for immediate output.

    • The b() function is called to print a separator line.

  2. User Interface:

    • Displays a welcome message and warning about the destructive nature of the process.

    • Waits for user input to continue.

  3. File Selection Menu:

    • Uses glob(q|*.png|) to list all PNG files in the current directory.

    • Creates a numbered menu of these files.

  4. User Input Handling:

    • Accepts user input for file selection.

    • Handles various input cases (empty input, quit commands, invalid numbers).

  5. Command Execution:

    • Constructs the command string for PNG compression and Base64 conversion.

    • Uses system to execute the constructed command.

  6. Utility Function:

    • sub b is a simple function to print a separator line.

Command-line Arguments

The script ends with two important command-line arguments passed to the Perl interpreter:

  1. PNG Compression:

    This uses pngquant to compress the PNG with a quality range of 65-80%.

  2. Base64 Conversion:

    This converts the compressed PNG to Base64 and saves it to a text file.

How to Use

  1. Save the script to a file (e.g., png_compress_base64.sh).

  2. Make it executable: chmod +x png_compress_base64.sh

  3. Run it: ./png_compress_base64.sh

  4. Follow the on-screen prompts to select and process a PNG file.

Key Features

Considerations

Conclusion

This CLI tool streamlines the process of optimizing PNG images for web use. By combining compression and Base64 conversion, it provides a quick and efficient way to prepare images for various web development scenarios, such as inline CSS backgrounds or data URIs in HTML.