JSON to PNG Empty picture - javascript

Need help with my function to download a PNG from a SVG.
I read many similar post about that but don't succeed to apply to my code.
The image that I download is empty ...
My code :
function downloadCarteJPEG(nom,dpi) {
var svg = document.querySelector("svg");
var svgData = "";
if (typeof window.XMLSerializer != "undefined") {
svgData = (new XMLSerializer()).serializeToString(svg);
} else {
console.error("XMLSerializer undefined");
return;
}
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var svgSize = svg.getBoundingClientRect();
canvas.width = svgSize.width * dpi / 25.4;
canvas.height = svgSize.height * dpi / 25.4;
var data = btoa(unescape(encodeURIComponent(svgData)));
data = 'data:image/svg+xml;base64,' + data;
var image = document.createElement("img");
image.onload = function() {
ctx.drawImage(image, 0, 0);
var link = document.createElement("a");
link.download = nom;
link.href = canvas.toDataURL("image/png");
document.querySelector("body").appendChild(link);
link.click();
document.querySelector("body").removeChild(link);
};
image.src = data;
console.log("EXIT");
}

Related

Retrieve Image from File Path and Encode it to Base64

I need to convert Base64 from provided image file path. Following are conversion codes:
var encodeImageUri = function(imageUri, callback) {
var c = document.createElement('canvas');
var ctx = c.getContext("2d");
var img = new Image();
img.onload = function() {
c.width = this.width;
c.height = this.height;
ctx.drawImage(img, 0, 0);
if(typeof callback === 'function'){
var dataURL = c.toDataURL("image/jpeg");
callback(dataURL);
}
};
img.src = imageUri;
}
function getFileContentAsBase64(path,callback){
console.log(path);
window.resolveLocalFileSystemURL(path, gotFile, fail);
function fail(e) {
alert(JSON.stringify(e));
}
function gotFile(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var content = this.result;
callback(content);
};
// The most important point, use the readAsDatURL Method from the file plugin
reader.readAsDataURL(file);
});
}
}
How I use it:
var image = 'file://' + path;
getFileContentAsBase64(image, function (base64File) {});
encodeImageUri(image, function(base64){});
path example:
file:///storage/emulated/0/test.jpeg
If I print base64 result to Code Beautifier, one is corrupted with 3kb size only, and other 1 is error with broken image icon.

Processing image to display

I want to check for the size of image, and then display the image as a cropped version by defining the set size(w*h).
How can i do this?
This is the code I have tried:
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
if (fileToLoad.type.match("image.*"))
{
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var imageLoaded = document.createElement("img");
imageLoaded.src = fileLoadedEvent.target.result;
document.body.appendChild(imageLoaded);
};
fileReader.readAsDataURL(fileToLoad);
}
}
<input type="file" onchange="handleFiles(this.files[0])" id="inputFileToLoad">
<canvas id="canvas"></canvas>
function handleFiles(fileToLoad) {
if (fileToLoad.type.match("image.*")) {
var fileReader = new FileReader();
fileReader.onload = function (fileLoadedEvent) {
var img = new Image();
img.onload = function () {
var canvas = document.getElementById("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
// cropped = ctx.getImageData(x, y, crop_width, crop_height);
cropped = ctx.getImageData(500, 500, 200, 200);
// clearing is optional ... new img is over the old one
ctx.clearRect(0, 0, canvas.width, canvas.height);
// re-size canvas to croped img size
canvas.width = 200;
canvas.height = 200;
ctx.putImageData(cropped, 0, 0)
};
img.src = fileLoadedEvent.target.result;
};
fileReader.readAsDataURL(fileToLoad);
}
}
draw the imageLoaded into canvas of the size w*h shifted by some position
get the image data by yourcanvas.toDataUrl()
place the image data into image element
The function that does this
function getImagePortion(imgObj, newWidth, newHeight, startX, startY, ratio){
/* the parameters: - the image element - the new width - the new height - the x point we start taking pixels - the y point we start taking pixels - the ratio */
//set up canvas for thumbnail
var tnCanvas = document.createElement('canvas');
var tnCanvasContext = canvas.getContext('2d');
tnCanvas.width = newWidth; tnCanvas.height = newHeight;
/* use the sourceCanvas to duplicate the entire image. This step was crucial for iOS4 and under devices. Follow the link at the end of this post to see what happens when you don’t do this */
var bufferCanvas = document.createElement('canvas');
var bufferContext = bufferCanvas.getContext('2d');
bufferCanvas.width = imgObj.width;
bufferCanvas.height = imgObj.height;
bufferContext.drawImage(imgObj, 0, 0);
/* now we use the drawImage method to take the pixels from our bufferCanvas and draw them into our thumbnail canvas */
tnCanvasContext.drawImage(bufferCanvas, startX,startY,newWidth * ratio, newHeight * ratio,0,0,newWidth,newHeight);
return tnCanvas.toDataURL();
}
is step by step described here
Thank you guys,
Using Canvas is the right approach here. This is my final piece of code
Here is the final Code:
Ref Link
<html>
<title>
Upload Image
</title>
<div style="text-align: center">
<h1>: UPLOAD IMAGE : </h1>
</div>
<div>
<input type="file" id="imageLoader" name="imageLoader" onchange="checkFileDetails()"/>
<br/>
<h3>Horizontal<h3>
<canvas id="imageCanvas1"></canvas>
<br/>
<h3>Vertical<h3>
<canvas id="imageCanvas2"></canvas>
<br/>
<h3>Horizontal Small<h3>
<canvas id="imageCanvas3"></canvas>
<br/>
<h3>Gallery<h3>
<canvas id="imageCanvas4"></canvas>
</div>
<script>
//Check for the image Size and type
// Display Image in the required format
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage1, false);
var canvas1 = document.getElementById('imageCanvas1');
var ctx1 = canvas1.getContext('2d');
function handleImage1(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas1.width = 755;
canvas1.height = 450;
ctx1.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
var imageLoader1 = document.getElementById('imageLoader');
imageLoader1.addEventListener('change', handleImage2, false);
var canvas2 = document.getElementById('imageCanvas2');
var ctx2 = canvas2.getContext('2d');
function handleImage2(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas2.width = 365;
canvas2.height = 450;
ctx2.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
var imageLoader2 = document.getElementById('imageLoader');
imageLoader2.addEventListener('change', handleImage3, false);
var canvas3 = document.getElementById('imageCanvas3');
var ctx3 = canvas3.getContext('2d');
function handleImage3(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas3.width = 365;
canvas3.height = 212;
ctx3.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
var imageLoader3 = document.getElementById('imageLoader');
imageLoader3.addEventListener('change', handleImage4, false);
var canvas4 = document.getElementById('imageCanvas4');
var ctx4 = canvas4.getContext('2d');
function handleImage4(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas4.width = 380;
canvas4.height = 380;
ctx4.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
</script>

javascript resize and preview multiple image before upload

I'm newbie in JS and React. I am using React and I have multiple file input in a form, I wish if the user select image the images should be resized and previewed before user click upload. Now the resizing, previewing and uploading are all fine, the problem is when I change a file input, the other file inputs preview and upload are all changed synchronously! any help will be appreciated.
This is the code:
render():
render(){
return(
...
<label>Image1
<input type="file" id="img1" on Change={this.handleChange} />
</label>
<br/>
<img id="img1_preview" src="" height="100" />
<label>Image2
<input type="file" id="img2" on Change={this.handleChange} />
</label>
<img id="img2_preview" src="" height="100" />
...
)
}
function():
...
handleChange(event) {
...
/* handle all image input change */
if (event.target.id.includes('img')) {
var field = event.target.id;
var preview = document.getElementById(field + '_preview');
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function(readerEvent) {
var image = new Image();
image.onload = function(imageEvent) {
var canvas = document.createElement('canvas');
var max_size = 800; /* max size */
var width = image.width, height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) === -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[-1];
var raw = 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});
}
/* End Utility function to convert a canvas to a BLOB */
var resizedImage = dataURLToBlob(dataUrl);
$.event.trigger({
type: "imageResized",
blob: resizedImage,
url: dataUrl
});
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
$(document).on("imageResized",function(event1){
if (event1.blob && event1.url) {
var blob = event1.blob, url = event1.url;
# set state, later will be submit to server
this.setState({[field]:blob});
/* preview */
var reader1 = new FileReader();
reader1.addEventListener("load",function(){
preview.src = url;
}, false);
reader1.readAsDataURL(blob);
/* end preview */
}
})
}
the page:
the page image
thanks #Kaiido, according to his advise, the problem has been solved(although I don't know the exact reason).
this is the working code:
...
handleChange(event) {
...
/* handle all image input change */
if (event.target.id.includes('img')) {
var field = event.target.id;
var preview = document.getElementById(field + '_preview');
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function(readerEvent) {
var image = new Image();
image.onload = function(imageEvent) {
var canvas = document.createElement('canvas');
var max_size = 800; /* max size */
var width = image.width, height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
/* changed code */
canvas.toBlob(function(blob){
this.setState({[field]:blob});
var reader1 = new FileReader();
reader1.addEventListener("load",function(){
preview.src = dataUrl;
}, false);
reader1.readAsDataURL(blob);
});
/* end changed */
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
}

Get image dataUrl before file upload in Angularjs | ng-file-upload

I'm resizing the image before upload it to the server using HTML5 Canvas.
Also I use Angular's module ng-file-upload.
Stack on getting dataUrl of resized image. Console returns data:,
What could be the problem here?
HTML
<input type="file" ngf-select ng-model="files">
<img ngf-src="files[0]">
JS
$scope.upload = function (files) {
if (files && files.length==1) {
var file = files[0];
var img = document.createElement("img");
var canvas = document.createElement("canvas");
var reader = new FileReader();
reader.onload = function(e) {img.src = e.target.result};
reader.readAsDataURL(file);
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 200;
var MAX_HEIGHT = 150;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
console.log( dataurl );
...
He had the same problem and solve it with:
$scope.upload = function (files) {
if (files && files.length==1) {
var file = files[0];
var URL = window.URL || window.webkitURL;
var srcTmp = URL.createObjectURL(file);
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = srcTmp;

Wait while image is loaded in Javascript

I have the following problem.
function getBase64Image() {
var svg = //some svg string;
var canvas = document.createElement('canvas');
var mimetype = 'image/png';
canvas.width = 600;
canvas.height = 600;
var timg = new Image(),
ctx = canvas.getContext('2d');
timg.width = 600;
timg.height = 600;
timg.onload = function () {
document.body.appendChild(canvas);
try {
ctx.clearRect(0, 0, 600, 600);
ctx.drawImage(timg, 0, 0);
}
catch (e) {
return false;
}
var strData = canvas.toDataURL(mimetype);
document.body.removeChild(canvas);
img_data = strData;
}
timg.src = 'data:image/svg+xml;base64,' + svg;
}
return img_data;
}
Basically, I want to convert svg to png.
I have svg string, I then load image and draw it with canvas. Then I fetch base64 string for png image.
The problem I encounter is that function getBase64Image exits before image is loaded.
How can I prevent it?
Maybe use deferred or rewrite function?
I Googled, but couldn't find close answers.
Thank you.
You can't change an asynchronous function in a synchronous one.
The simplest solution is to pass a callback :
function fetchBase64Image(callback) {
var svg = //some svg string;
var canvas = document.createElement('canvas');
var mimetype = 'image/png';
canvas.width = 600;
canvas.height = 600;
var timg = new Image(),
ctx = canvas.getContext('2d');
timg.width = 600;
timg.height = 600;
timg.onload = function () {
document.body.appendChild(canvas);
try {
ctx.clearRect(0, 0, 600, 600);
ctx.drawImage(timg, 0, 0);
}
catch (e) {
return false;
}
var strData = canvas.toDataURL(mimetype);
document.body.removeChild(canvas);
img_data = strData;
callback(img_data);
}
timg.src = 'data:image/svg+xml;base64,' + svg;
}
}
And you use it like this :
fetchBase64Image(function(img_data){
// use the image img_data
}):

Categories