0

I wanted to resize an image in PHP using the GD library.

I found this question, which helped me alot. It allowed me to do exactly what I wanted. I changed the default value to true instead of the false in the answer, and I also added a way to resize png as well.

This resize_image function worked splendidly for all the images, until I wanted to scale down this image to 400x128 (landscape).

This created a black image. I even removed the parts I added on, and used the plain function copied from the question, and it still rendered black. This particular image seems to have trouble with other image sizes such as 400x400 as well. It all works as expected if you disable the crop option.

Is there something wrong with the math included in the function? I tried doing the math on paper replacing variables with the numbers I wanted, but I got confused midway.

PHPfiddle for an example. Try changing the values in the second last line to something else. It partially works (not to scale, even though cropping should be to scale).

Community
  • 1
  • 1
FoxInFlame
  • 480
  • 8
  • 17
  • Which version of PHP? you use this function always passing the url? or just in this case? – Hail Hydra Oct 29 '16 at 15:08
  • @HailHydra 5.4.17. I pass the URL in all cases. The url is working, I think it's just the math. Try changing the values to resize in the fiddle to 500x500 and click run. It kind-of works there. – FoxInFlame Oct 29 '16 at 15:12
  • Ï will post as answer a function that I use to reduce the size and quality of images to see if it help you – Hail Hydra Oct 29 '16 at 15:15
  • @HailHydra I did until a few minutes ago. Not any more. I'm wondering if that function helps me with understanding what the black image is? – FoxInFlame Oct 29 '16 at 15:37

1 Answers1

1

When I debugged it, the width was negative. So, if I changed line 9 to the following

$width = abs(ceil($width-($width*abs($r-$w/$h))));

it's not black anymore. I don't check the formula whether it is correct or not as expected, but that abs() will make your image not black anymore.

elfan
  • 746
  • 4
  • 8
  • Not what I expected (It's supposed to be the same ratio - just cropped on the bottom to make it thinner; it looks stretched using `abs()`). **EDIT** I changed line 9 to `$width = abs(ceil($width-(abs($r-$w/$h))));` and added in a line after that, `$height = $height - abs($h);`, I think it fixed it mostly. – FoxInFlame Oct 29 '16 at 15:45
  • Well, I don't understand what you are trying to accomplish with that crop formula. Maybe it's better if you can create a new question that describes the expected behavior of your resize and crop function? This question is about black image, which is already answered, caused by negative width. – elfan Oct 29 '16 at 15:52
  • 1
    I don't think I'm going to create a new question. You have solved the most important part of my problem, which was the black image. I'll probably figure out somehow on my own. Thank you! – FoxInFlame Oct 29 '16 at 16:02