Resizing the image file size

Discussions related to customizing hooks. Hooks are documented at http://bigprof.com/appgini/help/advanced-topics/hooks/
Post Reply
nawabp
Posts:12
Joined: 2025-09-13 14:16
Location: India
Contact:

Resizing the image file size

Post by nawabp » 2025-11-07 10:07

The image fields in appgini applications have file size limit, like 500kb or any value you wish. But when we try to upload an image, it is really frustrating to first resize the image to keep it under the limits and then upload. So I just found a workaround for this using java script.

in the hooks/tablename-dv.js we can add the following code:

Code: Select all

$j(function() {
    var fileInput = $j('#imagefield);
    fileInput.on('change', function(e) {
        var file = e.target.files[0];
        if (file && file.type.match('image.*')) {
            // Maximum allowed size in bytes (1MB)
            const MAX_SIZE = 1048576; 
            if (file.size <= MAX_SIZE) {
                return; 
            }
            var reader = new FileReader();

            reader.onload = function(readerEvent) {
                var image = new Image();
                image.onload = function(imageEvent) {
                    var canvas = document.createElement('canvas'),
                        max_width = 1280, // Set maximum desired width
                        max_height = 1024, // Set maximum desired height
                        width = image.width,
                        height = image.height;
                    
                    if (width > height) {
                        if (width > max_width) {
                            height *= max_width / width;
                            width = max_width;
                        }
                    } else {
                        if (height > max_height) {
                            width *= max_height / height;
                            height = max_height;
                        }
                    }
                    
                    canvas.width = width;
                    canvas.height = height;

                    var ctx = canvas.getContext('2d');
                    ctx.drawImage(image, 0, 0, width, height);
                    
                    canvas.toBlob(function(blob) {
                        if (blob.size > MAX_SIZE) {
                             alert('The resized image is still too large. Please choose a smaller image or crop it.');
                             $j('#imagefield').val(''); 
                             return;
                        }
                        
                        var newFile = new File([blob], file.name, {
                            type: blob.type,
                            lastModified: Date.now()
                        });
                        
                        var dataTransfer = new DataTransfer();
                        dataTransfer.items.add(newFile);
                        
                        e.target.files = dataTransfer.files;
                        
                        console.log('Original size:', file.size, 'New size:', newFile.size);

                    }, 'image/jpeg', 0.7); 
                };
                image.src = readerEvent.target.result;
            };
            reader.readAsDataURL(file);
        }
    });
});
next onwards when you upload an image of bigger size, it will automatically reduce to the required file size and then upload.
Note: Ignore the warning and save the record.

saymaad
AppGini Super Hero
AppGini Super Hero
Posts:131
Joined: 2024-06-03 16:17

Re: Resizing the image file size

Post by saymaad » 2025-11-12 10:34

Thanks for sharing and welcome to the community!

nawabp
Posts:12
Joined: 2025-09-13 14:16
Location: India
Contact:

Re: Resizing the image file size

Post by nawabp » 2025-11-13 07:44

saymaad wrote: ↑
2025-11-12 10:34
Thanks for sharing and welcome to the community!
Thank you so much.

artemisia
Veteran Member
Posts:68
Joined: 2013-10-01 15:50

Re: Resizing the image file size

Post by artemisia » 2026-03-06 19:12

I'm trying out this code, AG v.25.15 Inserted to correct hook file for my table (it's the only code in that file).
Modifed one line: const MAX_SIZE = 3145728; (for 3mb)
when I upload an image of 5 mb new inserted image is same size as original. Appears that hook code is silently failing.

Q: are there additional lines in the code that need to be customized?

nawabp
Posts:12
Joined: 2025-09-13 14:16
Location: India
Contact:

Re: Resizing the image file size

Post by nawabp » 2026-04-02 04:16

I am sorry, i saw your post just now.

i have created a file hooks/tablename-dv.js and added code like below

Code: Select all

applyResizing('#field_name', 200, 0.5);
in header-extras.php i have added

Code: Select all

<script src="<?= PREPEND_PATH ?>hooks/abc/image-resizer.js></script> <!--usecase applyResizing(fieldname, maxSizeKB, jpegQuality=0.6) -->
hooks/abc/image-resizer.js has the code:

Code: Select all

function applyResizing(fileInputSelector, maxSizeKB, jpegQuality=0.6) {
    // Convert the limit from Kilobytes (KB) to Bytes
    const MAX_SIZE_BYTES = maxSizeKB * 1024; 
    
    // Set fixed dimensions for optimal resolution/size trade-off
    const max_width = 1280; 
    const max_height = 1024;
    // Set compression quality (0.0 to 1.0, 0.7 is a good balance)
    const jpeg_quality = jpegQuality; 

    $j(function() {
        var fileInput = $j(fileInputSelector);

        fileInput.on('change', function(e) {
            var file = e.target.files[0];

            // Only process files that exist, are images, and are larger than the limit
            if (file && file.type.match('image.*')) {
                
                if (file.size <= MAX_SIZE_BYTES) {
                    console.log(`File ${file.name} is within the limit (${maxSizeKB}KB). Skipping resize.`);
                    return; // No resizing needed
                }

                console.log(`File size (${Math.round(file.size / 1024)}KB) exceeds limit. Starting resize...`);
                
                var reader = new FileReader();

                reader.onload = function(readerEvent) {
                    var image = new Image();
                    image.onload = function(imageEvent) {
                        
                        // *** CANVAS AND RESIZING SETUP ***
                        
                        // 1. Create the canvas element (Fixes ReferenceError)
                        var canvas = document.createElement('canvas'),
                            width = image.width,
                            height = image.height;
                        
                        // 2. Maintain aspect ratio, resizing down if necessary
                        if (width > height) {
                            if (width > max_width) {
                                height *= max_width / width;
                                width = max_width;
                            }
                        } else {
                            if (height > max_height) {
                                width *= max_height / height;
                                height = max_height;
                            }
                        }
                        
                        // 3. Set the canvas dimensions and draw the scaled image
                        canvas.width = width;
                        canvas.height = height;

                        var ctx = canvas.getContext('2d');
                        ctx.drawImage(image, 0, 0, width, height);
                        
                        // *** COMPRESSION AND FILE REPLACEMENT ***

                        // 4. Convert canvas content back to a compressed file (Blob)
                        canvas.toBlob(function(blob) {
                            
                            // Fallback check: if compression/resizing still failed to meet the limit
                            if (blob.size > MAX_SIZE_BYTES) {
                                 alert(`Image failed to compress under the limit of ${maxSizeKB}KB. Current size: ${Math.round(blob.size / 1024)}KB. Please crop or choose a smaller image.`);
                                 $j(fileInputSelector).val(''); // Clear the input
                                 return;
                            }
                            
                            // Create a new File object from the compressed Blob
                            var newFile = new File([blob], file.name, {
                                type: blob.type,
                                lastModified: Date.now()
                            });
                            
                            // Replace the original file in the input field
                            var dataTransfer = new DataTransfer();
                            dataTransfer.items.add(newFile);
                            e.target.files = dataTransfer.files;
                            
                            console.log(`Resize successful! New size: ${Math.round(newFile.size / 1024)}KB`);

                        }, 'image/jpeg', jpeg_quality); // Use specified quality
                    };
                    image.src = readerEvent.target.result;
                };

                reader.readAsDataURL(file);
            }
        });
    });
}

artemisia
Veteran Member
Posts:68
Joined: 2013-10-01 15:50

Re: Resizing the image file size

Post by artemisia » 2026-04-03 02:03

Updated code per your suggestions...I did remove your subdir "abc" inside hooks from 2 places, since I put files just in /hooks. Using parameter of 2000 (~2mb) to pass in function.
Assuming the hash in '#field_name' is just a marker, I left it out in my parameter. For the header-extras code, I see an opening quote, but not a closing one...is that an error?

In test, a 4mb image is not reduced (but successfully uploaded).

I am not well-versed in JS, thanks for your patience.
I will be travelling next couple of weeks but will log in when I can to check for your reply.
~Bob

nawabp
Posts:12
Joined: 2025-09-13 14:16
Location: India
Contact:

Re: Resizing the image file size

Post by nawabp » 2026-04-03 13:46

The hash is required.
It is an identifier. ie., id of the input filed. You know that the input field class is represented by a dot and the input field id is represented by the hash.
Eg. if the filed name is image_1 then the id of the field is #image_1. So the hash is required.


By the way, You are absolutely right about the size, folder abc, and the closing quote required.

like for example if you have many uploads in the table named gallery. The you add the following data to the dv file like below
file: hooks/gallery-dv.js
content:
applyResizing('#featured_image', 2000, 0.9);
applyResizing('#image_1', 1000, 0.7);
applyResizing('#image_2', 200, 0.7);
applyResizing('#image_3', 200, 0.7);
applyResizing('#image_4', 200, 0.7);
applyResizing('#image_5', 200, 0.5);
applyResizing('#image_6', 200, 0.5);
applyResizing('#image_7', 200, 0.5);
applyResizing('#image_8', 200, 0.5);
Last edited by nawabp on 2026-04-03 13:49, edited 1 time in total.

artemisia
Veteran Member
Posts:68
Joined: 2013-10-01 15:50

Re: Resizing the image file size

Post by artemisia » 2026-04-18 19:15

OK - I'll try this again soon.

Post Reply