Search code examples
sortingjpegimage-compression

How to convert jpg images sorted by size


I have an folder of jpg images, that are numbered "01.jpg" up to "24.jpg".

They have all different sizes. My TV sorts files of an USB-Stick only by size... I need an efficient way to compress all images, so the order-by-size matches order-by-name.

I tried to do it manually, but figured quickly out that it was a bad idea.


Solution

  • First off: This is an X-Y-Problem. The underlying problem is that your TV won't let you sort by name.

    That said, this is a fun problem. Properly compressing the images to ensure the order however presumably is hard and likely to incur significant losses in quality. If you do not want to compromise quality, you'll have to bloat the images instead. This is also much simpler. Here is a Bash script that bloats JPEG images to force the order imposed by their naming:

    #!/bin/bash
    maxsize=0
    for file in *.jpg
    do
        size=$(stat --format %s $file)
        if [[ $size -gt $maxsize ]]
        then
            maxsize=$size
            echo "$file has correct size of $size bytes already"
        else
            maxsize=$((maxsize+128))
            tobloat=$((maxsize-size))
            # Dirty, dirty hack: Embed the bloat string as a comment
            # (which can get arbitrarily large);
            # use a temporary file to not run into the shell command length limit
            tmpfile=$(mktemp /tmp/jpeg-bloating.XXXXXX)
            while [ $tobloat -ne 0 ]
            do
                tobloat=$(($tobloat-1))
                echo -n 'a' >> "$tmpfile"
            done
            exiftool $file -overwrite_original '-Comment<='"$tmpfile"
            rm "$tmpfile"
            echo "$file bloated to $(stat --format %s $file) bytes"
        fi
    done
    

    It uses exiftool to add appropriately many as as copyright string a comment to bloat the file; the EXIF data does not appear to be compressed (no run-length encoding or the like is used), so this works. A decent difference of at least 128 bytes is ensured.