Using the PHP GD library to resize and save images is HELL

喜欢而已 提交于 2019-12-05 15:45:52

Using PHP's GD extension can truly be a pain. Personally, I would recommend adopting a abstraction library like WideImage. This would simplify your code greatly:

$picture = $_FILES['picture']['name'];

/*original file location*/                  
$file = 'picture/'.$picture;
move_uploaded_file($_FILES["userfile"]["tmp_name"], $picture);

/*save thumbnail location*/
$save = 'thumb/tn-'.$picture;

// Magic Begins Here ......

require "path-to/WideImage.php";

$image = WideImage::load($picture);
$thumb = $image->resizeDown(300, 200, 'inside');

$thumb->saveToFile($save);

Yes, all that code above reduced to four lanes.


A few pointers:

  • Never rely on $_FILES[]['mime']. That's sent by the user-agent and it cannot be trusted.
  • For the same reason, I wouldn't base my file names on $_FILES[]['name'].

Also, your original code doesn't work because you never move_uploaded_file().

user644602

Got better solution, hadling images can be fun actually using the Thumbnailer class.

function callb(& $image) {
   $image->thumbFixed(300,200)->save('/some/location/'.$image->filename);
}

// myFile refers to $_FILES['myFile']
// upload image and handle it
Thumbnailer::upload('myFile', 'callb');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!