سؤال

I have a PHP webpage that takes a BLOB from a database and outputs it as an image. When the user uploaded this image I stored the filesize (e.g. 491099) into the database.

When the image is requested through my webpage I add a watermark, set the HTTP HEADERS and output the image through a imagejpeg($img). The problem now is that when my image is fully loaded (takes almost no time) my browser still seems "busy" (loading indicator rotating). When requesting this page through an asynchronous call this makes the loading time long as well, even though the image is actually loaded within no time.

When I simply remove the Content-length header, the image is loaded just like before but now the browser stops right when it's loaded so the process time is really fast.

So it seems like the browser thinks (due to my Content-length header) that it should still be loading something while it's actually not...

Removing the Content-length header is no option since this is required in many browsers I've read.

// set the header for the image
header("Content-length: " . $image->imageSize);    //would be 491099 in my example
header("Content-type: " . $image->imageType);
header('Content-Disposition: inline; filename=" '. $image->imageName . '"');

$watermark          = imagecreatefrompng('../images/watermark.png');
$watermark_width    = imagesx($watermark); 
$watermark_height   = imagesy($watermark);  
$dest_x             = ($image->imageWidth - $watermark_width) / 2;  
$dest_y             = $image->height - $watermark_height - 5;
$img = imagecreatefromstring($image->image);
imagecopymerge($img, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, 55);

imagejpeg($img);

(Note that $image is an object of a custom image class that I created which holds all information regarding an image.)

Anyone has any idea why I am having this behaviour?

Thanks!

هل كانت مفيدة؟

المحلول

Try instead:

ob_start();
imagejpeg($img);

// this should be the real image size
$size = ob_get_length();

header("Content-length: " . $size); 

// send it
ob_flush();

نصائح أخرى

Adding a watermark on top of an unchanged image creates a new image, which will almost certainly have a different filesize, especially if it is a jpeg (lossy compression). As a matter of fact, some image programs and libraries will recompress a jpg even if you make no modifications, resulting in a different file contents (although probably not a visibly different image).

One Trick Pony's answer will get you the correct filesize of your new image with a minimal performance impact.

The other option would be to add the watermark before you save the blob to the DB, but then you lose the ability to render the original.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top