I’m taking a linked image, and making my own resized versions of them using the imagecopyresampled().
When trying to show GD library resampled images, those below a certain size (around 160px width) show up only as a bunch of gibberish (ex: ‘����JFIF��>CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), default quality ��C’).
I checked the images themselves, and they were stored fine and show up correctly when opened in a picture viewer. However, printing them to browser just doesn’t work. When I change the pixel size to a larger pixel size, it works fine.
I’m showing the images in the browser like this
$handle = fopen($fileName, "rb");
$img = fread($handle, filesize($fileName));
fclose($handle);
$imgSize = strlen($img);
$image_type = exif_imagetype($fileName);
header('Content-Type: image/JPEG');
header('Content-Transfer-Encoding: binary');
header("Content-Length: $imgSize");
print $img;
return true;
Right now I’m starting to believe it’s something to do with the GD library. Anyone else have any further insight into this?
Thanks.
EDIT:
One of Brad’s suggestions showed me the right way. As usual, it was a completely boneheaded mistake. I can’t answer my own question yet so I figured I’d make an edit instead.
What I forgot to include in my initial description, was that the previous code was all in one of my models, and I then called a function to show the image in my controller.
I’d recently switched to Symfony2, and have been using the Response return pretty much everywhere in my controllers. However, I’d been reusing my old show image code, which had been written without Symfony. I had a “show image” type of function, which I called in my controller and then returned an empty Response. Thus, Symfony’s Response return messed up the encoding. Advanced browsers were able to auto correct for large images, but not for small ones.
My final solution became
In my model
$handle = fopen($fileName, "rb");
$image= fread($handle, filesize($fileName));
fclose($handle);
$image_type = exif_imagetype($fileName);
In my controller
return new Response($image, 200, array('Content-Type' => $image_type));
What you are seeing is the raw image data, which means the browser is, for some reason, not registering the content type.
What I suspect is happening is that whatever browser you are testing with is case-sensitive to the
Content-Typeheader value.Change
image/JPEGtoimage/jpeg, and see if that works for you.As for an explanation of why it works with larger images… It is likely that the
Content-Typeis never being recognized as a known type. Browsers will look at the actual content they received, to try to figure out what type it is. There is probably something in its content sniffing function that looks at small lengths and says, “Nope, probably not an image”, and moves on.