I cannot get PHP GD image resizing scripts to work

45 views Asked by At

I have watched many videos about resizing images with PHP and GD and I have cut-and-pasted much code that I'm told will do the job, and yet I can never get image scripts to resize or even display images. They simply fail to work for me. Since I'm following all the advice without results, I feel like there's something basic about working with images in this way that I'm missing, despite my 20-plus years of experience with php coding.

Below is the latest script that I have tried without success. I wrote this one down step by step as it was explained to me on a website. I thought I understood everything that was going on, but the script does not resize any images for me. The page just "breaks" when I try to load it, returning a broken-image icon. (I have verified that the image $file_name exists at the supplied subdirectory.)

ADDITIONAL INFO: I am on an Apache Unix shared hosting platform. About 10 years ago, I did get a script or two to actually work (after many attempts) using the GD library and my hosting setup has not changed since. I think in that case, the fix involved getting rid of white spaces in the code in front of the content header -- although most tutorials I watch about PHP images never even mention a content header.

  <?php
header('Content-Type: image/png');
 
 $dimension="400";
 $file_name="pics/10.png";
 $image_size=getimagesize($file_name);
 $width=$image_size[0];
 $height=$image_height[1];
 $ratio=$width/$height;
 if ($ratio>1) {
     
     $new_width=$dimension;
     $new_height=$dimension/$ratio;
 } else {
     
     $new_height=$dimension;
     $new_width=$dimension*$ratio;
     
 }
 
 $src=imagecreatefromstring($file_name);
 $destination=imagecreatetruecolor($new_width,$new_height);
 imagecopyresampled($destination,$src,0,0,0,0,$new_width,$new_height,$width, $height);
 imagepng($destination,$file_name);
 
 imagedestroy($src);
 imagedestroy($destination);
 
 ?>
1

There are 1 answers

1
chiliNUT On

imagecreatefromstring takes a string of image data, not a file path

imagecreatefromstring(string $data): GdImage|false

Parameters ΒΆ

data
A string containing the image data.

get a string of the image data

$data = file_get_contents($file_name)
$src = imagecreatefromstring($data);