Media library

Class 'Format':
-a Field 'Width'
-a Field 'Height'

Class Image:
-a Field 'Image' to contain the original image with Field role 'Original blob field'.
-a Field 'Width'
-a Field 'Height'
-a Field 'Filesize'

Class 'Resized image':
-a field 'Main image' linking to class 'Image'
-a Field 'Image' that contains the resized image
-a Field 'Format' linking to the 'class 'Format'
-an Integer Field 'Minimum width' with Field role 'Minimum crop width'. This is a calculated value from class 'Format'.
-an Integer Field 'Minimum height' with Field role 'Minimum crop height'. This is a calculated value from class 'Format'.

Class trigger script on class 'Image':

## If the main image was not modified we do nothing
#if(!$record.isModified('image'))
    ##stop
#end

## Get the original image (full size)
#set($image = $record.getOriginalBlob('Image'))

## Remove previous resized images
#if($record.isEditableRecord())
    #set($resizedImages = $record.getRelevantEditableConnectedTable("Resized image"))
#else
    #set($resizedImages = $record.getConnectedTable("Resized image"))
#end    
$resizedImages.deleteAll()

#if($image)
    ## Get metadata
    #set($dimension = $image.getDimension())
    #if($dimension)
        #set($originalWidth = $dimension.getWidth())
        #set($originalHeight = $dimension.getHeight())
        $record.unconditionalUpdate('width', $!originalWidth)
        $record.unconditionalUpdate('height', $!originalHeight)
    #end
    #set($lengthBytes = $image.length())
    #if($lengthBytes)
        #set($lengthKB = $lengthBytes / 1000)
        $record.unconditionalUpdate('filesize', $lengthKB)
    #end
   
    ## Create resized images
    #set($formats = $session.getTable('format'))
    #foreach($format in $formats)
        #set($height = $format.get('height'))
        #set($width = $format.get('width'))
        #if($height < $originalHeight && $width < $originalWidth)           
            #set($newImage = $image.crop($width, $height))
            #if($newImage)
                #set($resizedImage = $resizedImages.addRecord())
                $resizedImage.put('main image', $record.getSingleKeyValue())
                $resizedImage.put('format', $format.getSingleKeyValue())
                $resizedImage.put('image', $newImage)
                #if(!$record.isEditableRecord())
                    #set($result = $resizedImage.save())
                    $session.addOneTimeInfo("$result")
                #end
            #end
            
        #else
            $session.addOneTimeWarning("The original height and width are smaller than the resized format $height x $width")    
        #end
    #end
   
    ## Save if not editable
    #if(!$record.isEditableRecord())
        $resizedImages.save(false)
    #end  
#end