Right now i am uploading image into canvas and after uploaded image, canvas converted into image by toDataURl. If i am converting canvas into image by toDataURL then i am getting base code(Base Code will be big). I want some small url instead of BaseCode.
var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
var img = document.createElement('img');
img.src = data;
img.onload = function () {
if (img.width < 300 || img.height < 300)
{
alert("upload image should be greater");
canvas.getActiveObject().remove();
}
};
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({left: 50, top: 100,width:100, height:100, angle: 00}).scale(0.9);
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
console.log("aaaaaaaaaaa" + dataURL);
// console.log("Canvas Image " + dataURL);
// document.getElementById('txt').href = dataURL;
});
};
reader.readAsDataURL(file);
});
document.querySelector('#txt').onclick = function (e) {
e.preventDefault();
canvas.deactivateAll().renderAll();
document.querySelector('#preview').src = canvas.toDataURL();
var b= canvas.toDataURL();
console.log(b);
}
canvas{
border: 1px solid black;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file">
<canvas id="canvas" width="400" height="400"></canvas>
Click Me!!
<br />
<img id="preview" />
JSFiddle: https://jsfiddle.net/varunPes/8gt6d7op/23/
The devil is in the details - nowhere in the question do you even suggest you want to send the image somewhere - the code below is limited to the client - you can only use the short form url on the client, and as mentioned in a comment, only for a session (restart browser, url is useless), or until revokeObjectURL is called
You can - if the browser supports it, use a Blob, it's URL is short
// converts a dataURI to a Blob
function dataUriToBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var arrayBuffer = new ArrayBuffer(byteString.length);
var _ia = new Uint8Array(arrayBuffer);
for (var i = 0; i < byteString.length; i++) {
_ia[i] = byteString.charCodeAt(i);
}
var dataView = new DataView(arrayBuffer);
var blob = new Blob([dataView], { type: mimeString });
return blob;
}
// cross browser cruft
var get_URL = function () {
return window.URL || window.webkitURL || window;
};
// ... your code, which eventually does this
var b = canvas.toDataURL();
// get an URL from the Blob
var blob = dataUriToBlob(b);
var url = get_URL().createObjectURL(blob);
console.log(url);
//
// ... when finished with the object URL
URL.revokeObjectURL(url);
If you want to avoid send dataURL, you can convert it into DataForm using this function:
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
Then, call it:
var dataURL = canvas.toDataURL('image/jpeg', 0.5);
var blob = dataURItoBlob(dataURL);
var fd = new FormData(document.forms[0]);
fd.append("canvasImage", blob);
Finally, send this form (regular or ajax).
Source answer
Related
I tried to load images into several canvas elements, but only the last image was loaded from the list of files. I need different images in different canvas elements, each in its own. Thanks for help.
HTML
<input type='file' id='imgfile' multiple />
The canvas element will be created by jQuery.
JavaScript
function loadImage(picture) {
var canvas = document.querySelectorAll('canvas');
var input, fr, file, img;
input = document.getElementById('imgfile');
$.each(canvas, function(i, v) {
file = input.files[i];
fr = new FileReader();
fr.onload = function createImage() {
img = new Image();
img.onload = function imageLoaded() {
var ctx = canvas[i].getContext("2d");
ctx.drawImage(img, 0, 0, 50, 50);
}
img.src = fr.result;
}
fr.readAsDataURL(file);
});
}
$("input").change(function() {
var picture = this.files;
var leng = picture.length;
for (var i = 0; i < picture.length; i++) {
$("input").after('<canvas width="50" height="50" style="border:1px solid red"></canvas>');
}
loadImage();
});
You need to declare variables inside iteratee function
function loadImage(picture) {
var canvas = document.querySelectorAll('canvas');
var input = document.getElementById('imgfile');
$.each( canvas, function( i, v) {
var file = input.files[i];
var fr = new FileReader(); // file reader per file
fr.onload = function createImage() {
var img = new Image(); // image per file
img.onload = function imageLoaded() {
var ctx = canvas[i].getContext("2d");
ctx.drawImage(img,0,0, 50, 50);
}
img.src = fr.result;
}
fr.readAsDataURL(file);
});
}
We are building an application where the user can upload images, but I need to resize an image before I can upload them to the server. The input for the file is an input[type=file] and we check if the image is valid. If it is valid, we continue with the following request:
Upload.upload({url: url, data: {file: input.x}, headers: {'Authorization': token}});
The input variable is the value of the input field in the HTML. This codes works great when we don't need to resize the image. Unfortunately, this would only be the case in a perfect world. After a while searching for the same problems, I seem to have found the solution using the following function:
var resize = function(size, url, callback) {
var temp = new Image();
temp.onload = function() {
var target = { width: temp.width, height: temp.height, aspect: temp.width / temp.height };
if (temp.width > temp.height) {
size = Math.min(temp.width, size);
target.width = size; target.height = size / target.aspect;
} else {
size = Math.min(temp.height, size);
target.height = size; target.width = size * target.aspect;
}
var canvas = document.createElement('canvas');
canvas.width = target.width; canvas.height = target.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0, temp.width, temp.height, 0, 0, target.width, target.height);
callback(canvas.toDataURL(url.split(',')[0].split(':')[1].split(';')[0]));
}; temp.src = url;
}
This appears to be working great. I need to pass a Base64 string. So I wrapped the upload method inside the following:
var reader = new FileReader();
reader.onload = function(e) {
resize(1000, e.target.result, function(done) {
console.log(done);
Upload.upload({url: url, data: {file: done}, headers: {'Authorization': UserService.getToken()}});
});
}
reader.readAsDataURL(file);
This way I pass a Base64 string containing the image and even this seems to be working like a charm. But the biggest problem is, the server expects a real file and not a Base64 string. So the upload itself fails.
I found the function on Convert Data URI to File then append to FormData which should fix this, but it doesn't. I changed the method to this after adding the method from the link:
var reader = new FileReader();
reader.onload = function(e) {
resize(1000, e.target.result, function(done) {
console.log(done);
Upload.upload({url: url, data: {file: dataURItoBlob(done)}, headers: {'Authorization': UserService.getToken()}});
});
}
reader.readAsDataURL(file);
Does any of you know how I could change the Base64 string back to a file again? I found tons of post explaining how I could show them in a browser, but none solving my problem to upload it as file.
Sorry for the question. But it seems the dataURItoBlob function works fine, but there is was no original filename inside the blob, so I couldn't upload it right away. I changed the resize function so it performs both actions at once and this is the result:
var resize = function(size, url, name, callback) {
var temp = new Image();
temp.onload = function() {
var target = { width: temp.width, height: temp.height, aspect: temp.width / temp.height };
if (temp.width > temp.height) {
size = Math.min(temp.width, size);
target.width = size; target.height = size / target.aspect;
} else {
size = Math.min(temp.height, size);
target.height = size; target.width = size * target.aspect;
}
var canvas = document.createElement('canvas');
canvas.width = target.width; canvas.height = target.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0, temp.width, temp.height, 0, 0, target.width, target.height);
var type = url.split(',')[0].split(':')[1].split(';')[0];
var data = canvas.toDataURL(type);
//callback(data);
var bytes = (data.split(',')[0].indexOf('base64') >= 0) ? atob(data.split(',')[1]) : unescape(dataURI.split(',')[1]);
var ia = new Uint8Array(bytes.length);
for(var i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i); }
var blb = new Blob([ia], {type : type});
blb.name = name;
callback(blb);
}; temp.src = url;
};
To upload the file, I do the following:
var deferred = $q.defer();
var reader = new FileReader();
reader.onload = function(e) {
resize(maxSize, e.target.result, image.name, function(done) {
deferred.resolve(Upload.upload({url: url, data: {file: done}, headers: {'Authorization': token}));
});
}
reader.readAsDataURL(image);
return deferred.promise;
My scenario is:
On clicking a button, import datas on a html into a PDF file.
Since this PDF must have some complicated required style, so my first step is to transfer this page into a image using html2canvas.js and then import this image to a PDF with jsPDF.js
And when the data is too large the PDF must be split to hold all the data,to do this,so I used the codes here: https://github.com/MrRio/jsPDF/pull/397
My problem is: on firefox the splited page on PDF on page 2 or 3...cannot be shown, they are totally blank. but on page 1 it is fine. (this is for firefox)
I tested other browsers they are all fine. pls someone could throw some light on how to fix this?
Here is my plnkr:
http://plnkr.co/edit/ElvAsriK2nssq2U9pgKX?p=preview
function initTemplate(){
datas=getData();
var templateData=_.template($('#tpl').html(), datas);
$('#tplW').html(templateData);
getPDF();
// $('#tplW').append(_.template($('#tpl').html(), datas));
// $('body').html( _.template($('#tpl').html(), datas));
}
function getData(){
var htmlData=$(".MsoNormalTable .inner").find("tr.tablerow");
var datas=[];
$.each(htmlData,function(i,v){
var d=[];
var tds=$(v).find("td");
$.each(tds,function(index,val){
d.push($(val).text());
});
datas.push(d);
});
return datas;
}
function getPDF() {
// initTemplate();
html2canvas($('#tplW')[0], {
onrendered: function(canvas){
canvasToImageSuccess(canvas);
}
});
function canvasToImage (canvas){
var img = new Image();
var dataURL = canvas.toDataURL('image/png');
img.src = dataURL;
return img;
};
function canvasShiftImage (oldCanvas,shiftAmt){
shiftAmt = parseInt(shiftAmt) || 0;
if(!shiftAmt){ return oldCanvas; }
var newCanvas = document.createElement('canvas');
newCanvas.height = oldCanvas.height - shiftAmt;
newCanvas.width = oldCanvas.width;
var ctx = newCanvas.getContext('2d');
var img = canvasToImage(oldCanvas);
ctx.drawImage(img,0, shiftAmt, img.width, img.height, 0, 0, img.width, img.height);
return newCanvas;
};
function canvasToImageSuccess (canvas){
var pdf = new jsPDF('l','px'),
pdfInternals = pdf.internal,
pdfPageSize = pdfInternals.pageSize,
pdfScaleFactor = pdfInternals.scaleFactor,
pdfPageWidth = pdfPageSize.width,
pdfPageHeight = pdfPageSize.height,
totalPdfHeight = 0,
htmlPageHeight = canvas.height,
htmlScaleFactor = canvas.width / (pdfPageWidth * pdfScaleFactor),
safetyNet = 0;
while(totalPdfHeight < htmlPageHeight && safetyNet < 15){
var newCanvas = canvasShiftImage(canvas, totalPdfHeight);
pdf.addImage(newCanvas, 'png', 0, 0, pdfPageWidth, 0, null, 'NONE');
totalPdfHeight += (pdfPageHeight * pdfScaleFactor * htmlScaleFactor);
if(totalPdfHeight < htmlPageHeight){
pdf.addPage();
}
safetyNet++;
}
pdf.save('test.pdf');
};
}
You should use canvas-to-blob and FileSaver.js
and modify this line:
pdf.save('test.pdf');
to this:
var data = pdf.output();
var buffer = new ArrayBuffer(data.length);
var array = new Uint8Array(buffer);
for (var i = 0; i < data.length; i++) {
array[i] = data.charCodeAt(i);
}
var blob = new Blob(
[array],
{type: 'application/pdf', encoding: 'raw'}
);
saveAs(blob, "test.pdf");
You can check it out here.
It worked for me on Mac, Firefox.
I found this solution here.
I try to convert a canvas image into a blob. This can be done with the toBlob() polyfile.
It works on desktop browsers but on iPhone I do not get any blob. The size is always zero.
Here is a JsFiddle for this: http://jsfiddle.net/confile/h7zV3/
How do I get the Blob from the canvas on the iPhone?
Here is the code I used:
<input id="file" type="file" />
<img id="img">
<br>canvas<br>
<canvas id="mycanvas" ></canvas>
<script type="text/javascript">
$(function(){
var $inputFile = $("#file"),
inputFile = $inputFile[0],
$img = $("#img"),
img = $img[0];
var tmpImage = img; // document.createElement("img");
$inputFile.on("change", function() {
var files = inputFile.files;
if (!files || !files.length)
return
var reader = new FileReader()
reader.onload = function(progressEvent) {
console.log("reader.result: "+reader.result);
tmpImage.onload = function() {
var canvas = $("#mycanvas")[0]; //document.createElement("canvas"),
context = canvas.getContext("2d");
canvas.width = this.width;
canvas.height = this.height;
context.drawImage(this, 0, 0);
var dataUrlValue = canvas.toDataURL(); //canvas.toDataURL("image/jpeg");
alert(dataUrlValue);
var myBlob1 = dataURItoBlob(dataUrlValue);
console.log(myBlob1);
alert(myBlob1.size);
canvas.toBlob(function(blob) {
console.log("done");
alert(blob.size);
}, 'image/jpeg');
}; // end onload
tmpImage.src = reader.result;
};
reader.readAsDataURL(files[0]);
});
}); // end JQuery
</script>
Use this plugin JavaScript-Canvas-to-Blob to convert canvas elements into Blob objects.
Then use the canvas.toBlob() method in the same way as the native implementation
You may use.
var data = context.getImageData(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
Each element of the returned array is a byte of the image, considering the image is 3 bytes per pixel in the order RGB.
for(var i = 0; i < data.length; i++) {
// do something for saving the data (bytes) in the format you need
// ... if you need to
}
I noticed when uploading a profile pic to Twitter that its size is checked before upload. Can anyone point me to a solution like this?
Thanks
If you're checking the file size you can use something like uploadify to check the file size before upload.
Checking the actual file dimensions (height / width) may need to be done on the server.
I think it is impossible unless you use a flash. You can use uploadify or swfupload for such things.
I have tested this code in chrome and it works fine.
var x = document.getElementById('APP_LOGO'); // get the file input element in your form
var f = x.files.item(0); // get only the first file from the list of files
var filesize = f.size;
alert("the size of the image is : "+filesize+" bytes");
var i = new Image();
var reader = new FileReader();
reader.readAsDataURL(f);
i.src=reader.result;
var imageWidth = i.width;
var imageHeight = i.height;
alert("the width of the image is : "+imageWidth);
alert("the height of the image is : "+imageHeight);
Something like this should cope with forms loaded asynchronously, inputs with or without "multiple" set and avoid the race conditions that happen when using FileReader.readAsDataURL and Image.src.
$('#formContainer').on('change', '#inputFileUpload', function(event) {
var file, _fn, _i, _len, _ref;
_ref = event.target.files;
_fn = function(file) {
var reader = new FileReader();
reader.onload = (function(f) {
return function() {
var i = new Image();
i.onload = (function(e) {
var height, width;
width = e.target.width;
height = e.target.height;
return doSomethingWith(width, height);
});
return i.src = reader.result;
};
})(file);
return reader.readAsDataURL(file);
};
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
file = _ref[_i];
_fn(file);
}
});
Note: Needs jQuery, HTML5, hooks to a structure like:
<div id="formContainer">
<form ...>
...
<input type="file" id="inputFileUpload"></input>
...
</form>
</div>
You need check image Width and Height when Image onload.
var img = new Image;
img.src = URL.createObjectURL(file);
img.onload = function() {
var picWidth = this.width;
var picHeight = this.height;
if (Number(picWidth) > maxwidth || Number(picHeight) > maxheight) {
alert("Maximum dimension of the image to be 1024px by 768px");
return false;
}
}
This works perfectly for me
var _URL = window.URL || window.webkitURL;
$("#file").change(function(e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function() {
if((this.width < 800)||(this.height < 400)){
alert('Image too small. Images must be bigger than 800 x 400');
$('#file').val('');
}
};
img.onerror = function() {
alert( "not a valid file: " + file.type);
};
img.src = _URL.createObjectURL(file);
}
});
Kudos to the original creator: http://jsfiddle.net/4N6D9/1/
I modified this to specify the min width and height of an upload.