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>
Related
I am trying to create an endless runner game from scratch using JavaScript, and I am currently in the process of making the character jump. However, when I press the spacebar, my character does not move up, but instead just stays in one place. I have pasted my code below:
let ctx = document.querySelector("canvas").getContext("2d");
// Screen size
ctx.canvas.height = 512;
ctx.canvas.width = 512;
// Images
let bg = new Image; // Background
bg.src = "./Background.png";
bg.onload = function() {
ctx.drawImage(bg, 0, 0);
};
let fl = new Image; // Floor
fl.src = "./Floor.png";
fl.onload = function() {
ctx.drawImage(fl, 0, 384);
ctx.drawImage(fl, 128, 384);
ctx.drawImage(fl, 256, 384);
ctx.drawImage(fl, 384, 384);
};
let pl = new Image; // Player
pl.src = "./Idle.png";
pl.onload = function() {
ctx.drawImage(pl, 0, 256);
};
// Movement
let UP = false;
document.onkeydown = function(e) {
if (e.keyCode == 32) UP = true;
};
document.onkeyup = function(e) {
if (e.keyCode == 32) UP = false;
};
setInterval(update, 10);
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Erase previous positions
if (UP) {
pl.onload = function() {
ctx.drawImage(pl, 0, 256 += 1); // Move player up
};
};
};
I fixed it with some help from Rojo.
let ctx = document.querySelector("canvas").getContext("2d");
// Screen size
ctx.canvas.height = 512;
ctx.canvas.width = 512;
// Images
let bg = new Image;
bg.src = "./Background.png";
let fl = new Image;
fl.src = "./Floor.png";
let pl = new Image;
pl.src = "./Idle.png";
let y = 256;
pl.onload = function() {
ctx.drawImage(pl, 0, y);
};
let UP = false;
document.onkeydown = function(e) {
if (e.keyCode == 32) UP = true;
};
document.onkeyup = function(e) {
if (e.keyCode == 32) UP = false;
};
function update() {
ctx.clearRect(0, 0, 512, 512);
ctx.drawImage(bg, 0, 0);
ctx.drawImage(fl, 0, 384);
ctx.drawImage(fl, 128, 384);
ctx.drawImage(fl, 256, 384);
ctx.drawImage(fl, 384, 384);
if (UP) {
ctx.drawImage(pl, 0, y -= 1);
} else {
ctx.drawImage(pl, 0, y);
};
};
setInterval(update, 10);
I am new to javascript and am modifying a javascript code which has draws dynamic text on image and user can upload it.
The image will be fixed, user can't upload his own image.
Whatever I do, I am not able to remove the "choose image to upload" option from this code. Can anyone please help me with this?
My code is below:
var text_title = "Heading";
var text_title1 = "Heading";
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.crossOrigin = "anonymous";
window.addEventListener('load', DrawPlaceholder)
function DrawPlaceholder() {
img.onload = function() {
DrawOverlay(img);
DrawText();
DynamicText(img)
};
img.src = 'uploads/<?php echo $image["image"] ?>';
}
function DrawOverlay(img) {
ctx.drawImage(img, 0, 0);
ctx.fillStyle = 'rgba(230, 14, 14, 0)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function DrawText() {
ctx.fillStyle = "black";
ctx.textBaseline = 'middle';
ctx.font = "50px 'Montserrat'";
ctx.fillText(text_title, 50, 50);
ctx.fillText(text_title1, 150, 250);
}
function DynamicText(img) {
document.getElementById('name').addEventListener('keyup', function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
DrawOverlay(img);
DrawText();
text_title = this.value;
ctx.fillText(text_title, 50, 50);
});
document.getElementById('name1').addEventListener('keyup', function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
DrawOverlay(img);
DrawText();
text_title1 = this.value;
ctx.fillText(text_title1, 150, 250);
});
}
function handleImage(e) {
var reader = new FileReader();
var img = "";
var src = "";
reader.onload = function(event) {
img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
}
img.src = event.target.result;
src = event.target.result;
canvas.classList.add("show");
DrawOverlay(img);
DrawText();
DynamicText(img);
}
reader.readAsDataURL(e.target.files[0]);
}
function convertToImage() {
window.open(canvas.toDataURL('png'));
}
document.getElementById('download').onclick = function download() {
convertToImage();
}
<input class="controls__input" type="file" id="imageLoader" name="imageLoader" />
<label class="controls__label" for="name">First, choose an image.</label>
Like this?
var text_title = "Heading";
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
// img.crossOrigin = "anonymous";
window.addEventListener('load', DrawPlaceholder)
function DrawPlaceholder() {
img.onload = function() {
DrawOverlay(img);
DrawText(text_title);
DynamicText(img)
};
img.src = 'https://via.placeholder.com/500x500';
}
function DrawOverlay(img) {
ctx.drawImage(img, 0, 0);
ctx.fillStyle = 'rgba(230, 14, 14, 0)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function DrawText(text) {
ctx.fillStyle = "black";
ctx.textBaseline = 'middle';
ctx.font = "50px 'Montserrat'";
ctx.fillText(text, 50, 50);
}
function DynamicText(img) {
document.getElementById('name').addEventListener('keyup', function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
DrawOverlay(img);
text_title = this.value;
DrawText(text_title);
});
}
canvas {
height: 300px;
width: 500px;
}
<input type="text" id="name" value="John" /><br/>
<canvas id="imageCanvas"></canvas>
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'm wondering what I am missing here I have a code that checks if the image is transparent based on canvas.
function Trasparent(url, npc, clb) {
var img = new Image();
img.src = url;
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
var maxlength = Math.sqrt(img.width * img.height) * 5 + 300;
if (canvas.toDataURL().length < maxlength) {
clb(false, npc);
} else {
clb(true, npc);
}
};
}
When I'm doing it this way:
function Trasparent(url, npc, clb) {
var img = new Image();
img.src = url;
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
var maxlength = Math.sqrt(img.width * img.height) * 5 + 300;
if (canvas.toDataURL().length < maxlength) {
clb(false, npc);
} else {
clb(true, npc);
}
};
}
function callback(success, npc) {
if (success) {
console.log("Not trasparent");
} else {
console.log("Trasparent");
}
}
Trasparent(npc.icon, npc, callback);
It works just fine, but when I'm trying to make this function above like this:
function Trasparent(url, npc) {
var img = new Image();
img.src = url;
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
var maxlength = Math.sqrt(img.width * img.height) * 5 + 300;
if (canvas.toDataURL().length < maxlength) {
return false;
} else {
return true;
}
};
}
if(Transparent(npc.icon, npc)){
console.log("Not transparent");
} else {
console.log("Trasparent");
}
It doesn't work...
Even tho in this example which i wrote it works fine:
function check(a, b) {
var result = a + b;
if (result <= 10) {
return (false);
} else {
return (true);
}
}
function test() {
if (check(5, 4)) {
console.log(">10");
} else {
console.log("<10")
}
}
test();
What i am missing?
The return-statements are not belonging to the function Transparent!
You are creating a different function here which returns true or false when it is called, but it is not executed right away and it's return-value is not returned in your function Transparent.
What you have is essentially this snippet:
function Trasparent(url, npc) {
var img = new Image();
img.src = url;
img.onload = function() {
// function body totally unrelated to the Transparent-function
// and not executed and not returning anything right now
};
return undefined;
}
(these are not actually the same since fat arrow functions capture this, see What does "this" refer to in arrow functions in ES6?)
Your solution with the callback is the way to go.
your code is async. you cant return true or false. you need to return a callback thats why your if doesn't work
function Trasparent(url, npc,cb) {
var img = new Image();
img.src = url;
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
var maxlength = Math.sqrt(img.width * img.height) * 5 + 300;
if (canvas.toDataURL().length < maxlength) {
cb(false);
} else {
cb(true);
}
};
}
Transparent(npc.icon, npc,function(result){
if(result)
console.log("Not transparent");
} else {
console.log("Trasparent");
}
})
)
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.