|
Posted by Andy Hassall on 08/18/05 02:35
On 17 Aug 2005 16:12:06 -0700, bissatch@yahoo.co.uk wrote:
>> MySQL can store binary data directly using the *BLOB types, which would avoid
>> the 33% size increase plus processing that you are incurring by base64 encoding
>> it.
>
>I was aware that my above method gave a 33% increase but I was just
>wanting to accomplish uploading, storing and outputing at this stage.
OK, fair enough.
>Anyway, going on your advice above I have tried the following code when
>the image is uploaded:
>
>$tmpfiletype = $_FILES['imgfile']['type'];
>switch ($tmpfiletype)
>{
>case "image/jpeg":
>case "image/pjpeg":
> $img = imagecreatefromjpeg($tmpfilename);
> break;
>case "image/gif":
> $img = imagecreatefromgif($tmpfilename);
> break;
>case "image/png":
> $img = imagecreatefrompng($tmpfilename);
> break;
>}
>
So $img is a resource handle here.
>//write to db
>$insert = "INSERT INTO imgblob (imgid, imgdata, imgtype) VALUES (null,
>'" . $img . "', '" . $imgtype . "')";
You don't want to write the string representation of a resource handle into
the database - it won't mean much. Also you want some escaping here - more so
since it'll be binary data now.
>$result = mysql_query($insert, $db);
>if ($result) {
> echo "<p>Result!</p>";
>}else{
> echo "<p>No, no, no ... it didnt work</p>";
The dreaded "doesn't work" message :-( Make it more helpful with
mysql_error().
>Unfortetely, I am getting the 'No, no, no ... it didnt work' output
>that indicates that it wasnt able to write the image to the database. I
>am guessing that I need to do something with $img before I can use it
>in the INSERT query. What do I need to do with $img to let me INSERT it
>if this is the case?
>
>Note: I have created a table called imgblob with a imgdata with type
>'blob' instead of 'text' for use here
Similar to the bit where you did imagejpeg to a temporary file, but instead
wrap it in buffering. This is just typed without testing:
ob_start();
imagejpeg($img, '', 80);
$imgdata = ob_get_contents();
ob_end_clean();
$insert = sprintf(
"INSERT INTO imgblob (imgid, imgdata, imgtype)
VALUES (null, '%s', '%s'),
mysql_real_escape_string($imgdata),
mysql_real_escape_string($imgtype),
);
Then go ahead and run the query.
You might also want a bigger datatype like MEDIUMBLOB or LONGBLOB.
--
Andy Hassall / <andy@andyh.co.uk> / <http://www.andyh.co.uk>
<http://www.andyhsoftware.co.uk/space> Space: disk usage analysis tool
Navigation:
[Reply to this message]
|