## Wednesday, September 1, 2010

### Stretching...with Php!!

Hi everybody,

are you sports? Well, so you know for sure the stretching...a programmer too, but he think immediately to pictures' stretching... What is this? Pictures' stretching is a set of operations of elongation, shrinking and many other applied to pictures...Usually you need to fit a picture in a smaller image using mathematical proportions...It works, obvious, but If you try this, you'll note that this image is very distorted! There's nothing to do, the only case where the final pictures looks not distorted is when the big image's dimensions ( width and height ) are multiples of the small picture's ones, but this is not always possible..If you have to create thumbnails with php this is not the right way..Keeping in mind the story of multiple dimensions, let's try to proceed in this other way: first we take the big picture and select an area centered in the image as big as the destination image ( yellow rectangle )..

This area is very small...let's try to multiply by 2 both width and height..We get this:

Quite as big as the image...multiplying now by 3 the area will exceed the image, so we consider the area * 2, an area proportioned to the final pictures...What remains to do? Stretch this area and fit it into our target picture, getting:

Here is the code:

`function makeThumbNotStretched(\$src_file,\$dest_file,\$t,\$win_w,\$win_h){     @list(\$width, \$height, \$type, \$attr) = @getimagesize(\$src_file);     \$cw=\$width/2;      \$ch=\$height/2;      \$i=1;      \$w=\$cw-((\$win_w*\$i)/2);      \$h=\$ch-((\$win_h*\$i)/2);      while(\$w>=0 && \$h>=0){              \$i++;              \$w=\$cw-((\$win_w*\$i)/2);                \$h=\$ch-((\$win_h*\$i)/2);      }      \$i--;      \$w=\$cw-((\$win_w*\$i)/2);      \$h=\$ch-((\$win_h*\$i)/2);      \$dest = imagecreatetruecolor(\$win_w*\$i, \$win_h*\$i);      if (\$t == 'image/jpeg')              \$src = @imagecreatefromjpeg(\$src_file);      imagecopy(\$dest,\$src,0,0,\$w,\$h,\$win_w*\$i,\$win_h*\$i);      \$thumb = imagecreatetruecolor(\$win_w, \$win_h);      imagecopyresampled(\$thumb,\$dest,0,0,0,0,\$win_w,\$win_h,\$win_w*\$i,\$win_h*\$i);      if (\$t == 'image/jpeg')              @imagejpeg(\$thumb,\$dest_file, 75);}`

::See you next post::