jQuery Ajax: set dataUrl beforeSend - javascript

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;
}

Related

Unable to convert png image to base64encoded string

This piece of code below is supposed to convert the raw image to base64 string.
let base1="";
let base2="";
let base3="";
let base64String="";
var img=new Image();
var img1=new Image();
var img2=new Image();
img.src='Screenshot (1).png';
img1.src='Screenshot (2).png';
img2.src='Screenshot (3).png';
var reader = new FileReader();
reader.onload = function () {
base64String = reader.result.replace("data:", "")
.replace(/^.+,/, "");
}
reader.readAsDataURL(img);
base1=base64String;
reader.readAsDataURL(img1);
base2=base64String;
reader.readAsDataURL(img2);
base3=base64String;
But when I execute the code, I get the following error:
Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader':
parameter 1 is not of type 'Blob'.
Why is that? Please help me fix this.
Because readAsDataURL expects the parameter as Blob. Best method will be to convert to base64 data url using canvas
let base1="";
let base2="";
let base3="";
let base64String="";
var img=new Image();
var img1=new Image();
var img2=new Image();
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
base1 = canvas.toDataURL();
}
img.src='Screenshot (1).png';
img1.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = img1.width;
canvas.height = img1.height;
ctx = canvas.getContext('2d');
ctx.drawImage(img1, 0, 0);
base2 = canvas.toDataURL();
}
img1.src='Screenshot (2).png';
img2.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = img2.width;
canvas.height = img2.height;
ctx = canvas.getContext('2d');
ctx.drawImage(img2, 0, 0);
base2 = canvas.toDataURL();
}
img2.src='Screenshot (3).png';
The canvas.toDataURL() without param will generate a data url of type png if if the img src is a jpg

JS image to base64 return string

I have code that works fine
function convertImgToBase64URL(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'), dataURL;
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
convertImgToBase64URL('/img/logo.png', function(base64Img){
console.log(base64Img);
});
But I need to get the result into a variable
convertImgToBase64URL('/img/logo.png', function(base64Img){
var test = base64Img;
});
alert(test);
Any idea how to pass the result to a variable?

JCrop: Manipulate image from external URL

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();
});
});

send canvas as an image to server

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.

Why my code to convert any image to a Base64 string is not working?

I am trying to convert any image to a Base64 String but not getting the output
See the screenshot what I am getting
Screenshot
Javascript code
function encodeImageFileAsURL(cb)
{
return function()
{
var file = this.files[0];
var reader = new FileReader();
reader.onloadend = function ()
{
cb(reader.result);
}
reader.readAsDataURL(file);
}
}
$('#inputFileToLoad').change(encodeImageFileAsURL(function(base64Img)
{
$('.output')
.find('textarea')
.val(base64Img)
.end()
.find('a')
.attr('href', base64Img)
.text(base64Img)
.end()
.find('img')
.attr('src', base64Img);
}));
Basic example to convert to base64:
function toBase64(src, callback) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
callback(canvas.toDataURL());
}
img.src = src;
}

Categories