Edit: just finished using Image Magick and fixed it.
In short, I'm trying to extract some basic school series information from Wikipedia using a combination of PHP and jQuery. Part of this information is the school’s emblem or logo, which is fairly easy to find in the list of items.
The problem is trying to make some adjustments to the image in PHP. I know that the image exists on the destination URL (which is in a different domain if that helps someone), and that it is the one I want, but some images look like this:

This is the original image:

Others, of all file types, look great.
The code for this part is as follows:
$ext = end(explode('.', $image));
if($ext == 'png') {
$img = imagecreatefrompng($image);
}
else if($ext == 'jpeg' || $ext == 'jpg') {
$img = imagecreatefromjpeg($image);
}
else if($ext == 'gif') {
$img = imagecreatefromgif($image);
}
else $img = false;
if($img) {
$raw_x = imagesx($img);
$raw_y = imagesy($img);
if($raw_x > $raw_y && $raw_x > 500)
{
$y = (500 / $raw_x) * $raw_y;
$tmp_img = imagecreatetruecolor(500, $y);
$white = imagecolorallocate($tmp_img, 255, 255, 255);
imagefill($tmp_img, 0, 0, $white);
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, 500, $y, $raw_x, $raw_y);
$img = $tmp_img;
}
else if($raw_y > 500)
{
$x = (500 / $raw_y) * $raw_x;
$tmp_img = imagecreatetruecolor($x, 500);
$white = imagecolorallocate($tmp_img, 255, 255, 255);
imagefill($tmp_img, 0, 0, $white);
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $x, 500, $raw_x, $raw_y);
$img = $tmp_img;
}
if(!file_exists("../images/schools/" . $id)) mkdir("../images/schools/" . $id, 0755, true);
imagejpeg($img, "../images/schools/" . $id . "/photo.jpg", 100);
}
, , , , -,