PHPBB论坛40G无扩展名图片批量压缩问题求助
Solution for Compressing Extension-Less Images in PHPBB Forum
Hey there! I get it—dealing with 40GB of extension-less JPEG/PNG/GIF files from PHPBB is tricky since your original script relies on file extensions to pick the right tool. Let's fix this by detecting the actual image type first instead of guessing from filenames.
Core Approach
We'll use the file command to identify each file's MIME type (like image/png or image/jpeg), then route it to the appropriate compression tool you already have installed. Here's a modified script that handles all your image types:
#!/bin/sh # Loop through all files (skip directories) in current and subdirectories find . -type f | while read -r file; do # Get the MIME type of the file (clean output with -b) mime_type=$(file --mime-type -b "$file") echo "Processing $file ($mime_type)..." # Route to the right compression tool based on MIME type case "$mime_type" in image/png) # Use pngcrush (same parameters as your original script) pngcrush -rem alla -reduce -brute "$file" temp.png if [ $? -eq 0 ]; then mv -f temp.png "$file" echo "✅ Successfully compressed PNG: $file" else rm -f temp.png echo "❌ Failed to compress PNG: $file" fi ;; image/jpeg) # Use jpegtran (preserve your original optimization flags) jpegtran -copy none -optimize -perfect "$file" > temp.jpg if [ $? -eq 0 ]; then mv -f temp.jpg "$file" echo "✅ Successfully compressed JPEG: $file" else rm -f temp.jpg echo "❌ Failed to compress JPEG: $file" fi ;; image/gif) # Use ImageMagick's convert to optimize GIFs convert "$file" -layers optimize temp.gif if [ $? -eq 0 ]; then mv -f temp.gif "$file" echo "✅ Successfully compressed GIF: $file" else rm -f temp.gif echo "❌ Failed to compress GIF: $file" fi ;; *) # Skip any non-image files echo "⏭️ Skipping non-image file: $file" ;; esac done
Key Details & Tips
- File Detection:
file --mime-type -bgives us a reliable way to identify image types without extensions—way more accurate than guessing. - Error Handling: Just like your original script, we only replace the original file if compression succeeds, so you don't lose data if something goes wrong.
- Test First: Before running on all 40GB, test with a small batch! Modify the
findline tofind . -type f | head -10to process only the first 10 files and verify everything works. - Backup: If possible, make a backup of a subset of files first—better safe than sorry with large datasets.
- Background Execution: Since this will take a long time, run it in the background with logs:
This lets it keep running even if you disconnect from SSH, and you can check progress withnohup ./compress_images.sh > compression_log.txt 2>&1 &tail -f compression_log.txt. - Optional PNG Optimization: If you're okay with minor quality loss for better compression, replace the
pngcrushline withpngquant --force --output temp.png "$file"—it's great for reducing PNG sizes significantly.
内容的提问来源于stack exchange,提问作者Anabanti
相关产品推荐
相关产品推荐

