Most of the web developer faces this problem. How to convert HTML into an image and save into the Database with PHP. I also face this problem and I found so many JS Plugins that you can use to convert any type of HTML into an image in HTML5 canvas tag.
What is Canvas tag?
According to the Mozilla Org. canvas is the element which can b used for a graphic with the help of scripting like JavaScript. See the below example of the canvas.
<canvas id="example" width="200" height="200">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
<script>
var example = document.getElementById('example');
var context = example.getContext('2d');
context.fillStyle = 'red';
context.fillRect(30, 30, 50, 50);
</script>
The best plugin to convert HTML into an image is html2canvas. But I found a blurry image bug in this plugin. This bug is resolved by graham73may click here to see detail. Download plugin js file after fixing the blurry image issue from here.
To save the file into the database you need to create a table. Copy paste below code to create a table.
CREATE TABLE `html_to_image` (
`id` int(11) NOT NULL,
`file_name` text NOT NULL,
`file_path` text NOT NULL,
`dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `html_to_image`
ADD PRIMARY KEY (`id`);
ALTER TABLE `html_to_image`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
In this example, we use ajax to send image data to save into sever and database. Consider below code that we use to convert HTML into a canvas. Then send canvas data to a convert.php file to save into DB.
$(document).ready(function(e) {
$("#save").on('click', function(){
$("#preview").html('');
html2canvas($(".well"),{
onrendered: function(canvas){
wmContext = canvas.getContext("2d");
dataURL4 = '';
$("#preview").append(canvas);
var dataURL = canvas.toDataURL("image/png", 0);
$.ajax({
type: 'POST',
url: 'convert.php',
data:{'imgCanvas':dataURL,'saveImage':'ok'},
success: function(data){
var a = data.split('|***|');
if(a[1]==1 || parseInt(a[1])==1){
$('#msg').html(a[0]);
setTimeout(function(){$("#preview").html('');},400);
setTimeout(function(){
location.reload(true);
},2000);
}
}
});
}
});
});
});
Here you can see we use a div with the id of preview that we use to convert HTML into a canvas. You can make it display none. In this example, we show you what HTML you convert into a canvas.
<div class="container">
<h1><a href="https://learncodeweb.com/web-development/php-crud-with-search-and-pagination-in-bootstrap-4/">Convert HTML into the Image and save on server</a></h1>
<div id="msg"></div>
<div class="well bg-info text-center p-3 mb-3">
<p class="m-0"><strong>Click to the convert button</strong></p>
<img src="php.jpg" class="img-thumbnail m-0">
<p class="m-0"><strong>Click to the convert button</strong></p>
</div>
<button type="button" class="btn btn-danger" id="save">Convert</button>
<div id="preview"></div>
</div>
How to save into DB with PHP?
As you know PHP is a server side language. First, we need to develop a connection with the MySql server to perform MYSQL Queries. First, we need to use the POD connection, the code is given below. Download the Database class file from here.
<?php
include_once('Database.php');
define('DB_NAME', 'test');
/** MySQL database username */
define('DB_USER', 'root');
/** MySQL database password */
define('DB_PASSWORD', '');
/** MySQL hostname */
define('DB_HOST', 'localhost');
$dsn = "mysql:dbname=".DB_NAME.";host=".DB_HOST."";
$pdo = "";
try {
$pdo = new PDO($dsn, DB_USER, DB_PASSWORD);
}catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$db = new Database($pdo);
?>
Once the connection is established you can perform actions on MySQL server. In convert.php paste below code that we use to convert canvas into the image and save into Database.
<?php include_once('config.inc.php');
if(isset($_REQUEST['saveImage']) and $_REQUEST['saveImage']!=""){
extract($_REQUEST);
$imageName = rand(0,9999).time();
$mimeType = str_replace("data:image/","",explode(";",$_POST['imgCanvas']));
if(strtolower($mimeType[0])=="png"){
$image = imagecreatefrompng($_POST['imgCanvas']);
imagealphablending($image, false);
imagesavealpha($image, true);
header("Content-Type: image/png");
imagepng($image, 'uploads/'.$imageName.'.'.$mimeType[0]);
}elseif(strtolower($mimeType[0])=="jpeg" || strtolower($mimeType[0])=="jpg"){
$image = imagecreatefromjpeg($_POST['imgCanvas']);
imagealphablending($image, false);
imagesavealpha($image, true);
header("Content-Type: image/jpeg");
imagejpeg($image, 'uploads/'.$imageName.'.'.$mimeType[0]);
}
$data = array(
'file_name'=>$imageName,
'file_path'=>'uploads/'.$imageName,
);
$db->insert('html_to_image',$data);
echo '<div class="alert alert-success"><i class="fa fa-fw fa-thumbs-up"></i> Image updated successfully <strong>Please wait...!</strong></div>|***|1';
}
?>
In the above code snippet, we create an image from data image with the help of PHP and then we save into the Database and on the server.