I'm having difficulties saving my canvas. I'm new to javascript so I think it could be a syntax issue.
I've got some vars saved in a function:
var imageView = document.getElementById("imageView");
var canvasData = imageView.toDataURL("image/png");
var postData = "canvasData="+canvasData;
If I add the following line it displays the image correctly:
imgData = $('#i').append($('<img/>', { src : canvasData }));
However, I have another function that I want to pass the base64 code in so I added:
var the_data = "test= "+imageView.toDataURL("image/png");
It does print out a base64 code, but just the blank canvas (not with the drawing the user has added).
If I add the following it doesn't work:
var the_data = "test= "+canvasData;
What am I doing wrong?
This is a basic jsfiddle of what I'm trying to do: http://jsfiddle.net/sMSeX/
Just a little hint from my side for uploading HTML5 canvas image data:
I am working on a project for a print-shop and had some problems due to uploading images to the server that came from an HTML5 canvas element. I was struggling at least for one hour and I did not get it to save the image correctly on my server.
I get the image data as Base64 decoded from the canvas element via
var can = document.getElementsByTagName('canvas');
var dataURL = can[0].toDataURL("image/jpg");
//dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
console.log('data url: '+dataURL);
Once I set the
contentType option of my jQuery ajax call to 'application/x-www-form-url-encoded' :
$.ajax({
url: 'index.php?page=upload-image',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
//data: '{ "imageData" : "' + dataURL + '" }',
data: dataURL,
beforeSend: function() {
$('.text-danger').remove();
},
complete: function() {
},
success: function(json) {
console.log('upload complete');
}
});
everything went the right way and the base64-encoded data was interpreted correctly and successfully saved as an image.
Maybe someone helps that!
Related
I am trying to wire up the ImagesLoader plugin, which allows uploading multiple images. It has a nice drag-n-drop UI but I just can't figure out how to get the images that were uploaded. I cannot find any documentation.
Link to the plugin page: ImagesLoader
Here is the javascript from the demo:
<script type="text/javascript">
// Ready
$(document).ready(function () {
// Create image loader plugin
var imagesloader = $('[data-type=imagesloader]').imagesloader({
minSelect: 3
,imagesToLoad: [{"Url":"./img/Nespresso001.jpg","Name":"Nespresso001"},{"Url":"./img/Nespresso002.jpg","Name":"Nespresso002"}]
});
//Form
$frm = $('#frm');
// Form submit
$frm.submit(function (e) {
var $form = $(this);
var files = imagesloader.data('format.imagesloader').AttachmentArray;
var il = imagesloader.data('format.imagesloader');
if (il.CheckValidity())
alert('Upload ' + files.length + ' files');
e.preventDefault();
e.stopPropagation();
});
});
The images are saved in the object "files". Here is a screen shot of the contents from the inspector:
I tried converting to json and posting, but that only generates an error.
$.ajax({
url: 'process-images.php',
type: 'POST',
data: JSON.stringify(files),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
cache: false,
error: function() {alert("ERROR");},
success: function() {alert("OK");}
});
The rest of the code works just like the demo. Looks like everything needed for the uploaded images is stored in "files". I just need to get the data back to php and I can pull it apart from there. But right now, the original submit code just dies or my addition aborts with an error.
THANKS!
I hope it is not too late to answer.
You just need to loop through the base64 encoded image object, decoding and saving each image to the disk.
// Sample code
foreach(json_decode($request->input('files')) as $file) {
$name = $file->FileName
$imagePath = storage_path('app/public/images/');
file_put_contents($imagePath.$name, base64_decode($file->Base64));
}
I want to take a screenshot of an HTML div tag when the web application is running on the client-side and store the image on the server. I read many articles on html2canvas and tried to implement the code however the image that is getting saved on the server is turning up all black. I tried by setting the background color to white but then it is turning up all white. In short, the image is blank. So any help will be appreciated. Thank you.
Html
<div id="viewer-container" class="sticky-top" style="height:70%;top:25%;width:41%;left:38%;">
<canvas id="viewer-canvas"></canvas>
</div>
Js
html2canvas(document.getElementById("viewer-container"), {
onrendered: function (canvas) {
var image = canvas.toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$.ajax({
type: "POST",
url: '#Url.Action("TakeImage", "Home")',
data: { base64data: image },
success: function (result) { alert(result); }
});
}
})
Controller
[HttpPost]
public ActionResult TakeImage()
{
if (Request.Form["base64data"] != null)
{
string image = Request.Form["base64data"].ToString();
byte[] data = Convert.FromBase64String(image);
var path = Path.Combine(Server.MapPath("~/BIM"), "testimage.png");
System.IO.File.WriteAllBytes(path, data);
}
return View();
}
I am using Cropper.js to send a cropped image to a server, but when I use "convtoblob(blob )" and append blob to formfile then send it to web API, original image Filename miss and according to attached image change to "blob"!
Please help me!
Part of my code is shown below:
canvas.toBlob(function(blobs) {
//blobs.nam = FN;
var formData = new FormData();
formData.append("up", blobs);
$.ajax('http://localhost:51320/api/fileupload/uploadfile', {
method: 'POST',
processData: false,
contentType: false,
data: formData,
cache: false,
success: function(d) {
var d;
$alert.show().addClass('alert-success').text('Upload success');
},
error: function(d) {
var d;
avatar.src = initialAvatarURL;
$alert.show().addClass('alert-warning').text('Upload error');
},
complete: function(d) {
var d;
$progress.hide();
}
});
});
Even when I add a new property as you see "//blobs.nam = FN;" I don't get it in webAPI.
also i have got canvas-toBlob.js but any changes!
please help me!
web api print screen
html page print screen
You can append the formdata like this
formData.append('up', blobs, "blobs.jpg");
Third parameter is your file name.if you want to get your old file name please just read your input type="file" value like this
var yourFileName = $("#ImageFile").val().split('\\').pop(); and change the appending code to
formData.append('up', blobs, yourFileName );
it's tested and working fine.
I am trying to load a previously saved database of the canvas. I get an error "error loadinghttp://flysite.byethost31.com/wp-content/plugins/coderisimo_diagram_constructor/user_images/rqtJkb.jpg" , But only in chrome. In firefox everything is working fine. The picture that the script can not load available. Link correctly. Thank you.
jQuery('body').on('click', '.di-links', function () {
var id = jQuery(this).attr('di-id');
jQuery.ajax({
type: 'POST',
url: base_url,
data: {'diagram_id': id, 'action': 'get_user_diagram'}
}).done(function (json) {
var data = JSON.parse(json);
canvas.loadFromJSON(data.diagram, canvas.renderAll.bind(canvas));//ERROR
jQuery('#diagram-title').val(data.title);
id_loaded_diagram = id;
});
video - https://dl.dropboxusercontent.com/u/19954007/WHY.mp4
Help!!!
I need some help here..
Im trying to save a canvas image after drawing..
following this example (http://www.dotnetfunda.com/articles/article1662-saving-html-5-canvas-as-image-on-the-server-using-aspnet.aspx)
$("#btnSave").click(function () {
var image = document.getElementById("canvas").toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$.ajax({
type: 'POST',
url: "../../Home/UploadImage?imageData=" + image,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved successfully !');
}
});
});
the controller:
public void UploadImage(string imageData)
{
string fileNameWitPath = path + DateTime.Now.ToString().Replace("/", "-").Replace(" ", "- ").Replace(":", "") + ".png";
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
}
}
But when im trying to convert form base64 the string that is passed like parameter in method, throw an error
Invalid length for a character array Base-64.
You can't post data with querystring parameters
Try this;
$("#btnSave").click(function () {
var image = document.getElementById("canvas").toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$.ajax({
type: 'POST',
url: "../../Home/UploadImage",
data: '{ "imageData" : "' + image + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved successfully !');
}
});
});
In that example, the author has posted the image data using a hidden field, notice below line of code in his article
<input type="hidden" name="imageData" id="imageData" />
http://www.dotnetfunda.com/articles/show/2665/saving-html-5-canvas-as-image-in-aspnet-mvc
And on click of the button, he is submitting the form after getting canvas data to the hidden field so follow the same approach. As written by Mehmet, querystring has limitations and its prone to be modified as it goes via url.
Instead of this
image = image.replace('data:image/png;base64,', '');
use this:
image = image.substr(23, image.length);
remove the leading characters up to the first comma (use any dev tool to see what you posted).