If I have an image in base64 ex.
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDAAwfqNRk/rjcYX+PxrV/wtWqwJSTlboMgAAAABJRU5ErkJggg==
What's the fastest way to change a filter (ex. brightness, contrast) programmatically and without creating any img or canvas tag in the view? Then once changed, convert it back to a base64 url?
You can do this by putting the image onto a HTML canvas with filters applied, then turning that canvas back into a base64 URL.
Since you never add the canvas to the document, it will never be seen.
This is how you would do it asynchronously:
This takes about 1-10ms
function applyFiltersToImage(imageURL, callBack) {
// load the image url into an image object
const image = new Image();
image.src = imageURL;
const canvas = document.createElement("canvas");
const ctx = canvas.getContext('2d');
image.onload = () => {
canvas.width = image.width;
canvas.height = image.height;
// apply css filters here
ctx.filter = 'brightness(0.5) contrast(2)';
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
// turn canvas back into a base64 image URL
callBack(canvas.toDataURL("image/png"));
}
}
You could do it synchronously if you already have the Image instance loaded.
This is how you will do it synchronously:
function applyFiltersToImageSync(imageObject) {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext('2d');
canvas.width = imageObject.width;
canvas.height = imageObject.height;
// apply css filters here
ctx.filter = 'brightness(0.5) contrast(2)';
ctx.drawImage(imageObject, 0, 0, canvas.width, canvas.height);
//turn canvas back into a base64 image
return canvas.toDataURL("image/png");
}
I have an image path which it is stored locally.
For example,
let path = 'C:\Users\Jonnie\Desktop'
How do I get the image by using JavaScript only and convert it to base64?
function imageToBase64(img)
{
var canvas, ctx, dataURL, base64;
canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL("image/png");
base64 = dataURL.replace(/^data:image\/png;base64,/, "");
return base64;
}
source
Now you just need to pass your image to there
You can use <canvas> for this.
Create a canvas and load in the image then use toDataURL() to get it in base64
The documentation for <canvas> can be found here
I have two main questions. I'm trying to resize a base64 image according to the answer in
JavaScript reduce the size and quality of image with based64 encoded code
This seemed simple enough, except for the fact that I need to get only the base64 string from that function, without the data:image... header.
I tried to modify the function like this:
function resizeBase64Img(base64, width, height) {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
var deferred = $.Deferred();
$("<img/>").attr("src", "data:image/gif;base64," + base64).load(function () {
context.scale(width / this.width, height / this.height);
context.drawImage(this, 0, 0);
deferred.resolve($("<img/>").attr("src", canvas.toDataURL()));
});
var result = canvas.toDataURL();
return result.substr(result.indexOf(",") + 1)
}
which returns a base64 string. This string is corrupted, and it never displays correctly. Why is this happening and how can I fix it?
The other question is, is there a way to resize the image based on percentage and not on pixel size?
Thanks
I ended up rewriting the function based on another canvas function I found. This function takes the src of a base64 img, modifies the size and assigns the result in base64 to another element:
function resizeBase64Img(url, width, height) {
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.scale(width/this.width, height/this.height);
ctx.drawImage(this, 0, 0);
result=canvas.toDataURL();
$('#ASSIGNEDELEMENT').val(result.substr(result.indexOf(",") + 1));
};
img.src = url;
}
And it should be invoked like this:
resizeBase64Img($('#image').attr('src'),300,300);
Hi want to resize an image using canvas but can't get it to work...
I want the image to be 100px * 100px, is there any way to solve this?
I have tried googleing and trying but can't get it to work...
I also tried changing the img size in css but this doesn't help either, please help me!
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to guess the
// original format, but be aware the using "image/jpg" will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
I also realized that I need to rotate it how can I do this?
You have to get a ratio of the width and apply it to the height.
var ratio = 100 / img.width; // 100 for desired width in px
canvas.width = img.width * ratio;
canvas.height = img.height * ratio;
ctx.drawImage(img, 0,0, canvas.width, canvas.height);
typed on phone so forgive small mistakes.
I need a way to resize pictures in JavaScript without using an HTML element.
My mobile HTML app capture photos and then converts them into base64 strings. Finally I want to resize them before they are sent to the API.
I'm looking for a different and more suitable way to resize than using a canvas element, is there a way?
A way to avoid the main HTML to be affected is to create an off-screen canvas that is kept out of the DOM-tree.
This will provide a bitmap buffer and native compiled code to encode the image data. It is straight forward to do:
function imageToDataUri(img, width, height) {
// create an off-screen canvas
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
// set its dimension to target size
canvas.width = width;
canvas.height = height;
// draw source image into the off-screen canvas:
ctx.drawImage(img, 0, 0, width, height);
// encode image to data-uri with base64 version of compressed image
return canvas.toDataURL();
}
If you want to produce a different format than PNG (default) just specify the type like this:
return canvas.toDataURL('image/jpeg', quality); // quality = [0.0, 1.0]
Worth to note that CORS restrictions applies to toDataURL().
If your app is giving only base64 encoded images (I assume they are data-uri's with base64 data?) then you need to "load" the image first:
var img = new Image;
img.onload = resizeImage;
img.src = originalDataUriHere;
function resizeImage() {
var newDataUri = imageToDataUri(this, targetWidth, targetHeight);
// continue from here...
}
If the source is pure base-64 string simply add a header to it to make it a data-uri:
function base64ToDataUri(base64) {
return 'data:image/png;base64,' + base64;
}
Just replace the image/png part with the type the base64 string represents (ie. make it an optional argument).
Ken's answer is the right answer, but his code doesn't work. I made some adjustments on it and it now works perfectly. To resize a Data URI :
// Takes a data URI and returns the Data URI corresponding to the resized image at the wanted size.
function resizedataURL(datas, wantedWidth, wantedHeight)
{
// We create an image to receive the Data URI
var img = document.createElement('img');
// When the event "onload" is triggered we can resize the image.
img.onload = function()
{
// We create a canvas and get its context.
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// We set the dimensions at the wanted size.
canvas.width = wantedWidth;
canvas.height = wantedHeight;
// We resize the image with the canvas method drawImage();
ctx.drawImage(this, 0, 0, wantedWidth, wantedHeight);
var dataURI = canvas.toDataURL();
/////////////////////////////////////////
// Use and treat your Data URI here !! //
/////////////////////////////////////////
};
// We put the Data URI in the image's src attribute
img.src = datas;
}
// Use it like that : resizedataURL('yourDataURIHere', 50, 50);
Pierrick Martellière is far the best answer, I just wanted to point that you should implement that with a async function. Once that, you would be able to do something like:
var newDataUri = await resizedataURL(datas,600,600);
This will wait for the result of the function before going to the next step. It's a cleaner way to write code. Here is the function from Pierrick with the little edit:
// Takes a data URI and returns the Data URI corresponding to the resized image at the wanted size.
function resizedataURL(datas, wantedWidth, wantedHeight){
return new Promise(async function(resolve,reject){
// We create an image to receive the Data URI
var img = document.createElement('img');
// When the event "onload" is triggered we can resize the image.
img.onload = function()
{
// We create a canvas and get its context.
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// We set the dimensions at the wanted size.
canvas.width = wantedWidth;
canvas.height = wantedHeight;
// We resize the image with the canvas method drawImage();
ctx.drawImage(this, 0, 0, wantedWidth, wantedHeight);
var dataURI = canvas.toDataURL();
// This is the return of the Promise
resolve(dataURI);
};
// We put the Data URI in the image's src attribute
img.src = datas;
})
}// Use it like : var newDataURI = await resizedataURL('yourDataURIHere', 50, 50);
For more details you can check MDN Docs : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
Yes, you can. These solutions good for resizing not just converting image to base64.
You can convert js file to image bitmap by jpg-js.And you can resize only by this lib, but in a case of resizing from very large image to very small, quality will be very bad.Best way for high-res images is to convert file to bitmap by jpg-js and then resize this bitmap by Pica lib.
You can get image data from a file by jpg-js (or draw an image on canvas)and then resize canvasImageData by resizing lib pica. (good for High-resolution images, without canvas size restriction)
You can use offscreen canvas, without attaching the canvas to a body, and resize an image. This solution will be faster but will be the worse solution for high-resolution images, for example 6000x6000 pixels. In that case, result canvas can be with bad quality or just empty, or browser can fall with memory limit exception. (good for normal and small images)
Jpg-js and Pica will not use dom elements at all. These libs are working only with image data, without dom elements (canvas and image).
About the canvas, size restriction see this post
I think this method is best way for this solution.
function base64Resize(sourceBase64, scale , callBack) {
const _scale = scale;
var img = document.createElement('img');
img.setAttribute("src", sourceBase64);
img.onload = () => {
var canvas = document.createElement('canvas');
canvas.width = img.width * _scale;
canvas.height = img.height * _scale;
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
var maxW = img.width * _scale;
var maxH = img.height * _scale;
var iw = img.width;
var ih = img.height;
var scl = Math.min((maxW / iw), (maxH / ih));
var iwScaled = iw * scl;
var ihScaled = ih * scl;
canvas.width = iwScaled;
canvas.height = ihScaled;
ctx.drawImage(img, 0, 0, iwScaled, ihScaled);
const newBase64 = canvas.toDataURL("image/jpeg", scl);
callBack(newBase64);
}
}
Important point is that you should use img.onload event.
My last suggestion (as Chris) was deemed to not answer the question as it used canvas. Because canvas is too obvious.
It's not possible to do without loading the image into memory somewhere so it can be manipulated. Why not just use a library like jimp?
import Jimp from "jimp";
async function resizeBase64Image(base64: string, targetWidth: number, targetHeight: number): Promise<string> {
// Decode the base64 image data and save it to a buffer
const imageBuffer = Buffer.from(base64, "base64");
// Use Jimp to load the image from the buffer and resize it
const image = await Jimp.read(imageBuffer);
image.resize(targetWidth, targetHeight);
// Convert the image back to a base64 data URI
const resizedImageBase64 = await image.getBase64Async(Jimp.MIME_PNG);
return resizedImageBase64;
}
You may want a resize function that returns the resized data uri:
const resizeBase64Image = (base64: string, width: number, height: number): Promise<string> => {
// Create a canvas element
const canvas = document.createElement('canvas') as HTMLCanvasElement;
// Create an image element from the base64 string
const image = new Image();
image.src = base64;
// Return a Promise that resolves when the image has loaded
return new Promise((resolve, reject) => {
image.onload = () => {
// Calculate the aspect ratio of the image
const aspectRatio = image.width / image.height;
// Calculate the best fit dimensions for the canvas
if (width / height > aspectRatio) {
canvas.width = height * aspectRatio;
canvas.height = height;
} else {
canvas.width = width;
canvas.height = width / aspectRatio;
}
// Draw the image to the canvas
canvas.getContext('2d')!.drawImage(image, 0, 0, canvas.width, canvas.height);
// Resolve the Promise with the resized image as a base64 string
resolve(canvas.toDataURL());
};
image.onerror = reject;
});
};
And simply await it like this:
const resizedImage: string = await resizeBase64Image(base64, 100, 100);
function resizeImage(base64Str) {
var img = new Image();
img.src = base64Str;
var canvas = document.createElement('canvas');
var MAX_WIDTH = 400;
var MAX_HEIGHT = 350;
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);
return canvas.toDataURL();
}
https://gist.github.com/ORESoftware/ba5d03f3e1826dc15d5ad2bcec37f7bf