Javascript - How do i submit a canvas in a form? - javascript

Basically my problem is that i have a canvas and i want to use the canvas in a form like if it were an image submitted in a input with a type of file, so i can access the $_FILES array..
The project i have made is an image cropping script where a user chose an image file through input type file, and then the script draw the image onto a canvas, then the user can zoom/crop the image... that all works perfectly fine..
But how can i send the cropped image to a php file as form file input data and access the $_FILES super global array?
I really hope someone can help
This link here tries to do something similar to me but i dont understand how it works, or how i could do the same with my project?
Javascript
function convertCanvasToImage() {
var temp_ctx, temp_canvas;
temp_canvas = document.createElement('canvas');
temp_ctx = temp_canvas.getContext('2d');
temp_canvas.width = windowWidth;
temp_canvas.height = windowWidth;
temp_ctx.drawImage(ctx.canvas, cutoutWidth, cutoutWidth, windowWidth, windowWidth, 0, 0, windowWidth, windowWidth);
var dataurl = temp_canvas.toDataURL("image/jpeg");
croppedImage.src = dataurl;
contentCall(dataurl);
}
function contentCall(profileImage) {
var http = new XMLHttpRequest();
var url = "ajax.php";
var params = "profileImage=" + profileImage;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
alert(this.responseText);
}
};
http.send(params);
}
document.getElementById("myfiles").addEventListener("change", pullFiles, false);
document.getElementById("scaleSlider").addEventListener("input", updateScale, false);
document.getElementById("convert").addEventListener("click", convertCanvasToImage, false);
UPDATE
I managed to solve the problem myself
var multiPart = new FormData();
var fileName = "pernille";
multiPart.append('retard', 'christian');
temp_canvas.toBlob(function(blob){
multiPart.append('blobTest', blob, fileName);
contentCall(multiPart);
}, "image/jpg");
}
function contentCall(profileImage) {
var http = new XMLHttpRequest();
var url = "ajax.php";
http.open("POST", url, true);
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
alert(this.responseText);
}
};
http.send(profileImage);
}

You'll need to store the canvas (as an image) in a hidden form field as its value and then when you submit your form, the image will be submitted.
// Save canvas as dataURL image
var dataURL = canvas.toDataURL('image/png');

Related

How to convert a Canvas image to a Buffered Image for Servlet Processing?

I need to send a HTML-Canvas image from a Webpage to a Servlet for Image Processing. On my webpage, this will be done by uploading a jpg or png image and then clicking a process button.
My frontend is working (I can upload and display images), but I do not know how to send an image from a webpage to a server and vice-versa.
Can you please help me?
HTML: (img stored in canvas)
<canvas id="canvas"></canvas>
JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Ajax Code here???
}
};
xhttp.open("GET", ?, true);
xhttp.send();
Unfortunately, not all browsers does support Canvas.toBlob() function. For example MS Edge and other browsers does not support it (see browser compatibility). Because of this we have to use Canvas.toDataURL() function.
I wrote for you the solution which does the same like normal sending a form from HTML:
var canvas = document.getElementById('canvas'),
dataURL = canvas.toDataURL('image/jpeg', 0.7), //or canvas.toDataURL('image/png');
blob = dataURItoBlob(dataURL),
formData = new FormData(),
xhr = new XMLHttpRequest();
//We append the data to a form such that it will be uploaded as a file:
formData.append('canvasImage', blob);
//'canvasImage' is a form field name like in (see comment below).
xhr.open('POST', 'jsp-file-on-your-server.jsp');
xhr.send(formData);
//This is the same like sending with normal form:
//<form method="post" action="jsp-file-on-your-server.jsp" enctype="multipart/form-data">
// <input type="file" name="canvasImage"/>
//</form>
function dataURItoBlob(dataURI)
{
var aDataURIparts = dataURI.split(','),
binary = atob(aDataURIparts[1]),
mime = aDataURIparts[0].match(/:(.*?);/)[1],
array = [],
n = binary.length,
u8arr = new Uint8Array(n);
while(n--)
u8arr[n] = binary.charCodeAt(n);
return new Blob([u8arr], {type: mime})
}
If you do not know how to save files on server side using JSP, please read:
How to upload files on server folder using JSP
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var canvas = document.getElementById('canvas');
canvas.toBlob(function(blob) {
var oReq = new XMLHttpRequest();
oReq.open("POST", /*URL*/, true);
oReq.onload = function (oEvent) {
// Uploaded.
};
oReq.send(blob);
},'image/jpeg', 0.95);
}
};
xhttp.open("GET", ?, true);
xhttp.send();
More information:CanvasElement toBlob and Sending Blob

Image src not updating after setRequestHeader call

I have two AJAX functions: one for an image file upload, one for a form info upload.
File Upload
function uploadFile(insertNodeID, inputFileID){
var img = document.getElementById(inputFileID).files[0];
var form_data = new FormData();
form_data.append('file[]', img, img.name);
var objXML = new XMLHttpRequest();
objXML.onprogress = updateProgress;
objXML.onload = function() {
if(objXML.readyState==4 && objXML.status==200) {
if(objXML.responseText !== 'no'){
document.getElementById(insertNodeID).src = objXML.responseText;
}
else{
errorInOut('There was a problem uploading the file.');
}
}
};
objXML.open('POST', baseURL+'ajax/admin_fileupload/', true);
objXML.send(form_data);
Form Info Upload
function uploadFormInfo(strURL, strData, type) {
strURL = baseURL+'ajax/'+strURL+'/';
var objXML = new XMLHttpRequest();
objXML.onreadystatechange = function() {
if (objXML.readyState == 4 && objXML.status == 200) {
returnXML(objXML.responseText, type);
}
};
objXML.open("POST", strURL, true);
objXML.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
objXML.send(strData);
They both work perfect independently.
The issue I'm running into is when I call the uploadFormInfo(), then call uploadFile(), the document.getElementById(insertNodeID).src does not render the uploaded image. It still uploads the image to the server and the responseText is the correct path to the image. I did a console.log on the .src of the id AFTER the I plugged in the new image and the .src is correct BUT, it never changes in the elements tab in Chome inspect. It also works fine BEFORE I call uploadFormInfo().
I've tried and number of things (sending a separate request header for the uploadFile) and nothing works.
I'm stumped.

Pass Base64 with POST Request

I am using javascript and I get a image file and encode it to base 64 like this
function el(id){return document.getElementById(id);} // Get elem by ID
function readImage() {
if ( this.files && this.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
el("img").src = e.target.result;
el("base").innerHTML = e.target.result;
};
FR.readAsDataURL( this.files[0] );
}
}
el("asd").addEventListener("change", readImage, false);
Where the encoded text is this and looks like this
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gxYSUNDX1BST0ZJTE.........
And now I want to send this data with a post which I know how to do, but when I read the data I sent on the other side I just see data:image/jpeg, where does the Base64 encoded start and how can I just pass that as a string?
I make the post like this
var base64data;
//base64data is declared in the function readImage and I log it in this one and it has data
function callHttpReq () {
var http = new XMLHttpRequest();
var url = "/admin/website_sql/save_info.py";
var params = "website_photo=" + base64data;
http.open("POST", url, true);
console.log(base64data);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
}
http.send(params);
Thanks

How to get image using XMLHttpRequest in javascript

I need to show a image which is generating in another page. I am using XMLHttpRequest to get the image from that page. Not able to do this please help.
Code Block
This is used to get image
Bitmap IMG = myPane.GetImage(700,700,92);
//Bitmap finalImage = new Bitmap(800, 800);
byte[] byteArray = new byte[0];
using (MemoryStream stream = new MemoryStream())
{
IMG.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
}
Response.Write(byteArray);
This is used to fetch that in javascript
function b() {
searchReq.onreadystatechange = ProcessResponse;
searchReq.open("GET", 'Default.aspx', true);
if (searchReq.overrideMimeType) {
searchReq.overrideMimeType('text/plain; charset=x-user-defined');
} else {
searchReq.setRequestHeader('Accept-Charset', 'x-user-defined');
}
searchReq.send(null);
}
function ProcessResponse() {
if (searchReq.readyState == 4) {
if (searchReq.status == 200) {
retval = "";
var img = document.getElementById("myimg");
img.src = "data:image/jpeg;base64," +(searchReq.responseText);
}
}
}
Thanks
Don't use XMLHttpRequest. Instead, just set the src of the img element to your .net script:
function b() {
var img = document.getElementById("myimg");
img.src = "Default.aspx";
}
If this doesn't work because the browser thinks it's the same image file just add some junk query param to the url:
img.src = "Default.aspx?q=" + Math.random();
Image is a binary data and you have to modify some attributes of your XmlHttpRequest object in order to process binary data.
Mozilla's website has a good documentation about this subject here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data
A code snippet from the above page does this:
var oReq = new XMLHttpRequest();
oReq.open("GET", "/myfile.png", true);
oReq.responseType = "blob";
oReq.onload = function(oEvent) {
var blob = oReq.response;
// ...
};
oReq.send();
You don't need to use XMLHttpRequest to retrieve your image. It can easily achieved by placing <img> tag like this:
<img src="myImageGenerator.aspx" alt="..." />
I'm assuming your script is on myImageGenerator.aspx page
Please note that myImageGenerator.aspx need to return the correct content type: image/png
You can do this in C#:
Response.Headers["Content-Type"] = "image/png";
Good luck

Renaming an image created from an HTML5 canvas

I have made a simple canvas and save it as an image. I have done this with the help of this code:
var canvas = document.getElementById("mycanvas");
var img = canvas.toDataURL("image/png");
and pop up the created image with this:
document.write('<img src="'+img+'"/>');
But its name is always a weird one. I want to rename the image name like faizan.jpg etc. How can I do this?
To put it simply, you can't. When you call the toDataURL method on an HTMLCanvasElement it generates a string representation of the image as a Data URL. Thus if you try to save the image, the browser gives it a default filename (e.g. Opera saves it as default.png if the Data URL was a png file).
Many workarounds exist. The simplest one is to make an AJAX call to a server, save the image on the server-side and return the URL of the saved image which can then be accessed and saved on the client-side:
function saveDataURL(canvas) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
window.location.href = request.responseText;
}
};
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.open("POST", "saveDataURL.php", true);
request.send("dataURL=" + canvas.toDataURL());
}
To save the image on the server side, use the following PHP script:
$dataURL = $_POST["dataURL"];
$encodedData = explode(',', $dataURL)[1];
$decodedData = base64_decode($encodedData);
file_put_contents("images/faizan.png", $decodedData);
echo "http://example.com/images/faizan.png";
Got this working 100%! Just had to do a little debugging to the above answer. Here's the working code:
The JavaScript:
var saveDataURL = function(canvas) {
var dataURL = document.getElementById(canvas).toDataURL();
var params = "dataURL=" + encodeURIComponent(dataURL);
var request = new XMLHttpRequest();
request.open("POST", "/save-data-url.php", true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
window.console.log(dataURL);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
window.console.log(request.responseText);
}
};
request.send(params);
}
/scripts/save-data-url.php:
<?php
$dataURL = $_POST["dataURL"];
$encodedData = explode(',', $dataURL);
$encodedData = $encodedData[1];
$decodedData = base64_decode($encodedData);
file_put_contents("images/log.txt", $encodedData);
file_put_contents("images/test.png", $decodedData);
echo "http://www.mywebsite.com/images/test.png";
?>

Categories

Resources