Jump to content
Dennis Spohr

API: resize images on upload

Recommended Posts

Hi all,

in the backend of ProcessWire it's possible to define a maximum width and height for images. If you upload an image, it will be resized automatically. I find this feature very handy to safe space. Very often users upload images which are much bigger than needed.

On my application users can upload their images via the frontend. But if you upload images using the API, images won't be resized automatically.

Is there any way to do this?

Currently that's my code:

if ($_FILES['thumbnail']['name'])
	$upload = new WireUpload('thumbnail');
	$upload->setValidExtensions(array('jpg', 'jpeg', 'png'));


	foreach ($upload->execute() as $file)

Thanks very much!


Share this post

Link to post
Share on other sites

I would use the hook that is called on adding the image to the images field. This is called everytime you add a new image, regardless if you do it via API or via Inputfield.

An up to date code example for this hook is here:

In this example you can check for a $p->template->name to match as condition to run different code parts, etc.
To resize the original image itself, you may want to invoke the imagesizer manually.


Instead of the hook, (for your case above), you only may use the manually invoked ImageSizer for each uploaded file *before* you add it to the image field:

    // set the max dimensions
    $targetWidth = 800;
    $targetHeight = 600;

    foreach($upload->execute() as $file) {

        // first get the filename of the *original image* (in case when hooking into file add !!)
        $filenameOrig = $file;

        // set options to not upscale, and set quality to 100%, if this image is a source for variations!!
        $options = array('upscaling' => false, 'quality' => 100, 'sharpening' => 'soft');

        // call the imagesizer
        $imageSizer = new ImageSizer($filenameOrig, $options);
        $success = $imageSizer->resize($targetWidth, $targetHeight); // resize to max dimensions

        if($success) $lesson->video_image->add($filenameOrig);



If you first need to inspect an image, (for conditional processing), you may use the ImageInspector :

    $imageInspector = new ImageInspector();

    foreach($imageFiles as $filename) {
        $result = $imageInspector->inspect($filename);

        // to check if we have a valid result, it must be an array
        if(!is_array($result)) continue;

        // $result['info'] has all relevant data, like width, height, imageType, mime, orientation, rotate, flip, channels, bits, ...
        $width = $result['info']['width']; 
        $height = $result['info']['height'];

        // ...


  • Like 4

Share this post

Link to post
Share on other sites

I just did a test, but unfortunately it doesn't work somehow.

I have the following code:

if ($_FILES['thumbnail']['name'])
	$upload = new WireUpload('thumbnail');
	$upload->setValidExtensions(array('jpg', 'jpeg', 'png'));


	foreach ($upload->execute() as $file)
            $original = $file;
            $options  = array('upscaling' => false, 'quality' => 100);

            $imageSizer = new ImageSizer($original, $options);
            $success    = $imageSizer->resize(500, 500);

            if ($success)

I always get this error:


Error: Exception: no valid filename passed to image inspector (in D:\xampp\htdocs\test\wire\core\ImageSizerEngine.php line 428)


Share this post

Link to post
Share on other sites

Just found the error, adding the path did the trick:

$imageSizer = new ImageSizer($lesson->video_image->path().$original, $options);


  • Like 2

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By EyeDentify
      Hello dear PW gurus.

      I have stumbled over a strange error that i all of sudden got when trying to upload an image to a images field on a page.
      There where images allready stored in the field that i wanted to keep, but during the upload the error apear and after that all images are gone from the field and i can´t upload any, i just get the error every time.
      I am running ProcessWire 3.0.153 dev.
      After looking in the assets folder i find the folder for the page and the image files seems to be there including the ones i tried to upload when the error occured.
      But they don´t show up in the images field in the page editor.
      The error reported:
      SQLSTATE[01000]: Warning: 1265 Data truncated for column 'ratio' at row 1 And here is a screenshot of the event:

      The TracyDebugger Error reporting:

      I hope you fine folks could point me in a direction.
      But it seems our old pal set_time_limit() is back.

      Regards, EyeDentify
    • By quickjeff
      Hi Guys, 
      I have been debugging a site for the last 2 hours and cannot solve the issue. 
      I have a site running on 3.0.148. 
      I installed the Kongondo Blog module and was updating the templates to include the website style. 
      Once everything was set and done, I checked the page tree to see an error appear. 
      Template must be assigned a name before 'filename' can be accessed
      The same error appears in templates. 
      Debugging Steps
      I checked the templates in the server to ensure I didnt accidentally delete the namespace.  Deleted cache in browser and server under assets Still no go. 
      Any help is appreciated. 
    • By Spyros
      I'm having a strange issue with the $page->find(), for some reason I'm missing some of the pages from the results. I found then that I was missing all the pages with the same "PAGE NAME". Is it a bug or am I missing something?
      If I change the "PAGE NAME" of one of the missing ones then I'm retrieving the page without any problem.
      Thank you
    • By rushy
      Hi all
      Continuing my first project where I am creating and manipulating stuff from the frontend. Till now I've always added things like images from the backend, but in this project I need to add and move images from a frontend control. This is a photo album where images are stored in albums, each album being a page containing a Pageimages array in the usual way. So what I want to know is how do I move an image from one album (page) to another in the frontend? I just need some guidance on how to approach this.  I suppose I need to do a copy and delete - but how do I copy an image or images from one page to another? What function should I use to create a new image on an existing page? I include a code snippet from the server side of my delete image request and it works fine. I'd like to implement something similar for a move and upload new image request. 
      Many thanks for any help. Paul 
      <?php namespace ProcessWire; // sanitize inputs as 1-line text $action = $sanitizer->text($input->post('action')); $instr = $sanitizer->text($input->post('input')); $sel = $input->post('selected'); // Expect JSON for image selected image list $selected = json_decode($sel); $nosel = count($selected); $response = array(); // for building JSON response switch($action) { // delete selected images case 'delete': $out = "<p>Deleted $nosel image(s)</p>"; foreach($selected as $item){ $album = $pages->get($item->album); $album->of(false); $out .= "<p>Image {$item->file} from album {$album->title}</p>"; $album->images->delete($item->file); $album->of(true); } $out .= saveUpdatedAlbums($pages, $selected); // add the response message for the delete $response['message'] = $out; break; ...... // save any album that had an image deleted function saveUpdatedAlbums($pages, $selected) { $cur = ''; $out = ''; foreach($selected as $item){ $album = $pages->get($item->album); if($album->id != $cur) { $album->of(false); $album->save('images'); $album->of(true); $cur = $album->id; $out .= "<p>Updated album {$pages->get($cur)->title}</p>"; } } return $out; }  
    • By Robin S
      Inspired by a recent question.
      Image Crop Ratios
      Allows preset aspect ratios to be defined per image field for the ProcessWire image crop tool.
      The module adds a select dropdown to the crop tool. Choose an aspect ratio and the crop area will be fixed to that ratio.

      Install the Image Crop Ratios module.
      Default aspect ratios for all image fields can be defined in the module config. Aspect ratios for specific image fields can be defined on the Input tab of the field settings. You can override the ratio settings in template context if needed. Insert a hyphen as the first item in the ratio settings unless you want to force a ratio to be applied to the crop tool. The hyphen represents a blank option that allows a free crop area to be drawn. Usage
      Click the "Crop" link on the details view of an image thumbnail. Click the "Crop" icon at the top of the editor window. Choose an option from the "Ratio" select dropdown.  
  • Create New...