Posts Tagged ‘image’

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.
More »