How to resize the image before base64 conversion - javascript

In my sencha based application i want to convert the image into base64,Before that i want to resize the original one.Here the code which i have used to convert base64
function getBase64FromImageUrl(URL)
{
var img = new Image();
img.style.width = '5%',
img.style.height = '5%',
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, 10, 10);
var dataURL = canvas.toDataURL("image/jpg");
if(App.gvars.userpic=='1')
{
cdd=dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
if(App.gvars.userpic=='2')
{
c=dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
}
}
How to resize or redimension the image before conversion?I have tried with changing img.style.width and hieght but there is no change at all.Please help me

Per devnull69's suggestion, simply use drawImage() to resize the image when you add it into the canvas.
See the API at either W3Schools or MSDN.
You can even play with the values in a live-coding example at Html5CanvasTutorials

Related

Loading image and resizing through canvas causes infinite loop

I want to get an image scaled correctly after loading it with a dummy click on a <input type='file'> and compressing it via drawing it onto a canvas. When calling a console.log() inside the img.onload I discovered it was being run in a loop. Putting the img.src = canvas.toDataURL("image/png") outside of the onload results in a blank image but no loop. Moving things around by trial and error has not been effective as I don't get the dynamics at play here (even though I can get images redrawn when rescaling a canvas). Thanks!
$('button.picture').on('click',function(){
var outerWrapper = $(this).closest('.outerWrapper')
$(this).siblings('.imageLoad').on('change', function(e){
var loadedImage = e.target.files[0]
var img = new Image();
img.src = window.URL.createObjectURL(loadedImage);
var canvas = document.createElement("canvas");
canvas.width = outerWrapper.width()
canvas.height = outerWrapper.height()
img.onload = function(e){
//still here the img.width returns the canvas width and not the original image's width
console.log(img.width)
var context = canvas.getContext("2d");
context.drawImage(img,0,0, canvas.width, canvas.height )
img.src = canvas.toDataURL("image/png")
}
$(this).closest('.outerWrapper').children('.imageWrapper').append(img)
})
$(this).siblings('.imageLoad').trigger('click')
})
To answer my own question I want to make clear what my aims were:
Load in image through a dummy click on an <input type="file">
Keeps the aspect ratio of the original image
Compress it
What worked was not setting img.src = canvas.toDataURL("image/png") as you would when resizing a canvas but by loading the original again image with URL.createObjectURL(loadedImage). To preserve the aspect ration I had to create two separate images, one to get the img.naturalWidth and img.naturalHeight for calculation and the next to load the image onto the canvas. Works a charm. Would be interested to learn where it can be refined.
$('button.picture').on('click',function(){
var outerWrapper = $(this).closest('.outerWrapper')
$(this).siblings('.imageLoad').on('change', function(e){
var loadedImage = e.target.files[0]
var img = new Image();
img.src = window.URL.createObjectURL(loadedImage);
var canvasPic = $('<canvas class="canvasPic"></canvas>')
canvasPic.prependTo(outerWrapper)
var canvas = canvasPic[0]
canvas.width = outerWrapper.width()
canvas.height = outerWrapper.height()
var context = canvas.getContext("2d");
var image = new Image();
image.onload = function(){
var w = img.naturalWidth
var h = img.naturalHeight
var ratio = h/w
var newWidth = canvas.height/ratio
context.drawImage(img,0,0,newWidth,canvas.height)
}
image.src = URL.createObjectURL(loadedImage);
})
$(this).siblings('.imageLoad').trigger('click')
})

HTML5 canvas drawImage, how to preserve image source size

function getImageBase64Data(_id)
{
var c = document.createElement('CANVAS');
var ctx = c.getContext("2d");
var img = document.getElementById(_id);
ctx.drawImage(img, 0, 0);
var dataURL = c.toDataURL();
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
I'm using HTML5 canvas to obtain base64-encoded image data. However, the resulting base64 encoded string is different and smaller than encoding the original image file with external software.
I suspect what is drawn on the canvas is the the resized/compressed image data rendered on the page, not the original source data. Is this the case, and how could I obtain the original bytes of the image? It is essential, that original bytes aren't manipulated in any way.
To make it shown without compress, change the height/width for canvas itself:
var img = new Image(); // var img = document.getElementById(_id);
img.onload = function() {
var c = document.createElement('canvas');
c.width = img.width;
c.height = img.height;
// ... other stuff
};

Javascript: Setting Image to Canvas doesn't work right

I'm basically trying to get the selected image file from a input dialog and set it to a canvas that's in my HTML. However, the image gets cropped and only a portion of the image is shown.
Javascript:
function onSS1Change(file) {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image;
img.onload = function () {
ctx.drawImage(img, 20, 20);
}
img.src = URL.createObjectURL(file.target.files[0]);
}
HTML:
<input id="ss1-inputdiag" type="file" onchange="onSS1Change(event)" />
Fiddle: http://jsfiddle.net/tdy9tqfh/
I need to get the original height and width
What am I doing wrong?
jsFiddle : http://jsfiddle.net/CanvasCode/tdy9tqfh/2/
Just update the canvas height and width to fit the image, also you were drawing your image at position x 20 and y 20 so all your images will be slightly cut off at the right side and bottom.
var input = document.getElementById('input');
input.addEventListener('change', handleFiles);
function handleFiles(e) {
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
var img = new Image;
img.src = URL.createObjectURL(e.target.files[0]);
img.onload = function() {
c.width = img.width;
c.height = img.height;
ctx.drawImage(img, 0,0);
alert('the image is drawn');
}
}

Unable to load an Image into Canvas and get base64 encoding for that image

I am trying to generate a PDF from HTML using jspdf plugin. I am stuck with loading Images into PDF. There is a function addImage() in plugin which takes base64 encoding of an image, but converting an image to base64 is not working.
I have used below two ways
//Create canvas, draw image in context and get the data url
imgToDataURL = function (img, outputFormat){
var canvas = document.createElement('canvas');
canvas.width = 20;
canvas.height = 20;
var c = canvas.getContext('2d');
c.height = img.height;
c.width=img.width;
c.drawImage(img, 0, 0);
c.save();
var dataurl = canvas.toDataURL(outputFormat);
return dataurl;
}
var img = new Image();
img.crossOrigin = 'Anonymous';
img.src = "image path"
img.height= 60;
img.width=60;
var dataURL = this.imgToDataURL(img,"image/jpeg");
renderer.pdf.addImage(dataURL, 'png',x+padding,y + this.internal.getLineHeight(),imageWidth,imageHeight);
This is printing wrong dataURL I am getting a white image. If I hard code the base64 code i.e return a hardcoded dataURL then addImage works fine. So the issue is with canvas.toDataURL which is giving me wrong output
this is the 2nd way
convertImgToBase64URL = function (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 = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
this.convertImgToBase64URL("Image Path",function(base64){
renderer.pdf.addImage(base64, 'PNG', 20, 20,48,48);
})
I have run this inside a javascript and the onload function is not even running I am not sure what is my mistake is.
Please suggest me what mistake I am doing in either way
In the first you missed assigning an onload function to your image. For that reason, the moment you try to create the dataURL, the image might not be loaded yet, ergo, the blank image. You could try changing the last few lines to this:
...
img.width=60;
img.onload = function () {
var dataURL = this.imgToDataURL(img,"image/jpeg");
renderer.pdf.addImage(dataURL, 'png',x+padding,y + this.internal.getLineHeight(),imageWidth,imageHeight);
}
img.src = "image path";
As for the second one, there seems to be a problem with the convertImgToBase64URL() which accepts 3 parameters, but you are passing 2. In you example, outputFormat parameter is undefined.

Loading Image into document.body Background

I'm attempting to pull an image (in this case, /camera/frame, which is a known-good JPG), and load it as the background of my document.body.
Here's my code thus far:
var backgroundImage = new Image();
backgroundImage.onload = function ()
{
console.log("onload");
document.body.style.backgroundImage = this.src;
};
backgroundImage.src = 'camera/frame';
"onload" prints as expected, and this.src prints out the full URL to /camera/frame, however document.body.style.backgroundImage remains "".
I believe you may be missing two things.
var path = 'path/to/image.jpg';
document.body.style.background='url('+path+')';
Canvas 2D to the rescue!
var backgroundImage = new Image();
backgroundImage.onload = function ()
{
var canvas = document.getElementById('canvas');
canvas.width = this.width;
canvas.height = this.height;
var canvasContext = canvas.getContext('2d');
canvasContext.drawImage(this, 0, 0, this.width, this.height);
};
backgroundImage.src = 'camera/frame';
backgroundImage.width = $(window).width();
backgroundImage.height = $(window).height();
Loads the image in the background, then draws it into the canvas seamlessly!

Categories

Resources