Running imagecreatefrompng throught image array but array just returns 1 image

266 views Asked by At

I'm trying to crop of the bottom part of an image, which i get from a remote site. Got it also working with the following code:

$u = $xmlString->xpath('//*[contains(@u, "/fds/")]');

foreach($u as $result) {
    $itemLinks = 'http://exampleurl/'.$result['u'].'.png';

    $in_filename = $itemLinks;
    list($width, $height) = getimagesize($in_filename);

    $offset_x = 0;
    $offset_y = 0;
    $new_height = $height - 264;
    $new_width = $width;

    $image = imagecreatefrompng($in_filename);
    $new_image = imagecreatetruecolor($new_width, $new_height);
    imagealphablending($new_image, false);
    imagesavealpha($new_image, true);
    $transparentindex = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
    imagefill($new_image, 0, 0, $transparentindex);
    imagecopy($new_image, $image, 0, 0, $offset_x, $offset_y, $width, $height);

    header("Content-Type: image/png");  
    imagepng($new_image);
}

The only problem with this code is the following:

I'm getting the Image Path from a remote XML file, which i filtered with xpath. So all my finished Image url's are stored in an array. But my code is just generating 1 image which contains the perfect size which i need.

It happens because its just generating 1 img in the end. Maybe also happens because it just returns 1 image with the name img.

Question: Does anyone have a idea why it wouldnt return all images?

For example:

  1. Array contains 15 image links.
  2. Im running my foreach loop through the array.
  3. Foreach loop returns only 1 image.
1

There are 1 answers

0
timclutton On BEST ANSWER

Your issue is caused by the last two lines:

header("Content-Type: image/png");
imagepng($new_image);

This has the same effect as opening a single image file (like a .PNG) in your browser. You can't view multiple image files at the same time unless they are embedded in a HTML page.

If you want to show all fifteen images at once in the browser you'll need to save each image as you process it and then output an HTML file, something like this:

$images = '';
foreach($u as $result) {
    // your existing code...
    imagepng($new_image, './'.$result['u'].'.png');
    $images .= '<img src="'.$result['u'].'.png">';
}

// wrap this in valid HTML syntax (<head>, <body>, etc.)
echo $images;