Learn DooPHP: High performance PHP framework

Upload and Resize Pictures with DooGdImage

First you must have an upload form in your HTML, notice that the file input field in the form below is profile_pic

<form action="/uploadme" method="post" enctype="multipart/form-data" name="upload-photo">
 <input name="profile_pic" type="file" />
 <input type="submit" value="submit"/>
</form>

In Controller, create an instance of DooGdImage, along with the upload/source path and the path to save your resized pictures:

 Doo::loadHelper('DooGdImage');
 //upload/source path, and output saved path
 $gd = new DooGdImage('/var/www/uploaded/', '/var/www/resized_pic/');

Call uploadImage() to save the uploaded file with a new name. The example below save the picture with the date as file name, img_20100104203245.jpg

$uploadImg = $gd->uploadImage('profile_pic', 'img_' .date('Ymdhis'));

Before your resize the picture, you can set the quality, generated image type and file name suffix (optional)

 $gd->generatedQuality = 85;
 $uploadImage->generatedType="jpg";

 //This thumbnail is 46x46 pixels, resize adaptively (perfect 46x46 crop from center)
 //Pic name is img_201001011200_46x46.jpg
 $gd->thumbSuffix = '_46x46';
 $gd->adaptiveResize($uploadImg,46,46);

You can use createThumb/createSquare to resize the pictures too.

 //Resize propotionally (so will not be perfect 75x75 depends on the image ratio, no cropping done)
 //Pic name is img_201001011200_75x75.jpg
 $gd->thumbSuffix = '_75x75';
 $gd->createThumb($uploadImg, 75, 75);

Some updates*

You can validate if the uploaded images meet your requirements by using checkImageType(), checkImageSize() and checkImageExtension()

  • checkImageType() – check if image mime type is in the allowed list. Default: JPEGs, GIFs and PNGs
  • checkImageExtension() – check if image file extension is in the allowed list. Default: jpg, jpeg, gif, png
  • checkImageSize() – check if image file size does not exceed the max file size allowed (KB)
if($gd->checkImageExtension('pfile')){
    $gd->uploadImage('pfile');
}

//or provide your own allowed list
$ext = array('jpg','jpeg','gif','png','bmp','tiff');
if($gd->checkImageExtension('pfile'), $ext){
    $gd->uploadImage('pfile');
}

Related links:

Picture example of images generated by adaptiveResize()
Questions on using DooGdImage.


  • 很好 谢谢

  • $uploadImage->generatedType=”jpg”;
    is false!
    $gd->generatedType=”jpg”;
    is right!

    BTW: ‘profile_pic’ means here the index in $_FILES array (set in HTML form), not a file name or something…
    I prefer to use prefixes (abc.jpg -> thumb_abc.jpg & prev_abc.jpg). It’ easier then a suffix usage (abc_thumb.jpg). You have to know only the original file name: ‘prev_’ and ‘thumb_’ are hard coded in templates!

    But a very nice helper!

  • Thanks alot for this efforts

You can follow any responses to this entry through the RSS 2.0 feed.

Trackbacks / Pingbacks