I am trying to create PDF with Image. I have URL of Image as below:
var url = "https://firebasestorage.googleapis.com/v0/b/dicom-poc.appspot.com/o/images%2FNiouCzjBYna8Wx1VO2x3UST5tDc2%2F2020-10-07%2F05%3A03%3A58%2Fvisualization%2FL-CC.png?alt=media&token=dce8859a-3427-432b-8176-590e9569aad9"
and my code is here:
var pdf = new jsPDF();
var img = new Image();
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
img = document.createElement('img');
img.src = url;
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
var dataURL = canvas.toDataURL('image/png')
var base64 = dataURL.replace(/^data:.+;base64,/, '');
pdf.text("Hi");
pdf.addImage(base64,'PNG',5,5,50,50);
pdf.save("download.pdf");
}
After running above code PDF is getting downloaded successfully with text "Hi" but image is not there.
I have tried multiple solutions suggested by people but no result.
Could you please guide me for same.
Thanks in advanace!
You did not draw anything on the canvas.
var pdf = new jsPDF();
var img = new Image();
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
img = document.createElement('img');
img.src = url;
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, img.width, img.width);
var dataURL = canvas.toDataURL('image/png')
var base64 = dataURL.replace(/^data:.+;base64,/, '');
pdf.text("Hi");
pdf.addImage(base64,'PNG',5,5,50,50);
pdf.save("download.pdf");
}
I need the base64-string (not URL) from an existing PNG (photo from a text document).
I use the following function to receive base64-String for my photo. The string, which I get back, is valid but if I test it in a online decoder, I get this image:
imageResult is an image-Element in my DOM. Any hints what is going wrong?
JS
var img = this.imageResult.nativeElement;
var ocrImage = this.getBase64Image(img);
getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
I'm trying to convert a SVG file to PNG by drawing it to canvas.
var svgToCanvas = function(svgElement) {
setNameSpaceOnEl(svgElement);
appendCSSRules(svgElement, getCssRules(svgElement));
var image = new Image();
// this is ugly but will do:
var svgXml = $('<div>').append($(svgElement).clone()).html();
var b64str = btoa(unescape(encodeURIComponent(svgXml)));
// var svgXml = new XMLSerializer().serializeToString(svgElement);
var defer = $q.defer();
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
defer.resolve(canvas);
};
image.src = 'data:image/svg+xml;base64,' + b64str;
return defer.promise;
};
The problem is that even though the image handling takes place inside the onload function, Firefox yields error NS_ERROR_NOT_AVAILABLE: ... on the line
context.drawImage(image, 0, 0);.
With breakpoints I see the image.src at this point is a valid base64 string, and I can even open up the image itself.
The code above works in Chrome, but not in Firefox. Any suggestions how to get around this in Firefox?
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
I am trying to get the orientation from an exif data like this: Extract exif orientation
var img = new Image();
img.src = "data:image/jpeg;base64," + imgData;
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var bin = atob(img.src.split(',')[1]);
var exif = EXIF.readFromBinaryFile(new BinaryFile(bin));
alert(exif.Orientation);
alert(EXIF.getTag(imgData, "Orientation"));
however all it alerts is undefined.... I am not sure why.
I have included exif.js and binaryajax.js in my html file so that is not the issue