Last active
May 27, 2025 08:45
-
-
Save rijieli/f715ee2c55bcc4fc87c5c85b6f7bfd13 to your computer and use it in GitHub Desktop.
PDF to PNG keep alpha
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# brew install imagemagick ghostscript | |
# Check if an input file is provided | |
if [ $# -eq 0 ]; then | |
echo "Usage: $0 input.pdf [output_basename]" | |
exit 1 | |
fi | |
# Define input and output file names | |
INPUT_PDF="$1" | |
OUTPUT_BASE="${2:-$(basename "$INPUT_PDF" .pdf)}" | |
HIGH_RES_TMP="${OUTPUT_BASE}-900dpi.png" | |
echo "Converting $INPUT_PDF to a high-resolution intermediate..." | |
# --- Create a single high-resolution image (900 DPI) --- | |
magick -density 900 "$INPUT_PDF" \ | |
-colorspace sRGB \ | |
-background transparent \ | |
-alpha on \ | |
-antialias \ | |
-filter Lanczos \ | |
-define pdf:use-cropbox=true \ | |
-quality 95 \ | |
PNG32:"$HIGH_RES_TMP" | |
# Check if the high-resolution image was created successfully | |
if [ ! -f "$HIGH_RES_TMP" ]; then | |
echo "Error: Failed to create the high-resolution image." | |
exit 1 | |
fi | |
echo "Creating resized images..." | |
# --- Get the width of the 900 DPI image --- | |
WIDTH=$(magick identify -format "%w" "$HIGH_RES_TMP") | |
# --- Create smaller images by resizing the high-resolution one --- | |
magick "$HIGH_RES_TMP" -resize $((WIDTH * 150 / 900)) -quality 95 PNG32:"${OUTPUT_BASE}-1x.png" | |
magick "$HIGH_RES_TMP" -resize $((WIDTH * 300 / 900)) -quality 95 PNG32:"${OUTPUT_BASE}-2x.png" | |
magick "$HIGH_RES_TMP" -resize $((WIDTH * 450 / 900)) -quality 95 PNG32:"${OUTPUT_BASE}-3x.png" | |
# --- Clean up the large intermediate file --- | |
rm "$HIGH_RES_TMP" | |
echo "✓ Created: ${OUTPUT_BASE}-1x.png, ${OUTPUT_BASE}-2x.png, ${OUTPUT_BASE}-3x.png" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: