HTML5 Canvas image upload - uploads blank image or destroyed - javascript

i am using the code bellow to mix two images and upload it to server as a new single image. For this i am using Canvas.
My html code is:
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img1 = loadImage('https://xxxdomain.com/image1.jpg', main);
var img2 = loadImage('https://xxxdomain.com/image2.jpg', main);
var imagesLoaded = 0;
function main() {
imagesLoaded += 1;
if(imagesLoaded == 2) {
// composite now
ctx.drawImage(img1, 0, 0);
ctx.globalAlpha = 0.5;
ctx.drawImage(img2, 0, 0);
}
var myimage = canvas.toDataURL();
var datasendervars = "myimage="+ myimage;
alert(myimage);
$.ajax({
type: "POST",
url: "save.php",
data: datasendervars,
cache: false,
success: function(html){
alert(html);
}
});
}
function loadImage(src, onload) {
var img = new Image();
img.onload = onload;
img.src = src;
return img;
}
<script>
<canvas width="700" height="367" id="canvas"></canvas>
And my upload php script is:
$img = $_POST['myimage'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = 'tester/img'.date("YmdHis").'.png';
if (file_put_contents($file, $data)) {
echo "<p>The canvas was saved as $file.</p>";
} else {
echo "<p>The canvas could not be saved.</p>";
}
Image uploads successful but its blank and all uploaded images are the same filesize.
Any idea?

You are sending the ajax post request incorrectly. It should be ...
$.ajax({
type: "POST",
url: "save.php",
data: {"myimage": myimage},
cache: false,
success: function(html) {
alert(html);
}
});
** also make sure the images are hosted on your local server (same domain)

Related

How to print shipping labels for multiple orders

Converted html content into image format when html page is loaded, But can't able to convert html content into image when it is called from controller.(For convertion we are using HTML2CANVAS)
This is for a Linux server, PHP 7.2 and Codeigniter 3.1.5
We have found solution for load html page using below function:
In Javascript
$.each(data, function(key,value) { //for select multiple datas
var html = escape(value.design);
var orderid = value.orderid;
var label_height = value.label_height;
var label_width = value.label_width;
$(".temp_div").load("<?php echo base_url();?>orders/downloadcavas?design="+html+"&orderid="+orderid+"&label_width="+label_width+"&label_height="+label_height);
});
In Codeigniter
function downloadcavas()
{
$data1['design'] = $design = urldecode($_GET["design"]);
$data1['orderid'] = $orderid = $_GET["orderid"];
$data1['label_width'] = $label_width = $_GET["label_width"];
$data1['label_height'] = $label_height = $_GET["label_height"];
if(isset($label_height))
{
if(isset($label_width))
{
$style = "height:".$label_height."in;width:".$label_width."in;";
}
else
{
$style = "height:".$label_height."in;";
}
}
else
{
$style = "";
}
echo '<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8" /><link rel="stylesheet" href="'.base_url().'js/jquery-ui.css"><link href="'.base_url().'js/lable_design.css" rel="stylesheet" />
<style>
.canvas-section {
background-color: #fff;
}
</style>
</head>
<body>
<div id="divCanvas" class="canvas-section divCanvas" style="'.$style.'margin-top:-70px;" >'.$design.' </div>
<script type="text/javascript" >$("#preloader").hide();
$.getScript("'.base_url().'js/html2canvas.js");
setTimeout(function(){
preview1();
},1000);
function preview1()
{
var element = $(".divCanvas");
var orderid = "'.$orderid.'";
var scaleBy = 5;
var w = 1000;
var h = 1000;
var div = document.querySelector(".divCanvas");
var canvas = document.createElement("canvas");
canvas.width = w * scaleBy;
canvas.height = h * scaleBy;
canvas.style.width = w + "px";
canvas.style.height = h + "px";
var context = canvas.getContext("2d");
context.scale(scaleBy, scaleBy);
html2canvas(div, {
useCORS: true,
canvas:canvas,
onrendered: function (canvas) {
theCanvas = canvas;
var image = theCanvas.toDataURL("image/jpg");
$.ajax({
url: "'.base_url().'template_builder/template/orderimagesave",
data:"canvas="+image+"&orderid="+orderid,
type: "POST",
cache: false,
global: false,
success: function(data){ }});
}
});
} </script>
</body>
</html>';
}
But we cant able to convert images for continuous html content. Can you please suggest anyother method to convert html content into image without loading html page.
Thanks in advance

How to clear downloaded images from cache

How to clear downloaded images from browser cache?
Here is how i assing new src to <img>:
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
imageSrc = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
self.$cameraImg.attr('src', 'data:image/png;base64,' + imageSrc);
};
img.src = '/camera/image/vehicle/' + id + '/code/' + code + '/cam_no/1/';
After many downloads, browsers memory use grow to massive number (> 1gb), after that i get browser crash (Chrome and Firefox).
You should do it from the server side. Thus it depends on what tech you are using there. Here are a lot of ideas how: How to set HTTP headers (for cache-control)?. But do not use HTML meta tag, as it is considered as a bad practice for cache control.
I found solution.
Download image as base64 instead of image and dont use new Image object and canvas.
var xhr = $.ajax({
type: "post",
url: '/camera/image/vehicle/' + self.selected.id + '/code/' + code + '/cam_no/1/',
data: {},
success: function (o) {
if (o) {
if (!o.err) {
self.$cameraImg.attr('src','');
self.$cameraImg.attr('src', 'data:image/png;base64,' + o);
}
}
},
error: function (xhr) {
}
});

How to save canvas as a png in localhost via a php script with the images loaded into the canvas?

I used the following function to add images to the canvas. I used fabric.js to do this.
document.getElementById('imgLoader').onchange = function handleImage(e) {
var reader = new FileReader();
reader.onload = function (event) { console.log('fdsf');
var imgObj = new Image();
imgObj.src = event.target.result;
imgObj.onload = function () {
// start fabricJS stuff
var image = new fabric.Image(imgObj);
image.set({
left: 250,
top: 250,
angle: 0,
padding: 10,
cornersize: 1
});
//image.scale(getRandomNum(0.1, 0.25)).setCoords();
c.add(image);
//context.drawImage(imgObj, 100, 100);
// end fabricJS stuff
}
}
reader.readAsDataURL(e.target.files[0]);
}
By using the above function I can succesfully add images to the canvas. But my problem is when I try to save the canvas as an image, it gives a blank image. I used the below code to convert the canvas to an image.
var canvas = document.getElementById('c'); //Id of the canvas
var dataURL = canvas.toDataURL();
$('#saveMe').click(function() {
$.ajax({
type: "POST",
url: "myscript.php",
data: {
img: dataURL
}
}).done(function(o) {
console.log('saved');
});
myscript.php is as below.
define('UPLOAD_DIR', 'C:/xampp/htdocs/pic/');
chmod(UPLOAD_DIR, 777);
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
Even though I added images to the canvas, when saving, I get only the blank canvas, not getting the image I have loaded into the canvas. Please help me.Thanks in advance.
Use fileSaver.js,its very handy .
You can also see a demo here
http://eligrey.com/demos/FileSaver.js/
Implementation
$(function () {
$("#btnSave").click(function () {
html2canvas($("#widget"), {
onrendered: function (canvas) {
canvas.toBlob(function (blob) {
saveAs(blob, "Dashboard.png");
});
}
});
});
});

imagecreatefromgif() from base64 encoded animated gif in POST

I am trying to make animated GIFs from media streams, videos, or images using the GifShot plugin.
My problem is that the ajax part does not see webcam_image_ajax.php. isn't working. Please do not hate me so the question will be a little longer.
I have to create this ajax function for uploading image:
var pos = 0, ctx = null, saveCB, gif = [];
var createGIFButton = document.createElement("canvas");
createGIFButton.setAttribute('width', 320);
createGIFButton.setAttribute('height', 240);
if (createGIFButton.toDataURL)
{
ctx = createGIFButton.getContext("2d");
gif = ctx.getImageData(0, 0, 320, 240);
saveCB = function(data)
{
var col = data.split(";");
var img = gif;
for(var i = 0; i < 320; i++) {
var tmp = parseInt(col[i]);
img.data[pos + 0] = (tmp >> 16) & 0xff;
img.data[pos + 1] = (tmp >> 8) & 0xff;
img.data[pos + 2] = tmp & 0xff;
img.data[pos + 3] = 0xff;
pos+= 4;
}
if (pos >= 4 * 320 * 240)
{
ctx.putImageData(img, 0, 0);
$.post("webcam_image_ajax.php", {type: "data", gif: createGIFButton.toDataURL("image/gif")},
function(data)
{
if($.trim(data) != "false")
{
var dataString = 'webcam='+ 1;
$.ajax({
type: "POST",
url: $.base_url+"webcam_imageload_ajax.php",
data: dataString,
cache: false,
success: function(html){
var values=$("#uploadvalues").val();
$("#webcam_preview").prepend(html);
var M=$('.webcam_preview').attr('id');
var T= M+','+values;
if(T!='undefinedd,')
$("#uploadvalues").val(T);
}
});
}
else
{
$("#webcam").html('<div id="camera_error"><b>Camera could not connect.</b><br/>Please be sure to make sure your camera is plugged in and in use by another application.</div>');
$("#webcam_status").html("<span style='color:#cc0000'>Camera not found please try again.</span>");
$("#webcam_takesnap").hide();
return false;
}
});
pos = 0;
}
else {
saveCB = function(data) {
gif.push(data);
pos+= 4 * 320;
if (pos >= 4 * 320 * 240)
{
$.post("webcam_image_ajax.php", {type: "pixel", gif: gif.join('|')},
function(data)
{
var dataString = 'webcam='+ 1;
$.ajax({
type: "POST",
url: "webcam_imageload_ajax.php",
data: dataString,
cache: false,
success: function(html){
var values=$("#uploadvalues").val();
$("#webcam_preview").prepend(html);
var M=$('.webcam_preview, .gifshot-image-preview-section').attr('id');
var T= M+','+values;
if(T!='undefined,')
$("#uploadvalues").val(T);
}
});
});
pos = 0;
}
};
}
};
}
$("#webcam").webcam({
width: 320,
height: 240,
mode: "callback",
swffile: "js/jscam_canvas_only.swf",
onSave: saveCB,
onCapture: function ()
{
webcam.save();
},
debug: function (type, string) {
$("#webcam_status").html(type + ": " + string);
}
});
});
/**Taking snap**/
function takeSnap(){
webcam.capture();
}
You can see this code in my ajax function:
$.post("webcam_image_ajax.php", {type: "data", gif: createGIFButton.toDataURL("image/gif")},
the webcam_image_ajax.php is created in base64 format and then it upload the gif image from the images folder.
Also when clicked Create GIF button this JavaScript will starting: CLICK.
After that my ajax code have this line webcam_imageload_ajax.php
<?php
include_once 'includes.php';
if(isSet($_POST['webcam']))
{
$newdata=$Wall->Get_Upload_Image($uid,0);
echo "<img src='uploads/".$newdata['image_path']."' class='webcam_preview gifshot-image-preview-section' id='".$newdata['id']."'/>
";
}
?>
the webcam_imageload_ajax.php working with webcam_image_ajax.php.
If webcam_image_ajax.php created image then webcam_imageload_ajax.php echoing image like:
upload/14202558.gif
But now it looks like:
data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAABE...
creat a gif button:
<button type="button" id="create-gif" class="btn btn-large btn-primary create-gif-button camclick" onclick="return takeSnap();">Create GIF</button>
<input type="hidden" id="webcam_count" />
Forget the JavaScript code in the question.
If you want to use this script then use this code from demo.js inside in gifshot plugin.
function create_gif(data){
$.post(
"webcam_image_ajax.php",
{
data: data,
dataType: 'json'
},
function(js_data)
{
var js_d = $.parseJSON(js_data);
$('#gif_preview').attr('src', js_d.path);
if(js_d.id != 'error'){
$("#uploadvalues").val(js_d.id);
$('.webcam_preview, .gifshot-image-preview-section').attr('id', js_d.id);
}
}
);
}
and you can write your own php code for webcam_image_ajax.php.
Simply do like this:
file_put_contents('filename',file_get_contents(str_replace('data:','data://','<your base64 encoded data>')));
This is simply adapting your data:... into the data:// wrapper.
There is no simpler way to do this.
Notice that this is HIGHLY UNSECURE and you should validate the data (using preg_match for example) before usage.

When calling canvas.toDataURL, why is the part from rasterizeHTML.drawHTML black?

I have a button and when it is pressed it calls common_save_project(). What happens right now is the canvas is produced correctly on the screen, but the image that is created by canvas.toDataURL is black where rasterizeHTML.drawHTML was called. I am using http://cburgmer.github.io/rasterizeHTML.js/.
Here is the relevant code:
function common_save_project()
{
var image = common_screenshot();
$.ajax
(
{
type: "POST",
processData: false,
url: SITE_URL + "/system/xml/import/" + app_type + "/" + session_id + "/?prjid=" + project_id,
data: "xml=" + common_order_xml + "&prodid=" + product_id + "&file=" + image.src
}
).done(function( msg )
{
console.log("Project saved. " + msg);
});
}
function common_screenshot()
{
var canvas = document.getElementById("save_image_canvas");
var ctx = canvas.getContext('2d');
if (typeof(moulding_canvas) === "undefined")
{
canvas.height = parseInt($("#matte_canvas").height());
canvas.width = parseInt($("#matte_canvas").width());
}
else
{
canvas.height = parseInt($("#moulding_canvas").height());
canvas.width = parseInt($("#moulding_canvas").width());
}
canvas.style.backgroundColor = "#FFFFFF";
var moulding_top = 0;
var moulding_left = 0;
if (document.getElementById("moulding_canvas"))
{
moulding_top = -1 * parseInt(document.getElementById("moulding_canvas").style.top);
moulding_left = -1 * parseInt(document.getElementById("moulding_canvas").style.left);
}
var mattes_html = document.getElementById("mattes").innerHTML;
mattes_html = mattes_html.replace(/<\/?script\b.*?>/g, "");
mattes_html = mattes_html.replace(/ on\w+=".*?"/g, "");
rasterizeHTML.drawHTML(mattes_html).then(function (renderResult)
{
ctx.drawImage(renderResult.image, moulding_left, moulding_top);
});
ctx.drawImage(matte_canvas, moulding_left, moulding_top);
if (typeof(moulding_canvas) !== "undefined")
{
ctx.drawImage(moulding_canvas, 0, 0);
}
var image = new Image();
image.src = canvas.toDataURL("image/jpeg");
return image;
}
Original:
After rasterizeHTML.drawHTML:
Final result (after canvas.toDataURL):
It will work fine if you will re-declare the canvas again for saving.
Try this:
<script type="text/javascript">
var canvas = document.getElementById("canvas");
rasterizeHTML.drawHTML('<h1>hello Im here</h1>Some <span style="color: green; font-size: 20px;">HTML</span>', canvas);
$('#saveImg').click(function(){
var canvas = document.getElementById("canvas");
var dataURL = canvas.toDataURL("image/png");
window.open(dataURL, "toDataURL() image", "width=600, height=200");
});
</script>

Categories

Resources