I have a table named users and each row (user) has an image.
The image is stored as a BLOB in a mysql database using this code:
$filename = $_FILES['image']['tmp_name'];
$size = getimagesize($filename);
$handle = fopen( $filename , "rb" );
$content = fread( $handle , filesize( $filename ) );
fclose( $handle );
unlink($filename);
$image = base64_encode( $content );
// .... send query to database ....
This worked at first, but as more and more images have to be shown at each page, it gets really loaded, so now I want to create thumbnails, saved in the server’s filesystem, using php GD.
I have the following code but I have no idea what to do in order to read the image from the database so I can create its thumbnail.
$query = "SELECT * FROM users;";
$result = mysql_query( $query );
while( $row = mysql_fetch_array( $result ) ) {
$uploaded_image = base64_decode( $row['image'] );
$size = getimagesize($uploaded_image); <--------------------
$dimension_x = 73;
$dimension_y = 73;
$directory = 'views/images/generated/people/';
do{
$filename = random_32();
$filename = $directory.$filename.'.jpg';
} while( file_exists($filename) );
$image = imagecreatefromjpeg( $uploaded_image );
$thumb = imagecreatetruecolor( $dimension_x , $dimension_y );
$size = getimagesize( $uploaded_image );
imagecopyresampled( $thumb , $image , 0 , 0 , 0 , 0 , $dimension_x , $dimension_y , $size['0'], $size['1']);
imagejpeg( $thumb , $filename , 100);
}
I am trying to find what should I put where the arrow is to make the script work.
All it does now is output
Warning: getimagesize(ÿØÿà): failed to open stream: No such file or directory in /var/www/play/ns4/models/create_thumbs_people.php on line 12
For every entry in the database.
—- EDIT —-
Forgot to mention, random_32() is a function that generates a 32 characters long random string so that the images are named.
And here’s one of the many reasons why storing files in the database is a bad idea…
getimagesize() works on files, not strings. Since you’ve got the raw image in a string, use [imagecreatefromstring()][1], then the imagesx() and imagesy() functions to get the dimensions:
Note that imagecreatefromstring actually has a bit of smarts and can figure out what type the image is, unlike the quite moronic createfromgif/jpg/png/etc… functions, which only work on those particular file types.
[1]: https://www.php.net/imagecreatefromstring