Last active
June 28, 2024 06:20
-
-
Save parthnvaswani/125bd06c0196cc6a07e2cd714b5373b6 to your computer and use it in GitHub Desktop.
BASH Script for updating image file extension according to its mime type in a recursive manner and log it in JSON file
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
# Image Folder | |
IMAGE_FOLDER="./uploads" | |
# JSON File | |
JSON_FILE="./images.json" | |
# JSON string | |
JSON_STRING="" | |
# Loop through all image files recursively in the folder and update the extension | |
for image in $(find $IMAGE_FOLDER -type f); do | |
# Get the file extension | |
extension="${image##*.}" | |
# Get the mime type | |
mime_type=$(file --mime-type -b $image) | |
# Get image name without extension | |
image_name=$(basename $image .$extension) | |
# Get image location | |
image_location=$(dirname $image) | |
# New image name | |
new_image_name="" | |
# Check if mime type and extension are the same | |
if [ $extension == "jpeg" ] && [ $mime_type == "image/jpeg" ]; then | |
continue | |
elif [ $extension == "jpg" ] && [ $mime_type == "image/jpeg" ]; then | |
continue | |
elif [ $extension == "png" ] && [ $mime_type == "image/png" ]; then | |
continue | |
elif [ $extension == "gif" ] && [ $mime_type == "image/gif" ]; then | |
continue | |
elif [ $extension == "webp" ] && [ $mime_type == "image/webp" ]; then | |
continue | |
fi | |
# Update the mime type | |
if [ $mime_type == "image/jpeg" ]; then | |
mv $image $image_location/$image_name.jpg | |
new_image_name=$image_location/$image_name.jpg | |
elif [ $mime_type == "image/png" ]; then | |
mv $image $image_location/$image_name.png | |
new_image_name=$image_location/$image_name.png | |
elif [ $mime_type == "image/gif" ]; then | |
mv $image $image_location/$image_name.gif | |
new_image_name=$image_location/$image_name.gif | |
elif [ $mime_type == "image/webp" ]; then | |
mv $image $image_location/$image_name.webp | |
new_image_name=$image_location/$image_name.webp | |
fi | |
# Add old and new name to json file | |
JSON_STRING+="{"\"old_name"\": "\"$image\"", "\"new_name"\": "\"$new_image_name"\"}," | |
done | |
# Add the json string to the json file | |
echo "["${JSON_STRING%?}"]" > $JSON_FILE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment