Chuck Le Butt
Chuck Le Butt

Reputation: 48758

Returning an image as an array

I'm trying to resize an image in PHP if an uploaded image is too big. I've created a function that should resize the file, and then (hopefully) return an array -- except it isn't working :(

private function _resizeImage($image, $width = 780, $height = 780) {

    $imgDetails = GetImageSize($image["tmp_name"]);

    // Content type
    //header("Content-Type: image/jpeg");
    //header("Content-Disposition: attachment; filename=resized-$image");

    // Get dimensions
    $width_orig = $imgDetails['0'];
    $height_orig = $imgDetails['1'];

    $ratio_orig = $width_orig/$height_orig;

    if ($width/$height > $ratio_orig) {
       $width = $height*$ratio_orig;
    } else {
       $height = $width/$ratio_orig;
    }

    // Resample
    switch ( $imgDetails['2'] ) 
    {
      case 1: $newImage = imagecreatefromgif($image["tmp_name"]); break;
      case 2: $newImage = imagecreatefromjpeg($image["tmp_name"]); break;
      case 3: $newImage = imagecreatefrompng($image["tmp_name"]); break;
      default: trigger_error('Unsupported filetype!', E_USER_WARNING);  break;
    }

    if (!$newImage) {
        // We get errors from PHP's ImageCreate functions...
        // So let's echo back the contents of the actual image.
        readfile ($image);
    } else {
        // Create the resized image destination
        $thumb = @ImageCreateTrueColor ($width, $height);
        // Copy from image source, resize it, and paste to image destination
        @ImageCopyResampled ($thumb, $newImage, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
        // Output resized image
        //ImageJPEG ($thumb);
    }

    // Output
    $newFile = imagejpeg($thumb, null, 100);
    return $newFile;
}

Which is called by:

if($imgDetails['0'] > 780 || $imgDetails['1'] < 780) {
    $file = $this->_resizeImage($file); // Resize image if bigger than 780x780
} 

But I'm not getting an object back, and I'm not sure why.

Upvotes: 0

Views: 265

Answers (1)

ozz
ozz

Reputation: 1137

As Seain mentioned in comment, imagejpeg returns a bool value.

bool imagejpeg ( resource $image [, string $filename [, int $quality ]] )

Returns TRUE on success or FALSE on failure.

imagejpeg reference on php.net

Also, you have NULL as the second parameter which will output the image as a raw image stream. If you want to save the image to file somewhere you need to provide a filename for this parameter.

Another note - you should call imagedestroy($newImage); to free up memory you allocated when you created the image from gif/jpeg/png. Do this after you call imagejpeg.

Also I recommend that you not suppress your errors using the @ operator. Instead try logging those errors to the error log. The suppression will make it harder to debug your code and if there is a critical error you suppress it will kill your script entirely with no indication as to why. Error logs help.

Upvotes: 1

Related Questions