Image resize PHP [duplicate] Image resize PHP [duplicate] php php

Image resize PHP [duplicate]


imagecopyresized takes an image resource as its second parameter, not a file name. You'll need to load the file first. If you know the file type, you can use imagecreatefromFILETYPE to load it. For example, if it's a JPEG, use imagecreatefromjpeg and pass that the file name - this will return an image resource.

If you don't know the file type, all is not lost. You can read the file in as a string and use imagecreatefromstring (which detects file types automatically) to load it as follows:

$oldImage = imagecreatefromstring(file_get_contents($_FILES['image']['tmp_name']));


$_FILES['image']['tmp_name'] is path not image resource. You have to use one of imagecreatefrom*() functions to create resource.


Here is my implementation of saving a thumbnail picture:

Resize and save function:

function SaveThumbnail($imagePath, $saveAs, $max_x, $max_y) {    ini_set("memory_limit","32M");    $im  = imagecreatefromjpeg ($imagePath);    $x = imagesx($im);    $y = imagesy($im);    if (($max_x/$max_y) < ($x/$y))     {        $save = imagecreatetruecolor($x/($x/$max_x), $y/($x/$max_x));    }    else     {        $save = imagecreatetruecolor($x/($y/$max_y), $y/($y/$max_y));    }    imagecopyresized($save, $im, 0, 0, 0, 0, imagesx($save), imagesy($save), $x, $y);    imagejpeg($save, $saveAs);    imagedestroy($im);    imagedestroy($save);}

Usage:

$thumb_dir = "/path/to/thumbnaildir/"$thumb_name = "thumb.jpg"$muf = move_uploaded_file($_FILES['imgfile']['tmp_name'], "/tmp/test.jpg")if($muf){    SaveThumbnail("/tmp/test.jpg", $thumb_dir . $thumb_name, 128, 128);}