Reputation: 113
I am trying to save an image generated from html5 canvas into mysql database. I know how to insert the image in base64 format, but I learned that base64 will take 33% more storage space, so I want to save it as either as BLOB or as file, but I'm having trouble with these two methods. I am receiving the base64 string from an ajax method from another page, and use $_POST["image"] to get it. my first attempt is to save the image as blob:
$data = $_POST["image"];
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ','+',$data);
$data = base64_decode($data);
$sql=mysql_query("INSERT INTO capimages(image)VALUES('$data')");
but if I open the table nothing really got inserted.
For saving it as a file path, I don't quite understand how file_put_content or imagepng can save the file in the database, because there is no sql query with insert statement. I tried the following code, but after executing it I cannot find anything in my table:
define('upload_dir', 'images/');
$img = $_POST["image"];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = uploaddir . uniqid() . '.png';
$success = file_put_contents($file, $data);
Can someone show me how to save it to the table either as a BLOB or as a file path after I receive the image in base64 format? Also, does it really matter than base64 format will take 33% more storage space if i'm not expecting a lot of volume for my website?
Upvotes: 1
Views: 21864
Reputation: 109
In general you don't want to store images in a relational database.
But as you want.
here's the code to store a blob using MySQLi(mysqli manual):
first: Create a table to store your images.
CREATE TABLE `test` (
`id` int(11) NOT NULL,
`content` blob NOT NULL
)
then:
<?php
$host = 'localhost';
$user = 'root';
$pass = 'root';
$db_name = 'test';
$base64_data = $_POST['base64_data'];
$link = mysqli_connect($host, $user, $pass, $db_name);
$stmt = mysqli_prepare($link, "INSERT INTO test (id, content) VALUES (?, ?)");
$stmt->bind_param('ib', $id, $content);
$id = 1;
$content = null;
//$base64_data = base64_decode(base64_encode(file_get_contents('3413983627135443.jpg')));
//$stmt->send_long_data(1, $base64_data);
$stmt->send_long_data(1, base64_decode($base64_data));
mysqli_stmt_execute($stmt);
printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));
mysqli_stmt_close($stmt);
Do not use the MySQL (Original)Extensions : intro.mysql
Upvotes: 5