Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save imagepng to MySQL database

Tags:

php

mysqli

I have a script that creates an image and calls imagepng to output it to the browser. Instead, I would like to save it to a MySQL database (as a blob). I know how to read a file into a prepared statement

while ($data = fread($fp, 1024)) {
    $size += strlen($data);
    $stmt->send_long_data(0, $data);
}

The problem is that I don't want to have imagepng write to a file just so I can read it back into the database.
Is there an easy way to do that?

UPDATE: Here is how I tried to use output buffering:

ob_start();
imagepng($dst_r,null);
$img = ob_get_clean();

$db = Database::getInstance(); // Singleton on MySQLi
$s = $db->prepare("UPDATE " . $db->getTableName("Users") . " SET `Picture` = ? WHERE `UserID` = ?" );
$s->bind_param('bi', $img, $_POST['UserID']);
$s->send_long_data(0, $img);
$s->execute();

The database is not updated and there are no errors.

like image 685
yakatz Avatar asked Dec 27 '22 03:12

yakatz


1 Answers

From what I've just read in php.net, you can probably do that using a mix of ob_start(), ob_get_contents & ob_end_clean().

By a mix, I mean that:

ob_start();
imagepng($image);
$imageContent = ob_get_contents();
ob_end_clean();

If I were you, I would save it in a temporary file, but do as you wish :)


Edit: I think you also have a problem with the management of your DB. Here is what might works

//include here the thing to get $imageContent

$db = Database::getInstance(); // Singleton on MySQLi
$s = $db->prepare("UPDATE " . $db->getTableName("Users") . " SET `Picture` = ? WHERE `UserID` = ?" );
$null = NULL;
$s->bind_param('bi', $null, $_POST['UserID']);
$byteToSend = 1024;//this should equals the max_allowed_packet variable in your mysql config (usually in my.cnf config file)
$i=0;
while ($contentToSend = substr($imageContent, $i, $byteToSend)) {
    $s->send_long_data(0, $contentToSend);
    $i+=$byteToSend;
}
like image 58
haltabush Avatar answered Dec 29 '22 17:12

haltabush