Без категории

Resizing images to save space in web hosting

Situations described below can happen not only inside web hosting it could be applied to other places where you need to free up space. I face it with my current web hosting and its tariff plan. One day used space is become close to tariff limits. I was a bit surprises as I don’t have many images on site. Unfortunately some or many of them were uploaded with really big resolution. All of us knows that in web we don’t require such a big size of images like we receive from out Cameras.

Web images size and other best practices

To have a fastest page load we need to use thumbnails, caching and for full size view we don’t require large images like 4k.

Thumbnails and caching is not a part of this article, you can setup them via you CMS (in my case WordPress). Image size for full page view I recommend to 2048px on largest side of images. Unless you are providing really high quality 8k images as you main site key feature.

Using AI to prepare a draft of scripts to use

I used Chat GPT to prepare a basic prototype of PowerShell script for going thru all files in folder recursively and applying one or another action. I got this:

# Specify the folder containing your images
$sourceFolder = "C:\Path\To\Your\Folder"

# Specify the maximum size for the biggest side (2048 pixels)
$maxSize = 2048

# Path to the ImageMagick convert.exe executable (update this to your installation path)
$imageMagickPath = "C:\Path\To\ImageMagick\convert.exe"

# Function to resize an image
function Resize-Image($imagePath) {
    $outputPath = $imagePath  # The output path will be the same as the input path
    
    # Get the image dimensions
    $imageInfo = & $imageMagickPath $imagePath -format "%wx%h" 2>$null
    $width, $height = $imageInfo.Split('x')

    # Check if the image needs resizing
    if ($width -gt $maxSize -or $height -gt $maxSize) {
        # Resize the image to fit within the specified dimensions
        & $imageMagickPath $imagePath -resize "$maxSize"x"$maxSize^" $outputPath
        Write-Host "Resized: $imagePath"
    } else {
        Write-Host "Skipped (Size OK): $imagePath"
    }
}

# Recursively process images in the folder
Get-ChildItem -Path $sourceFolder -File -Recurse | ForEach-Object {
    if (@("jpg", "jpeg", "png", "gif", "bmp") -contains $_.Extension.ToLower()) {
        Resize-Image $_.FullName
    }
}

Write-Host "Resize operation complete."

After that I started to apply it and adjust command line arguments of ImageMagick and other improvements. My improvements were the following:

  1. Remove non-image files (I simply don’t need to touch them)
  2. Remove files which are already satisfy require resolution
  3. During adjusting arguments of ImageMagick I found it’s command to do exactly what I need, but it still require for me both points above to reduce size of work and network communication later.

Code for resizing whole folder if you have everything prepared

mogrify -resize 2048x2048> *.jpg
mogrify -resize 2048x2048> *.jpeg
mogrify -resize 2048x2048> *.png
mogrify -resize 2048x2048> *.bmp
mogrify -resize 2048x2048> *.gif

Full script which removes non-image files, removed images less than 2k (I don’t need them for next step), resize large images to 2k.

$sourceFolder = "C:\Path\To\Your\Folder"
$maxSize = 2048

$imageMagickPath = "C:\Path\To\ImageMagick\convert.exe"
$imageMagickIdentifyPath = "C:\Path\To\ImageMagick\identify.exe"

$allowedExtensions = @(".jpg", ".jpeg", ".png", ".gif", ".bmp")

#*.jpg; *.jpeg; *.png; *.gif; *.bmp;

function Process-File(
    $imagePath) {
    $outputPath = $imagePath

    $imageInfo = & $imageMagickIdentifyPath -format "%[fx:w]x%[fx:h];" $imagePath    
    $widthStr, $heightStr = $imageInfo.Split(';')[0].Split('x')
    $width = [int]$widthStr
    $height = [int]$heightStr    

    if ($width -gt $maxSize -or $height -gt $maxSize) {
        $option = "" + $maxSize + "x" + $maxSize + ">"
        & $imageMagickPath $imagePath -resize $option $outputPath
        Write-Host "Resized: $imagePath"
    }
    else {
        if ($width -lt $maxSize -and $height -lt $maxSize) {        
            Remove-Item -Path $imagePath -Force
            #Write-Host "Removed thumbnail: $imagePath"
        }    
        else {
            Write-Host "Skipped: $imagePath"
        }
    }
}

Get-ChildItem -Path $sourceFolder -File -Recurse | ForEach-Object {
    $filePath = $_.FullName
    try {  
        if ($_.Extension -ne "") {
            $fileExtension = $_.Extension.ToLower()
            if (-not $allowedExtensions.Contains($fileExtension)) {
                Remove-Item -Path $filePath -Force            
                #Write-Host "Removed non-image: " $filePath
            }

            if ($allowedExtensions.Contains($fileExtension)) {
                Process-File $filePath
            }
        }
        else {
            Remove-Item -Path $filePath -Force
            #Write-Host "Removed non-image: " $filePath
        }

    }
    catch { 
        Write-Host $_
        Remove-Item -Path $filePath -Force

        Write-Host "Removed due to error: " $filePath 
    }

}

Write-Host "Resize and cleanup operation complete."

Free up space on web hosting via FTP

This is simplistic part. First of course you need to download all content from web hosting to your local, not a big archive around 12 GB in my case. Install ImageMagick, I used version on Windows ImageMagick-7.1.1-Q16-HDRI. Unpack archive, adjust paths in script and run it.

Now we have all files are prepared, we just need to upload them back to web hosting which have to be configured for FTP access. I used WinSCP, opened my folder with images and same folder on remote server. Copied over network with replacement. Hence paths left the same, images become smaller, space is released we can continue usual post writing and surfing thru world net.

Used resources

Leave a Reply

Your email address will not be published. Required fields are marked *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.