How to upload canvas image in server? - ajax

I Take a snap by using HTML5 Now i want to upload that image into server(by using spring mvc+Ajax i want to upload that image in google app blob store) Any one Help me
here My Sample code
<video id="video" width="640" height="480" autoplay></video>
<button id="snap">Snap Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>
<button id="getBase" onclick="getBase()">Get Base64</button>
<textarea id="textArea"></textarea>
<script>
// Put event listeners into place
window.addEventListener("DOMContentLoaded", function() {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
}
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 640, 480);
});
document.getElementByID("getBase").addEventListener("click", getBase());
}, false);
function getBase(){
var imgBase = canvas.toDataURL("image/png");
alert(imgBase);
document.getElementByID("textArea").value=imgBase;
}
`
Any one help me How can i upload image on server by using ajax

You likely want to use a FormData object. Mozilla has a pretty good guide on how to do that. They even cover sending files specifically. In your case, I'd recommend storing the image data as a blob.

Related

How to align fabric.Image objects horizontally?

I am simply trying to load three rectangular images and want them to align horizontally adjacent to each other. I thought setting the left property in fabric.Image.fromURL method would accomplish this but the tree images load stacked on top of each other. Also even though I include selectable:true, the images are not selectable. Am I using fabric.Image.fromURL incorrectly?
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<!-- Get version 1.1.0 of Fabric.js from CDN -->
<script src="js/fabric.js"></script>
<!-- Get the highest 1.X version of jQuery from CDN. Required for ready() function. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(function () {
var canvas = new fabric.Canvas('canvas', {
backgroundColor: 'black',
selectionColor: 'blue',
selectionLineWidth: 0
// ...
});
debugger;
var tiles = [
"images/Green.png",
"images/Red.png",
"images/Yellow.png"
];
var offset = [
"0",
"200",
"400"
];
debugger;
for (i = 0; i < tiles.length; i++) {
fabric.Image.fromURL(tiles[i], function (img) {
img.scale(1.0).set({
left: offset[i],
top: 0,
selectable:true,
});
canvas.add(img).setActiveObject(img);
});
}
function handleDragStart(e) {
[].forEach.call(images, function (img) {
img.classList.remove('img_dragging');
});
this.classList.add('img_dragging');
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
e.dataTransfer.dropEffect = 'copy'; // See the section on the DataTransfer object.
// NOTE: comment above refers to the article (see top) -natchiketa
return false;
}
function handleDragEnter(e) {
// this / e.target is the current hover target.
this.classList.add('over');
}
function handleDragLeave(e) {
this.classList.remove('over'); // this / e.target is previous target element.
}
function handleDrop(e) {
// this / e.target is current target element.
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
var img = document.querySelector('#images img.img_dragging');
console.log('event: ', e);
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
// Set the center of the new object based on the event coordinates relative
// to the canvas container.
left: e.layerX,
top: e.layerY
});
canvas.add(newImage);
return false;
}
function handleDragEnd(e) {
// this/e.target is the source node.
[].forEach.call(images, function (img) {
img.classList.remove('img_dragging');
});
}
// Bind the event listeners for the image elements
var images = document.querySelectorAll('#images img');
[].forEach.call(images, function (img) {
img.addEventListener('dragstart', handleDragStart, false);
img.addEventListener('dragend', handleDragEnd, false);
});
// Bind the event listeners for the canvas
var canvasContainer = document.getElementById('canvas-container');
canvasContainer.addEventListener('dragenter', handleDragEnter, false);
canvasContainer.addEventListener('dragover', handleDragOver, false);
canvasContainer.addEventListener('dragleave', handleDragLeave, false);
canvasContainer.addEventListener('drop', handleDrop, false);
});
</script>
</head>
<body>
<div id="canvas-container">
<canvas id="canvas" width="600" height="200"></canvas>
</div>
<div id="images">
<img draggable="true" src="images/Red.png" width="50" height="50"></img>
<img draggable="true" src="images/Yellow.png" width="50" height="50"></img>
<img draggable="true" src="images/Green.png" width="50" height="50"></img>
</div>
</body>
</html>
There is a race condition between your fabric.Image.fromURL callback and the execution of the for loop, which prevents the images from showing.
If you print i and offset[i] inside your callback:
fabric.Image.fromURL(tiles[i], function (img) {
console.log(i, offset[i]);
...
});
you'll notice that i is 3 and offset[i] is undefined in all off the callbacks.
This happens because each of the callbacks retain a reference to the same instance of the i variable, and use its latest value at the time they execute. The for loop loops through its cycles, each time incrementing i, before any of your callbacks execute, leaving i with a final value of 3. When your callbacks execute, they try to set the left: value to offset[3], which is undefined, and fabric falls back to 0.
Solution
Variables in pre-ES6 javascript (unlike most languages) are only scoped to the function they are declared it, and code-blocks do not affect scope.
Place your image build logic into its own function, passing the current value of i as a parameter in each loop cycle. This will place the value into a new scope, and preserve the value.
Also, don't forget the var keyword in front of your i. Otherwise you're affecting the global namespace, which you want to avoid at all cost.
Here's what your code should look like:
for (var i = 0; i < tiles.length; i++) {
buildImage(i);
}
// creates a new scope for the passed in value of i when called:
function buildImage(i) {
fabric.Image.fromURL(tiles[i], function (img) {
img.scale(1.0).set({
left: offset[i],
top: 0,
selectable: true,
});
canvas.add(img).setActiveObject(img);
});
}
Finally, you may want to consider setting the originX and originY properties of the images, like so:
originX: 'left',
originY: 'top'
By default, fabric will use the center of the images as the point of origin when placing them, and your images will not be in full view of the canvas.
Update
Here is the fully working example. It is dependent on fabric, which needs to be placed in your js/ folder.

How to access the image data after dropping an image from the html-part of a webpage onto a canvas?

This is a follow up question to
How to drop texts and images on a canvas? (Firefox 41.0.1)
I simply can't find out how to access the image data of the image I dropped onto the canvas. I tried things like data = event.dataTransfer.getData("image"), but that all doesn't work.
function addDragNDropToCanvas() {
document.getElementById('canvas').addEventListener("dragover", function(event) { event.preventDefault();}, false);
//handle the drop
document.getElementById('canvas').addEventListener("drop", function(event) {
event.preventDefault();
console.log('something is dropped on the object with id: ' + event.target.id);
// var directData=event.dataTransfer.getData("image");
console.log(event);
}, false);
}
There surely is the image-data somewhere incorporated in the drop-event data? Isn't it???
(The image doesn't have an own id-attribute.)
Your user might do one (or both) of these two drags:
Drag an img element from your webpage onto the canvas, or
Drag an image file from your local drive onto the canvas.
If the image is being dragged from your webpage:
Listen for the dragover, drop, and optionally the dragenter events.
When handling all 3 events, tell the browser you're handling the event with event.preventDefault and optionally event.stopPropagation.
In the drop handler, get event.dataTransfer.getData('text/plain') which fetches the.src` of the image that was dropped.
Create a new Image() object using the .src and drawImage to the canvas.
If the image is being dragged from your local drive:
1 & 2. Listen & handle the same events as in the webpage code.
Fetch the local image file(s) that the user dropped which have been placed in event.dataTransfer.files.
Create a FileReader and read each image file. The FileReader.readAsDataURL method will return an image URL that you can use as a .src for an Image object.
drawImage each new image to the canvas.
Here's example code that allows both:
window.onload=function(){
// canvas related vars
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// dropZone event handlers
var dropZone=document.getElementById("canvas");
dropZone.addEventListener("dragenter", handleDragEnter, false);
dropZone.addEventListener("dragover", handleDragOver, false);
dropZone.addEventListener("drop", handleDrop, false);
//
function handleDragEnter(e){e.stopPropagation(); e.preventDefault();}
//
function handleDragOver(e){e.stopPropagation(); e.preventDefault();}
//
function handleDrop(e){
e.stopPropagation();
e.preventDefault();
//
var url=e.dataTransfer.getData('text/plain');
// for img elements, url is the img src so
// create an Image Object & draw to canvas
if(url){
var img=new Image();
img.onload=function(){ctx.drawImage(this,0,0);}
img.src=url;
// for img file(s), read the file & draw to canvas
}else{
handleFiles(e.dataTransfer.files);
}
}
// read & create an image from the image file
function handleFiles(files) {
for (var i=0;i<files.length;i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)){continue;}
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
var reader=new FileReader();
reader.onload=(function(aImg){
return function(e) {
aImg.onload=function(){
ctx.drawImage(aImg,0,0);
}
// e.target.result is a dataURL for the image
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
} // end for
} // end handleFiles
}; // end $(function(){});
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<!doctype html>
<html>
<body>
<h4>Drag an image from below onto the canvas, or<br>Drag an image file from your desktop onto the canvas.</h4>
<canvas id="canvas" width=300 height=300></canvas>
<br>
<img width="50" src="https://cfl.dropboxstatic.com/static/images/index/rebrand/logos/glyphs/glyph_french_vanilla.svg">
</body>
</html>
Here is a set of (stripped down) tools I use to play with images
var imageTools = (function () {
var tools = {
canvas : function (width, height) { // create a blank image (canvas)
var c = document.createElement("canvas");
c.width = width;
c.height = height;
return c;
},
createImage : function (width, height) {
var image = this.canvas(width, height);
image.ctx = image.getContext("2d");
return image;
},
loadImage : function (url, callback) {
var image = new Image();
image.src = url;
image.addEventListener('load', cb);
image.addEventListener('error', cb);
return image;
},
image2Canvas : function (img) {
var image = this.canvas(img.width, img.height);
image.ctx = image.getContext("2d");
image.drawImage(ig, 0, 0);
return image;
},
getImageData : function (image) {
return (image.ctx || (this.image2Canvas(image).ctx)).getImageData(0, 0, image.width, image.height).data;
},
};
return tools;
})();
After it is parsed you will have the global variable imageTools
To load and get the image data you will have to wait for the image load callback.
var image;
var imageData;
function loaded(event){
if(event.type === "load"){
image = imageTools.image2Canvas(this);
imageData = imageTools.getImageData(image);
// image data is now in the typed array
// imageData.data
// with imageData.width and imageData.height holding the size
// there are 4 bytes per pixel in the form RGBA
}
}
imageTools.loadImage(imageURL,loaded);
To put the data back into the image after using the imageTools
// image.ctx is non standard and is a result of the imageTools adding the
// attribute ctx
image.ctx.putImageData(imageData,0,0);
To get the URL from the drop event which may be more than one image
var fileList = []; // a list of dropped images
// function called when images dropped
var imagesDropped = function(){
fileList.forEach(function(image){
// image.name is the image URL
// image.type is the mime type
});
fileList = []; // clear the file list
}
var dropEvent = function (event) {
var i,j, imagesFound;
imagesFound = false;
event.preventDefault();
dt = event.dataTransfer;
for (i = 0; i < dt.types.length; i++) { // for each dropped item
if (dt.types[i] === "Files") { // content from the file system
for (var j = 0; j < dt.files.length; j++) {
// check the mime type for the image prefix
if (dt.files[j].type.indexOf("image/") > -1){
fileList.push({ // add to image list
name : dt.files[j].name,
type : dt.files[j].type,
});
imagesFound = true; // flag images found
}
}
}
}
if(imagesFound){ // if images dropped call the handling function
imagesDropped();
}
}
Please note this is an example only and is not a cross browser solution. You will have to implement a variety of drop managers t cover all the browsers. This works on Chrome so covers the majority of users.

Firebase know when message pushed?

I'm upload images in the form of Base64 into Firebase but what I've noticed is that it shows up on the uploader's interface before it's finished uploading to Firebase server.
So how would I know when it's finished uploading the image?
Alternatively, how can I postpone the image showing up on the uploader's interface until the image has been uploaded, so it displays synchronously with all users?
Any help is appreciated, thanks in advance.
Edit: March 6th
Ok so I've reduce the code to the bare minimum to demonstrate this. Though to observe this effect it's best to view the CodePen on two separate locations simultaneously.
HTML:
<script src='https://cdn.firebase.com/js/client/2.0.4/firebase.js'></script>
<ul id="messages"></ul>
<input id="upload" type="file" accept="image/*" onchange="uploadImage()">
JQuery:
var dataRef = new Firebase('https://citruso.firebaseio.com/');
var messagesRef = dataRef.child('Messages');
messagesRef.on('child_added', function(snapshot) {
var message = snapshot.val();
var text = message.text;
if (text.substring(0,11) === "data:image/") {
$('#messages').append('<img class="message-image" src="' + text + '">');
}
else {
$('#messages').append('<li>' + text + '</li>');
}
});
function uploadImage() {
var file = document.querySelector('#upload').files[0];
var reader = new FileReader();
reader.onloadend = function () {
messagesRef.push({text: reader.result});
}
if (file) {
if (file.size < 10000000) {
reader.readAsDataURL(file);
}
else {
alert('File size cannot exceed 10mb.');
}
}
}

YouTube iFrame API 'onStateChange' not firing in Firefox

As of today, I'm having some difficulty getting the YouTube iFrame API onStateChange to fire in Firefox.
This appears to be a new problem - projects using the same code with the same API that were working fully last week are now not firing their onStateChange events. This issue only seems to affect Firefox - Chrome and Internet Explorer are working fully.
Is this a known bug, and is there a workaround available if it is?
(There's a similar question here, but it appears to be for a temporary bug on YouTube's side that has now been fixed. The solution posted there also doesn't seem to fix this issue.)
As an example, here's a fiddle using the basic example from Google. The player should stop after six seconds, but doesn't:
http://jsfiddle.net/wf4NW/
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
This appears to be an issue with the YouTube flash player. When flash is used (which seems to be the default) the API does not work.
However, when HTML5 mode is requested, the stateChange event does fire.
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
playerVars: {
html5: 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
Here is the OP's jsfiddle, but modified to use the HTML5 player. With the HTML5 player, the video does pause after 6 seconds like it should.

trying to save an image from Phonegap camera

I have this code which should get the base64 of the captured image, then save it as a jpg into the devices SD card, under the foler MyAppFolder. However it wont work and i cannot figure out why
<html>
<head>
<script src=../cordova.js></script>
<script>
// A button will call this function
//
function capturePhoto() {
sessionStorage.removeItem('imagepath');
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI });
}
function onPhotoDataSuccess(imageURI) {
// Uncomment to view the base64 encoded image data
// console.log(imageData);
// Get image handle
//
var imgProfile = document.getElementById('imgProfile');
// Show the captured photo
// The inline CSS rules are used to resize the image
//
imgProfile.src = imageURI;
if(sessionStorage.isprofileimage==1){
getLocation();
}
movePic(imageURI);
}
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
function movePic(file){
window.resolveLocalFileSystemURI(file, resolveOnSuccess, resOnError);
}
//Callback function when the file system uri has been resolved
function resolveOnSuccess(entry){
var d = new Date();
var n = d.getTime();
//new file name
var newFileName = n + ".jpg";
var myFolderApp = "MyAppFolder";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
//The folder is created if doesn't exist
fileSys.root.getDirectory( myFolderApp,
{create:true, exclusive: false},
function(directory) {
entry.moveTo(directory, newFileName, successMove, resOnError);
},
resOnError);
},
resOnError);
}
//Callback function when the file has been moved successfully - inserting the complete path
function successMove(entry) {
//Store imagepath in session for future use
// like to store it in database
sessionStorage.setItem('imagepath', entry.fullPath);
}
function resOnError(error) {
alert(error.code);
}
</script>
</head>
<body>
<button onclick="capturePhoto()">Take photo</button>
<img src="" id="imgProfile" style=position:absolute;top:0%;left:0%;width:100%;height:100%;>
</body>
</html>
when the button is pressed, the camera doesnt launch.
I solved it as follow. It might help you:
function capturePhoto() {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoSuccess, function(message) {
alert('Image Capture Failed');
}, {
quality : 40,
destinationType : Camera.DestinationType.FILE_URI
});
}
function onPhotoSuccess(imageURI) {
var gotFileEntry = function(fileEntry) {
alert("Default Image Directory " + fileEntry.fullPath);
var gotFileSystem = function(fileSystem) {
fileSystem.root.getDirectory("MyAppFolder", {
create : true
}, function(dataDir) {
var d = new Date();
var n = d.getTime();
//new file name
var newFileName = n + ".jpg";
// copy the file
fileEntry.moveTo(dataDir, newFileName, null, fsFail);
}, dirFail);
};
// get file system to copy or move image file to
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFileSystem,
onFail);
};
// resolve file system for image
window.resolveLocalFileSystemURI(imageURI, gotFileEntry, fsFail);
// file system fail
var onFail = function(error) {
alert("failed " + error.code);
};
var dirFail = function(error) {
alert("Directory" + error.code);
};
The button wont get clicked because your image src is overlapping it.
Change the position of image src and your code shall work fine

Resources