Last week I converted my page img src values from pointing at image files to using a PHP script to serve up the images. The primary reason was to accommodate both files and database BLOBs as the actual source.
Now when a user goes to a page, sometimes images show and sometimes not. If not, and the page is refreshed\reloaded, then the image appears. When images do not appear, sometimes it is an image the user has already accessed previously today.
I am stumped.
Here is the img tag:
<img src="../somedir/image_script.php?i=1234">
The image_script.php file figures out where to get the image from, then finishes up with:
header("Content-type: image/jpeg");
if($from_db){
print $image_blob;
} else {
$im = imagecreatefromjpeg($image_file);
imagejpeg($im,null,100);
imagedestroy($im)
}
I am using PHP 5.2.8 on IIS 6 using FastCGI. There are no cache headers on the image_script.php file nor on the directory it is in. Currently 99.9% of the images are file based, so I do not know if there is a difference in result between db-based and file-based images. When I go directly to image_script.php in my browser it returns the requested image (i=????) 100% of the time.
a> Any clue as to why the hit and miss with images being displayed? and,
b> what would be a proper way to actually cache the images served up by the PHP script? (they are very static)
Scott
Hmm. Can't tell for sure, but maybe your imagecreatefromjpeg is occasionally running out of memory? In that case, you'd serve an error message out as JPEG data and never see it, right?
Incidentally, wouldn't just grabbing the image file in as a string and shovelling it out without going through imagecreatefromjpeg/imagejpeg/imagedestroy be more efficient? It looks like you're reading a JPEG file, creating an internal PHP memory image from it, then reconverting it to a JPEG (at hefty 100% quality) then serving that data out, when you could simply read the JPEG file data in and print it, like you do from the database.
What happens if you do, say...
...
} else {
header ('Content-length: ' .filesize($image_file));
readfile ($image_file);
}
Related
I'm uploading an image using WinSCP, which gets sent to a web server using PHP.
Then the site refreshes automatically every X seconds and notices that a new image file is present, and displays it to the user.
However, during the loading time, it shows the following image, which doesn't look very nice:
http://s10.postimg.org/fwz0ok16h/imageupload.png
How can I ensure it only shows the image after it is completely uploaded and ready?
Is there maybe some sort of "pre-loader" or fade effect you could use in PHP that really only shows the picture once it's done? It needs to be PHP because Javascript can't find out the exact image name. Here's how I currently display the image:
foreach($files as $key => $value)
{
if($count >= 1)
break;
echo '<th><img id="image" height="250px" width="250px" src="files/'."$key".'"><br />'."$value".'</img></th>';
$count++;
}
Open the Image using
$png = #imagecreatefrompng('stamp.png');
// Or:
$jpg = #imagecreatefromjpeg('photo.jpeg');
If it doesn't fail, the image is complete. If it fails you either don't have the GD lib installed and enabled or the image is corrupt / incomplete.
But it is the best way to check if the Image upload is complete using Javascript event handlers, like onreadystate attached to the upload, and only refresh the page when that event is triggered.
Further links:
jQuery: Check if image exists
Taking control of image loading
Propably the best one: Is there any way to have PHP detect a corrupted image?
Before outputting a file, check its filemtime. If that modification time is less than a few seconds ago, you can assume that it's still being uploaded and skip over it.
I need to get a image saved on a mysql DB to a folder into the server...
I have the script: watch_pic.php the which get the byte of the image and prints it into a based64 code, I send the Header and the image can be seen on browser, then if I write on the browser 'watch_pic.php?id=1234' it will display and image. I need to copy these image to a folder in the server with any name... I think that using the 'copy' function I could get the image, but it don't works. I can do it using CURL, but I don't wanna like to use this, cause i haven't install it on the server, and could be conflictive with other extras... How can I caopy the image without using CURL??
If you included the code of watch_pic I could give you the exact code to make it work (and if you put it up I can certainly improve this answer). However I can give you a suggestion:
somewhere in that file there will most likely be a line like this:
imagejpeg($img);
(or imagepng or imagegif)
and just change that to something like this:
if (isset($_GET["save"]) {
imagejpeg($img,$_GET["save"]);
}
else {
imagejpeg($img);
}
and call it by image_pic.php?id=####&save=filepathandnametosaveto.jpg
HTH;
Nick
I have a PHP script that takes an images, checks type and filesize, then creates 2 resized copies of the master image, all 3 images are saved to the server. I was under the impression everything worked fine. I was testing out script and on one jpg image I got thrown the error "Content Encoding Error" by firefox. Doing some reading suggested this was a Firefox issue but testing in IE and Chrome resulted in similar errors.
The odd thing is that some .jpg files work, others don't. For those that don't work the error is occurring when the script comes to encode the second resized copy as the master, and first copy are outputted to specified folder. I have checked to see that the image itself isn't corrupt after doing some more reading. The only difference I could note between a .jpg that would allow the script to complete fully and one that wouldn't was that, when viewing the properties of the failing one within Windows it appeared to carry more data, such as camera used to, model number, etc.
Does anyone know what might be causing this error to be thrown?
EDIT
Here's the code I'm using.
$imgsrc = imagecreatefromjpeg($file);
imagecopyresampled($thbout,$imgsrc,0,0,0,0,$thbwid,$thbhei,$width,$height);
imagejpeg($thbout,$thbpath,80);
imagedestroy($thbout);
imagecopyresampled($optout,$imgsrc,0,0,0,0,$optwid,$opthei,$width,$height);
imagejpeg($optout,$optpath,80);
imagedestroy($optout);
Having played about a bit tonight I got it working, by switching the code to this. (Switch to create larger file first)
$imgsrc = imagecreatefromjpeg($file);
imagecopyresampled($optout,$imgsrc,0,0,0,0,$optwid,$opthei,$width,$height);
imagejpeg($optout,$optpath,80);
imagedestroy($optout);
imagecopyresampled($thbout,$imgsrc,0,0,0,0,$thbwid,$thbhei,$width,$height);
imagejpeg($thbout,$thbpath,80);
imagedestroy($thbout);
So I guess my new question becomes, why does it behave like this?
I am trying to display an image from a MySQL blob field. I have tried a few different things and none of them seem to work.
I have tried:
header("Content-type: $type"); img src = $blobData;
header("Content-type: $type"); echo($blobData);
<?php
header("Content-type: $type");
echo $blobData;
?>
This code looks perfectly OK. However, I heard a similar complain from another person and I was able to troubleshoot it by assuring that:
The php script does not output any extra character before or after sending the binary image data.
The php script is saved as a pure ASCII text file, not as a Unicode/UTF-8 encoded file. The Unicode/UTF-8 encoded PHP files might include a signature as the first bytes. These bytes will be invisible in your text editor but server will send these few extra bytes to the browser before the JPEG/GIF/PNG data. The browser will therefore find the wrong signature in the beginning of data. To workaround, create a blank text file in notepad, paste in the php code and save the file in ANSI encoding.
Another option you might consider (assuming you are on Apache):
Create an .htaccess file with a mod_rewrite for all image extensions (png, jpg, gif).
Have it redirect to a php script that looks up the image requested in the DB. If it is there, it echos out the header and BLOG. If it isn't there, it returns a standard 404.
This way you can have:
<img src="adorablepuppy.jpg" />
Which then gets redirected ala:
RewriteEngine on
RewriteRule \.(gif|jpg|png)$ imagelookup.php
This script does a query for the image, which (obviously) assumes that the requested image has a unique key that matches the filename in the URL:
$url = $_SERVER['REQUEST_URI'];
$url_parts = explode("/", $url);
$image_name = array_pop($url_parts);
Now you have just the image filename. Do the query (which I shall leave up to you, along with any validation methods and checks for real files at the address, etc.).
If it comes up with results:
header('Content-type: image/jpeg');
header('Content-Disposition: inline; filename="adorablepuppy.jpg"');
print($image_blog);
otherwise:
header("HTTP/1.0 404 Not Found");
FYI: I have no idea if this would be bad in terms of performance. But it would allow you to do what I think you want, which is output the image as though it were a flat image file on the server using a simple image element. I'm inclined to agree that BLOBs are not the best way to go, but this does avoid any cross-browser issues.
I believe that the issue that you are encountering is an issue with encoding. This resource claims that you can use the print function.
Just get the image from the database. And print it using the correct headers.
$image = mysql_fetch_array(...)
header("Content-type: image/jpeg"); // change it to the right extension
print $image['data'];
For performance reasons... this is not advisable. There are several reasons to put images in databases but the most common are:
a) keeping them indexed (duh!)
You can do this by storing the images flat on the server and just indexing the image filename.
b) keeping the image hidden/protected
Flickr and alike still store the images flat on the server and use a different approach. They generate a URL thats hard to find.
This link points to a protected image on my account. You can still access it once you know the correct URL. Try it!
farm2.static - a farm optimized for delivering static content
1399 - perhaps the server
862145282 - my username
bf83f25865_b - the image
In order to find all my secret images any user can hard hit Flickr with the above address and change the last part. But it would take ages and the user would probably be blocked for hammering the server with thousands of 404s.
That said there is little reason to store images on BLOBs.
Edit:Just a link pointing to someone that explained much better than I did why BLOB is not the way to go when storing images.
I would like to generate a dynamic image from a script, and then have it load to the browser without being persistent on the server.
However, I cannot call this by setting the image's src="script.php", since that would require running the script that just generated the page and its data all over again, just to get the final data that will generate the graph.
Is there a way to do this that is similar to setting image's src="script.php", but which is called from within another script, and just sends the image without saving it? I need access to the data that is used in the generation of the markup, in order to create this dynamic image.
Or, if not, what is the easiest way to destroy the image once the page is loaded? a quick ajax call?
Is there any way to cache certain data for some limited time frame in order for it to be available to some other script?
Any ideas would be greatly appreciated, as I'm having a really hard time finding the right solution to this...
Thanks!
You can inline the image into a <img> tag if you need to.
Like
<?php
$final_image_data; // Your image data, generated by GD
$base64_data = base64_encode($final_image_data);
echo "<img src=\"data:image/png;base64,{$base64_data}\" ... />";
?>
That should work on all modern browsers, and IE8. Doesn't work well with some email clients tho (Outlook, for one).
Also, another solution I found is to store the image in a session variable which is then called from a php script in the image tag. This would allow a user specific image to be served, and then removed from memory by the script... This also avoids messy img src="" tags...
Hopefully that is helpful to someone.
Use a rewrite rule.
RewriteRule ^magicimage.jpg$ /myscript.php
Then simply echo your image data from gd, instead of writing it to disk -- which is as simple as not providing a filename to the appropriate image*() function
myscript.php
<?php
$im = imagecreatetruecolor($w, $h);
//...do gd stuff...
header('Content-type: image/jpeg');
//this outputs the content directly to the browser
//without creating a temporary file or anything
imagejpeg($im);
And finally, utilize the above
display.php
<img src="magicimage.jpg">