Recovering Images from WordPress’ Downscaled Images

Many years ago WordPress introduce a new method for handling large images. If an image larger then 2560px wide is uploaded then WordPress would generate a scaled down version. These scaled images help keep users from accidentally linking to truly massive original sized images. This past week these scaled images also helped me restore missing images for one of my new WordPress customers.

A new customer had original images that were empty.

I don’t know if this was done intentionally through an offloading media plugin or maliciously though a previous infection. Either way, one customer reached out to me having issues with some of their older blog posts missing images. Upon digging in I concluded this was an issues with their website from before they moved it over to Anchor Hosting. That means the same issue was happening with previous web host as revealed over cPanel.

I noticed most of the missing original images were 0KB. Luckily the scaled version of these images were healthy. I decided to create a script to restore the scaled images over the original image.

Recovering missing original images based on scaled versions with a BASH script.

Create a file missing-images.sh with the following. Grant it execute permissions chmod +x missing-images.sh then run ./missing-images.sh. This will overwrite all original uploaded images with their scaled version. Now on a normal website this would actually overwrite the original image, which might actually be useful in certain situations. Either way, feel free to adapt and use as you like.

cd ~/public/wp-content/uploads/
files=$(find . -name "*.jpg" -o -name "*.png")
for file in ${files[@]}; do
    if [[ "$file" == *".jpg" ]]; then
        if [ -f "${file/.jpg/-scaled.jpg}" ]; then
            size=$( du -sh "${file/.jpg/-scaled.jpg}" | awk '{print $1}' )
            echo "Restoring ${file/.jpg/-scaled.jpg} ($size) to $file"
            cp "${file/.jpg/-scaled.jpg}" "$file"
        fi
        continue
    fi
    if [[ "$file" == *".png" ]]; then
        if [ -f "${file/.png/-scaled.png}" ]; then
            size=$( du -sh "${file/.png/-scaled.png}" | awk '{print $1}' )
            echo "Restoring ${file/.png/-scaled.png} ($size) to $file"
            cp "${file/.png/-scaled.png}" "$file"
        fi
        continue
    fi
done