Simon
Simon

Reputation: 121

PHP GD :image re size with some black rectangles?

I am trying to accomplish this task for 2 days, read various stuffs online but still can't find out what is happen, also read all here at SO about similar problems but nothing.

I have image 400x400 and want to generate 120x120 using php gd. using this code:

                    $image_p = imagecreatetruecolor(120,120);
        $image = imagecreatefromstring($X_IMAGE);
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, 120, 120, 400, 400);
    // RETURN
            header('Content-Type: image/jpeg');
            imagejpeg($image_p, null, 70);
            //destroy...

$X_IMAGE is 400x400 JPG that is stored as string. All images are generated in 120x120 but most of them have some BLACK rectangle at bottom at some pictures it is larger on some it is smaller but 50% of images are with that square. So all are VISIBLE, just some part of image is covered with that black color. What would be solution for my problem? All source images are JPG and also those 120x120 that I need are JPG as you can see...

Upvotes: 0

Views: 373

Answers (1)

lorenzo-s
lorenzo-s

Reputation: 17010

The problem is that your original image is not a square! You pass 400x400 to imagecopyresampled, but the height of the original image maybe is not 400px!

In the image you posted, for example, you have a not-squared original image. When you tell PHP to resample a square on anther image resource, you will resample the image plus a non-existent rectangle at the bottom.

The solution depends on what you want to output.

  • Do you want a scaled image that keeps ratio? For example, from 400x300 to 120x90.
  • Or a scaled image that not keeps ratio? For example, from 400x300 to a distorted 120x120?
  • Or a cropped thumbnail? 400x300 to a 120x120 with left and right parts trimmed out a little?
  • Do you want to replace the black rectangle with a white one, so fill the resampled image in that way?

Upvotes: 3

Related Questions