Trying to crop image and send canvas as an image to server but original image is sent to server.
Code used is as follows:
<script type="text/javascript">
var crop_max_width = 400;
var crop_max_height = 400;
var jcrop_api;
var canvas;
var context;
var image;
var prefsize;
$("#file").change(function() {
console.log("1");
loadImage(this);
});
function loadImage(input) {
if (input.files && input.files[0]) {
console.log("2");
var reader = new FileReader();
canvas = null;
reader.onload = function(e) {
console.log("3");
image = new Image();
image.onload = validateImage;
/* $("image").on("load",function() {image.src = e.target.result;}); */
image.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
}
function dataURLtoBlob(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
console.log("4");
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {
type: contentType
});
}
console.log("4 else");
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
}
function validateImage() {
if (canvas != null) {
console.log("5");
image = new Image();
image.onload = restartJcrop;
image.src = canvas.toDataURL('image/png');
} else restartJcrop();
}
function restartJcrop() {
if (jcrop_api != null) {
console.log("6");
jcrop_api.destroy();
}
console.log("7");
$("#views").empty();
$("#views").append("<canvas id=\"canvas\">");
canvas = $("#canvas")[0];
context = canvas.getContext("2d");
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
$("#canvas").Jcrop({
onSelect: selectcanvas,
onRelease: clearcanvas,
boxWidth: crop_max_width,
boxHeight: crop_max_height
}, function() {
console.log("8");
jcrop_api = this;
});
clearcanvas();
}
function clearcanvas() {
console.log("9");
prefsize = {
x: 0,
y: 0,
w: canvas.width,
h: canvas.height,
};
}
function selectcanvas(coords) {
console.log("10");
prefsize = {
x: Math.round(coords.x),
y: Math.round(coords.y),
w: Math.round(coords.w),
h: Math.round(coords.h)
};
}
function applyCrop() {
console.log("11");
canvas.width = prefsize.w;
canvas.height = prefsize.h;
context.drawImage(image, prefsize.x, prefsize.y, prefsize.w, prefsize.h, 0, 0, canvas.width, canvas.height);
validateImage();
}
$("#cropbutton").click(function(e) {
console.log("12");
applyCrop();
});
$("#form").submit(function(e) {
console.log("form clicked for image");
e.preventDefault();
formData = new FormData($(this)[0]);
var blob = dataURLtoBlob(canvas.toDataURL("image/png"));
//---Add file blob to the form data
formData.append("file", blob);
$.ajax({
url: "/uploadImages/",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log("Successfully uploaded");
location.href = "${pageContext.request.contextPath}/myPage/"
},
error: function(data) {
alert("Error");
},
complete: function(data) {}
});
});
</script>
I want to send canvas as an image to server but original image is sent to server.
Related
I want to upload cropped image to server. For this I am using jQuery Jcrop lib in this canvas image cropped then convert to blob that is working perfectly , but the problem is that file name on server is just blob without any extension or undefined type.
When I am using this in img Sec on web page it's working perfectly.
<script>
function uploadPhoto(thisVar) {
if($("#profilePic").val() == "")
{
alert('Please attach a image.');
return false;
}
else
{
var formData = new FormData();
//formData.append("profilePic", $('#profilePic').prop('files')[0])
var blob = dataURLtoBlob(canvas.toDataURL('image/png'));
formData.append("profilePic", blob);
$.ajax({
url:"/imageUpload.jsp",
type: "POST",
data: formData,
contentType:false,
cache: false,
processData:false,
}).done(function(data){
data = $.trim(data);
data = JSON.parse(data);
if(data.status == 'OK'){
alert("Profile pic uploaded successfully.");
$('.imagefldforpar img').attr('src',data.imgPath);
}else{
alert("Profile pic not uploaded.");
}
console.log(data);
$('#uploadPhoto').modal('hide');
});
}
}
</script>
<link href="/css/jquery.Jcrop.min.css" rel="stylesheet">
<script type="text/javascript" src="/js/jquery.Jcrop.min.js"></script>
<script>
var crop_max_width = 400;
var crop_max_height = 400;
var jcrop_api;
var canvas;
var context;
var image;
var prefsize;
$("#profilePic").change(function() {
loadImage(this);
});
function loadImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
canvas = null;
reader.onload = function(e) {
image = new Image();
image.onload = validateImage;
image.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
}
function dataURLtoBlob(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {
type: contentType
});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
}
function validateImage() {
if (canvas != null) {
image = new Image();
image.onload = restartJcrop;
image.src = canvas.toDataURL('image/png');
} else restartJcrop();
}
function restartJcrop() {
if (jcrop_api != null) {
jcrop_api.destroy();
}
$("#views").empty();
$("#views").append("<canvas id=\"canvas\">");
canvas = $("#canvas")[0];
context = canvas.getContext("2d");
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
$("#canvas").Jcrop({
onSelect: selectcanvas,
onRelease: clearcanvas,
aspectRatio: 4/5,
boxWidth: crop_max_width,
boxHeight: crop_max_height
}, function() {
jcrop_api = this;
});
clearcanvas();
}
function clearcanvas() {
prefsize = {
x: 0,
y: 0,
w: canvas.width,
h: canvas.height,
};
}
function selectcanvas(coords) {
prefsize = {
x: Math.round(coords.x),
y: Math.round(coords.y),
w: Math.round(coords.w),
h: Math.round(coords.h)
};
}
function applyCrop() {
canvas.width = prefsize.w;
canvas.height = prefsize.h;
context.drawImage(image, prefsize.x, prefsize.y, prefsize.w, prefsize.h, 0, 0, canvas.width, canvas.height);
validateImage();
}
function applyScale(scale) {
if (scale == 1) return;
canvas.width = canvas.width * scale;
canvas.height = canvas.height * scale;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
validateImage();
}
function applyRotate() {
canvas.width = image.height;
canvas.height = image.width;
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.height / 2, image.width / 2);
context.rotate(Math.PI / 2);
context.drawImage(image, -image.width / 2, -image.height / 2);
validateImage();
}
function applyHflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.width, 0);
context.scale(-1, 1);
context.drawImage(image, 0, 0);
validateImage();
}
function applyVflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(0, image.height);
context.scale(1, -1);
context.drawImage(image, 0, 0);
validateImage();
}
$("#cropbutton").click(function(e) {
applyCrop();
});
$("#scalebutton").click(function(e) {
var scale = prompt("Scale Factor:", "1");
applyScale(scale);
});
$("#rotatebutton").click(function(e) {
applyRotate();
});
$("#hflipbutton").click(function(e) {
applyHflip();
});
$("#vflipbutton").click(function(e) {
applyVflip();
});
</script>
Thanks #Zigri2612 for Solution
<script>
function uploadPhoto(thisVar) {
if($("#profilePic").val() == "")
{
alert('Please attach a image.');
return false;
}
else
{
var formData = new FormData();
//formData.append("profilePic", $('#profilePic').prop('files')[0])
var blob = dataURLtoBlob(canvas.toDataURL('image/png'));
formData.append("profilePic", blob,"image.png");
$.ajax({
url:"/imageUpload.jsp",
type: "POST",
data: formData,
contentType:false,
cache: false,
processData:false,
}).done(function(data){
data = $.trim(data);
data = JSON.parse(data);
if(data.status == 'OK'){
alert("Profile pic uploaded successfully.");
$('.imagefldforpar img').attr('src',data.imgPath);
}else{
alert("Profile pic not uploaded.");
}
console.log(data);
$('#uploadPhoto').modal('hide');
});
}
}
</script>
<link href="/css/jquery.Jcrop.min.css" rel="stylesheet">
<script type="text/javascript" src="/js/jquery.Jcrop.min.js"></script>
<script>
var crop_max_width = 400;
var crop_max_height = 400;
var jcrop_api;
var canvas;
var context;
var image;
var prefsize;
$("#profilePic").change(function() {
loadImage(this);
});
function loadImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
canvas = null;
reader.onload = function(e) {
image = new Image();
image.onload = validateImage;
image.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
}
function dataURLtoBlob(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {
type: contentType
});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
}
function validateImage() {
if (canvas != null) {
image = new Image();
image.onload = restartJcrop;
image.src = canvas.toDataURL('image/png');
} else restartJcrop();
}
function restartJcrop() {
if (jcrop_api != null) {
jcrop_api.destroy();
}
$("#views").empty();
$("#views").append("<canvas id=\"canvas\">");
canvas = $("#canvas")[0];
context = canvas.getContext("2d");
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
$("#canvas").Jcrop({
onSelect: selectcanvas,
onRelease: clearcanvas,
aspectRatio: 4/5,
boxWidth: crop_max_width,
boxHeight: crop_max_height
}, function() {
jcrop_api = this;
});
clearcanvas();
}
function clearcanvas() {
prefsize = {
x: 0,
y: 0,
w: canvas.width,
h: canvas.height,
};
}
function selectcanvas(coords) {
prefsize = {
x: Math.round(coords.x),
y: Math.round(coords.y),
w: Math.round(coords.w),
h: Math.round(coords.h)
};
}
function applyCrop() {
canvas.width = prefsize.w;
canvas.height = prefsize.h;
context.drawImage(image, prefsize.x, prefsize.y, prefsize.w, prefsize.h, 0, 0, canvas.width, canvas.height);
validateImage();
}
function applyScale(scale) {
if (scale == 1) return;
canvas.width = canvas.width * scale;
canvas.height = canvas.height * scale;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
validateImage();
}
function applyRotate() {
canvas.width = image.height;
canvas.height = image.width;
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.height / 2, image.width / 2);
context.rotate(Math.PI / 2);
context.drawImage(image, -image.width / 2, -image.height / 2);
validateImage();
}
function applyHflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.width, 0);
context.scale(-1, 1);
context.drawImage(image, 0, 0);
validateImage();
}
function applyVflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(0, image.height);
context.scale(1, -1);
context.drawImage(image, 0, 0);
validateImage();
}
$("#cropbutton").click(function(e) {
applyCrop();
});
$("#scalebutton").click(function(e) {
var scale = prompt("Scale Factor:", "1");
applyScale(scale);
});
$("#rotatebutton").click(function(e) {
applyRotate();
});
$("#hflipbutton").click(function(e) {
applyHflip();
});
$("#vflipbutton").click(function(e) {
applyVflip();
});
</script>
I need to rotate/scale/flip/crop an image on an HTML page.
I'm using JCrop.js for image manipulation on client side. I'm able to do this successfully with a file selector, where the user selects an image file on their local computer. My requirement is to do the same, but for an image loaded from another URL (without selecting a local image).
Need help on the next step.
Here is the complete code that works well with local file selection:
HTML:
<img scr="externalURL" id="imgMain" alt=""/>
<input type="button" id="cropbutton" value="Crop" />
<input type="button" id="rotatebutton" value="Rotate" />
<input type="button" id="hflipbutton" value="Flip Horizontal" />
<input type="button" id="vflipbutton" value="Flip Vertical" />
JS:
var cropWidth = 800;
var cropHeight = 800;
var crop_max_width = 400;
var crop_max_height = 400;
var jcrop_api;
var canvas;
var context;
var image;
var prefsize;
$(document).ready(function () {
$("#file").change(function () {
loadImage(this);
});
$("#btnCrop").click(function () {
SaveData();
});
});
function SaveData() {
formData = new FormData($(this)[0]);
var blob = dataURLtoBlob(canvas.toDataURL('image/jpeg'));
formData.append("cropped_image[]", blob, "CroppedImage.jpeg");
$.ajax({
url: urlToSendData
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function (data) {
alert("Image cropped!");
},
error: function (data) {
alert('There was an error');
}
});
}
function loadImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
canvas = null;
reader.onload = function (e) {
image = new Image();
image.onload = validateImage;
image.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
applyCrop();
}
}
function dataURLtoBlob(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {
type: contentType
});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
}
function validateImage() {
if (canvas != null) {
image = new Image();
image.onload = restartJcrop;
image.src = canvas.toDataURL('image/png');
} else restartJcrop();
}
function restartJcrop() {
if (jcrop_api != null) {
jcrop_api.destroy();
}
$("#views").empty();
$("#views").append("<canvas id=\"canvas\">");
canvas = $("#canvas")[0];
context = canvas.getContext("2d");
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
$("#canvas").Jcrop({
onSelect: selectcanvas,
onRelease: clearcanvas,
boxWidth: crop_max_width,
boxHeight: crop_max_height,
allowResize: false,
allowSelect: false,
setSelect: [0, 0, cropWidth, cropHeight],
aspectRatio: 1
}, function () {
jcrop_api = this;
});
clearcanvas();
}
function clearcanvas() {
prefsize = {
x: 0,
y: 0,
w: canvas.width,
h: canvas.height,
};
}
function selectcanvas(coords) {
prefsize = {
x: Math.round(coords.x),
y: Math.round(coords.y),
w: Math.round(coords.w),
h: Math.round(coords.h)
};
}
function applyCrop() {
canvas.width = prefsize.w;
canvas.height = prefsize.h;
context.drawImage(image, prefsize.x, prefsize.y, prefsize.w, prefsize.h, 0, 0, canvas.width - 10, canvas.height - 10);
validateImage();
}
function applyScale(scale) {
if (scale == 1) return;
canvas.width = canvas.width * scale;
canvas.height = canvas.height * scale;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
validateImage();
}
function applyRotate() {
canvas.width = image.height;
canvas.height = image.width;
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.height / 2, image.width / 2);
context.rotate(Math.PI / 2);
context.drawImage(image, -image.width / 2, -image.height / 2);
validateImage();
}
function applyHflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.width, 0);
context.scale(-1, 1);
context.drawImage(image, 0, 0);
validateImage();
}
function applyVflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(0, image.height);
context.scale(1, -1);
context.drawImage(image, 0, 0);
validateImage();
}
$("#scalebutton").click(function (e) {
var scale = prompt("Scale Factor:", "1");
applyScale(scale);
});
$("#rotatebutton").click(function (e) {
applyRotate();
});
$("#hflipbutton").click(function (e) {
applyHflip();
});
$("#vflipbutton").click(function (e) {
applyVflip();
});
Looks like loadImage reads the file and sets the image global.
As there is now already an image on the page, we should be able to skip this step.
So we can probably just set the image in ready like this:
$(document).ready(function () {
// (this code replaces the file selecting)
image = $("#imgMain"); // set image from the page
canvas = null; // this was done in loadImage
applyCrop(); // this was called from loadImage
// (this code is the same as before)
$("#btnCrop").click(function () {
SaveData();
});
});
I have a simple code to upload files using ajax to server, but i don't know how i can resize the image before that process to improve the performance ..
Code of Previewing image.
function Preview_Image(index){
var img = document.createElement("img");
img.src = window.URL.createObjectURL(filesList[index]);
$('#loaded-image-frame' + index + ' #preview').html(img);
img.onload = function () {
window.URL.revokeObjectURL(img.src);
}
}
Code of Uploading image..
function Upload_ResizedImage(index){
var image = filesList[index]
var form_data = new FormData();
form_data.append('file[]', image);
process = $.ajax({
url: "ControlPanelAjax.ashx?job=UploadImages,
type: "POST",
data: form_data,
processData: false,
cache: false,
contentType: false,
beforeSend: function (event) { },
success: function (data, textStatus, jQxhr) {
if (data != '-1') {
alert("image uploaded correctly");
}
else {
alert("Error Uploading..");
}
},
complete: function (event) {},
error: function (jqXhr, textStatus, errorThrown) {},
xhr: function () {}
});
}
Note: filesList is an array containing files that i made up
You can achieve this using canvas from HTML5. Here is a tutorial and here is the related code
HTML:
if (window.File && window.FileReader && window.FileList && window.Blob) {
document.getElementById('filesToUpload').onchange = function(){
var files = document.getElementById('filesToUpload').files;
for(var i = 0; i < files.length; i++) {
resizeAndUpload(files[i]);
}
};
} else {
alert('The File APIs are not fully supported in this browser.');
}
function resizeAndUpload(file) {
var reader = new FileReader();
reader.onloadend = function() {
var tempImg = new Image();
tempImg.src = reader.result;
tempImg.onload = function() {
var MAX_WIDTH = 400;
var MAX_HEIGHT = 300;
var tempW = tempImg.width;
var tempH = tempImg.height;
if (tempW > tempH) {
if (tempW > MAX_WIDTH) {
tempH *= MAX_WIDTH / tempW;
tempW = MAX_WIDTH;
}
} else {
if (tempH > MAX_HEIGHT) {
tempW *= MAX_HEIGHT / tempH;
tempH = MAX_HEIGHT;
}
}
var canvas = document.createElement('canvas');
canvas.width = tempW;
canvas.height = tempH;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, tempW, tempH);
var dataURL = canvas.toDataURL("image/jpeg");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(ev){
document.getElementById('filesInfo').innerHTML = 'Done!';
};
xhr.open('POST', 'uploadResized.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var data = 'image=' + dataURL;
xhr.send(data);
}
}
reader.readAsDataURL(file);
}
PHP:
if ($_POST) {
define('UPLOAD_DIR', 'uploads/');
$img = $_POST['image'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.jpg';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
}
I want to upload a resized image to server, but I get "Required MultipartFile parameter 'file' is not present" error when I try to upload the resized image. When I upload the original file from there is no problem.
Script:
function resizeAndUpload(file) {
var reader = new FileReader();
reader.onloadend = function () {
var tempImg = new Image();
tempImg.src = reader.result;
tempImg.onload = function () {
var MAX_WIDTH = 200;
var MAX_HEIGHT = 200;
var tempW = tempImg.width;
var tempH = tempImg.height;
if (tempW > tempH) {
if (tempW > MAX_WIDTH) {
tempH *= MAX_WIDTH / tempW;
tempW = MAX_WIDTH;
}
} else {
if (tempH > MAX_HEIGHT) {
tempW *= MAX_HEIGHT / tempH;
tempH = MAX_HEIGHT;
}
}
var canvas = document.createElement('canvas');
canvas.width = tempW;
canvas.height = tempH;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, tempW, tempH);
var dataURL = canvas.toDataURL("image/jpeg");
var data = new FormData();
data.append('file', dataURL);
$.ajax({
url: '/changeimage',
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
success: function () {
window.alert("uploaded")
}
});
}
}
reader.readAsDataURL(file);
}
Server:
#RequestMapping(value = "/changeimage", method = RequestMethod.POST)
#ResponseBody
public String changeProfileImage(#Context HttpServletRequest request, #RequestParam("file") MultipartFile file) {
return "ok";
}
A data url is a string and will not upload as a file.
However you can use a blob instead
...
ctx.drawImage(this, 0, 0, tempW, tempH);
canvas.toBlob(function(blob){
var data = new FormData();
data.append('file', blob);
$.ajax({
url: '/changeimage',
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
success: function () {
window.alert("uploaded")
}
});
});
...
This AJAX request doesn't return any 64-Value-String in the beforeSend handler like it should. But as alert in the function it does! I don't know how to do this async. What is the Issue?
$imageMaps[0] = '1.jpeg';
$imageMaps[1] = '2.jpeg';
for (var k in $imageMaps) {
$file = $imageMaps[k];
$.ajax({
type: "POST",
async: 0,
beforeSend: function (xhr, settings) {
$base64 = convertImgToBase64($file);
alert($base64)
settings.data.img = $base64;
settings.data.url = $file;
},
url: '/request.php?imagePost=1',
data: {
img: '',
url: $file
},
success: function () {}
});
}
function convertImgToBase64(url) {
var img = new Image();
img.src = url;
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);
dataurl = canvas.toDataURL("image/png");
alert(dataurl)
return dataurl;
}
}
You are actually returning nothing from that func. Try to do like this:
function convertImgToBase64(url) {
var img = new Image();
img.src = url;
return 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);
dataurl = canvas.toDataURL("image/png");
alert(dataurl)
return dataurl;
}
}
I may be wrong, so if does not work, do comment it.
Here is the Solution:
$imageMaps[0] = '1.jpeg';
$imageMaps[1] = '2.jpeg';
for (var k in $imageMaps) {
$file=$imageMaps[k];
convertImgToBase64($url, function($base64Img,$url2){
$.ajax({
type: "POST",
async : 1,
url: '/request.php?imagePost=1',
data: {img:$base64Img,url:$url2},
xhr: function() {},
success: function(){}
});
})
}
function convertImgToBase64(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this,0,0);
var dataURL = canvas.toDataURL(outputFormat || 'image/png');
callback(dataURL,url);
canvas = null;
};
img.src = url;
}