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";
?>
Related
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
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');
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.
I want to make image upload from url for example: http://.. ../logo.png
I need to make formData object from image url but it doesn't work:
HTML:
<form id="form-url">
<input type="text" class="image" id="textarea" placeholder="URL" />
<button>UPLOAD</button>
</form>
Javascript:
$("#form-url").submit(function(e) {
if ($(".image").val() != "URL" && $(".image").val() != "") {
//I also tried this:
var data;
var img = new Image();
img.src = $(".image").val();
img.load = function(){
data = getBase64Image($(".image").val());
};
//but it send undefined
//and this:
var data = URL.createObjectURL($(".image").val()); //dont work
//error: TypeError: Argument 1 is not valid for any of the 1-argument overloads of URL.createObjectURL.
//Upload process working on normal input type file uploading but no on URL image
var formData = new FormData(data);
formData.append("fileToUpload", data);
var xhr = new XMLHttpRequest();
xhr.open('POST', "upload_ajax.php", true);
xhr.onload = function () {
if (xhr.status === 200) {
data = xhr.responseText;
datas = data.split("_");
if (datas[0] != "true") {
alert(data);
} else {
alert('YES');
}
} else {
alerter('An error occurred while uploading this file! Try it again.');
}
};
xhr.send(formData);
} else { alerter("Your file must be an image!"); }
return false;
});
My php script for debug:
<?php
if (isset($_POST)) {
var_dump($_POST);
if (empty($_FILES['fileToUpload']['tmp_name'])) {
echo "Your file must be an image!";
} else {
echo $_FILES['fileToUpload']['name'];
echo $_FILES['fileToUpload']['size'];
}
}
?>
Thanks for all help and your time..
and sorry for my bad english (student)
If getBase64Image is from here, or is similar to it.
Then you are using it wrong. You need to pass it the image node itself. Also the image onload event is async, and as such you have to wait for it to be done to get the data and send it.
var xhr = new XMLHttpRequest();
var formData = new FormData();
xhr.open('POST', "upload_ajax.php", true);
...
var img = new Image();
img.onload = function(){
var data = getBase64Image(this);
formData.append("fileToUpload", data);
xhr.send(formData);
};
Also note on the server side you will need to decode it from the base64 encoding, as it is being sent by string, it is going to be in $_POST not $_FILE
var rawContents = base64_decode($_POST['fileToUpload']);
Note you could also just send the url to the php script and just have php get the image data
var rawContents = file_get_contents($_POST['imageurl']);
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