I want to convert an image to base64 from reactjs to save that image in mongo without uploading the image to the server and then converting it if not converting the image directly
I share my solution
const getEmergencyFoundImg = urlImg => {
var img = new Image();
img.src = urlImg;
img.crossOrigin = 'Anonymous';
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.height = img.naturalHeight;
canvas.width = img.naturalWidth;
ctx.drawImage(img, 0, 0);
var b64 = canvas.toDataURL('image/png').replace(/^data:image.+;base64,/, '');
return b64;
};
I recommend calling this function with async / await to build the object of the post.
The method extracts it from this source:
https://base64.guru/developers/javascript/examples/convert-image
Related
I tried with this library: https://www.npmjs.com/package/convert-svg-to-png
But it reaise an error:
import { convert } from 'convert-svg-to-png'
useEffect(() => {
let png = convert('/iStock-1188768310.svg')
console.log(png)
})
Error: Module not found: Can't resolve 'fs'
Import trace for requested module:
./node_modules/tar-fs/index.js
./node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserFetcher.js
./node_modules/puppeteer/lib/cjs/puppeteer/node/Puppeteer.js
./node_modules/puppeteer/lib/cjs/puppeteer/initialize-node.js
What do I wrong, or is it any more 'standard' way to do it? My goal is to use the image az an og:image. I heard SVG can not be used, this is why I try convert to PNG.
I tried this package also: https://github.com/canvg/canvg Like this:
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
v = await Canvg.from(ctx, './svgs/1.svg')
// Start SVG rendering with animations and mouse handling.
v.start()
But it also raise error:
TypeError: Cannot read properties of null (reading 'getContext')
24 | let cv = async () => {
25 | const canvas = document.querySelector('canvas')
> 26 | const ctx = canvas.getContext('2d')
| ^
27 |
28 | v = await Canvg.from(ctx, './sv
according to the library's npm page, the function you need to import is convertFile and not convert:
const { convertFile} = require('convert-svg-to-png');
The following code should work:
(async() => {
const inputFilePath = '/path/to/my-image.svg';
const outputFilePath = await convertFile(inputFilePath);
console.log(outputFilePath);
//=> "/path/to/my-image.png"
})();
The title says "A Node.js package for converting SVG to PNG using headless Chromium". You can only use it in nodejs not in client-side JavaScript. You may want to check this answer if you want to do it in the browser: Convert SVG to image (JPEG, PNG, etc.) in the browser.
Here you have an (client-side) example of how an SVG document can be loaded using fetch() (if the SVG is not already in the DOM), turned into a File object, drawn on a canvas and expoted as a PNG.
var svgcontainer, svg, canvas, ctx, output;
document.addEventListener('DOMContentLoaded', e => {
svgcontainer = document.getElementById('svgcontainer');
canvas = document.getElementById('canvas');
output = document.getElementById('output');
ctx = canvas.getContext('2d');
fetch('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI1MCIgZmlsbD0ib3JhbmdlIiAvPgo8L3N2Zz4KCgo=').then(res => res.text()).then(text => {
let parser = new DOMParser();
let svgdoc = parser.parseFromString(text, "application/xml");
canvas.width = svgdoc.rootElement.getAttribute('width');
canvas.height = svgdoc.rootElement.getAttribute('height');
// append SVG to DOM
svgcontainer.innerHTML = svgdoc.rootElement.outerHTML;
svg = svgcontainer.querySelector('svg');
// create a File object
let file = new File([svgdoc.rootElement.outerHTML], 'svg.svg', {
type: "image/svg+xml"
});
// and a reader
let reader = new FileReader();
reader.addEventListener('load', e => {
/* create a new image assign the result of the filereader
to the image src */
let img = new Image();
// wait for it to got load
img.addEventListener('load', e => {
// update canvas with new image
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(e.target, 0, 0);
// create PNG image based on canvas
let img = new Image();
img.src = canvas.toDataURL("image/png");
output.append(img);
});
img.src = e.target.result;
});
// read the file as a data URL
reader.readAsDataURL(file);
});
});
<div style="display:flex">
SVG:
<div id="svgcontainer"></div>
Canvas: <canvas id="canvas" width="200" height="200"></canvas>
</div>
<p>Exported PNG:</p>
<div id="output"></div>
I wanted to upload the image files, draw them into canvas, make changes and save it in the database. I tried to test the base64 value that the canvas image (Pic) returned, and it is blank. However, I see the result when I append the canvas (Pic) to the document. What am I doing wrong here?
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) {
continue;
}
// read contents of files asynchronously
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
var canvas = document.createElement("canvas");
var datauri = event.target.result,
ctx = canvas.getContext("2d"),
img = new Image();
img.onload = function() {
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
};
img.src = datauri;
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
document.body.appendChild(canvas); //picture gets uploaded
// Generate the image data
var Pic = canvas.toDataURL("image/png");
console.log(Pic); // => returns base64 value which when tested equivalent to blank
Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "")
// Sending image to Server
$.ajax({
// …
});
};
})(f);
reader.readAsDataURL(f);
}
}
My intuition says that everything from var imageData = … should go into the img.onload function.
That means, at the relevant part the code becomes:
img.onload = function() {
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
document.body.appendChild(canvas); //picture gets uploaded
// Generate the image data
var Pic = canvas.toDataURL("image/png");
console.log(Pic); // => returns base64 value which when tested equivalent to blank
Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "")
// Sending image to Server
$.ajax({
// …
});
};
img.src = datauri;
The reason is that the line
ctx.drawImage(img, 0, 0, width, height);
correctly executes after the image has been loaded. But unfortunately, you don’t wait for loading when this line gets executed:
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
and all subsequent lines.
The image needs to be loaded in order to draw it on the canvas. The canvas needs to contain the loaded image in order to call getImageData.
I found a better solution to get the base64 code
Instead of this line:
var Pic = canvas.toDataURL("image/png");
use this:
var Pic = canvas.toDataURL("image/png").split(',')[1];
I am trying to convert an external svg icon to a base64 png using a canvas. It is working in all browsers except Firefox, which throws an error "NS_ERROR_NOT_AVAILABLE".
var img = new Image();
img.src = "icon.svg";
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL;
};
Can anyone help me on this please? Thanks in advance.
Firefox does not support drawing SVG images to canvas unless the svg file has width/height attributes on the root <svg> element and those width/height attributes are not percentages. This is a longstanding bug.
You will need to edit the icon.svg file so it meets the above criteria.
As mentioned, this is an open bug caused by limitations on what Firefox accepts as specification for SVG sizes when drawing to a canvas. There is a workaround.
Firefox requires explicit width and height attributes in the SVG itself. We can add these by getting the SVG as XML and modifying it.
var img = new Image();
var src = "icon.svg";
// request the XML of your svg file
var request = new XMLHttpRequest();
request.open('GET', src, true)
request.onload = function() {
// once the request returns, parse the response and get the SVG
var parser = new DOMParser();
var result = parser.parseFromString(request.responseText, 'text/xml');
var inlineSVG = result.getElementsByTagName("svg")[0];
// add the attributes Firefox needs. These should be absolute values, not relative
inlineSVG.setAttribute('width', '48px');
inlineSVG.setAttribute('height', '48px');
// convert the SVG to a data uri
var svg64 = btoa(new XMLSerializer().serializeToString(inlineSVG));
var image64 = 'data:image/svg+xml;base64,' + svg64;
// set that as your image source
img.src = img64;
// do your canvas work
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL;
};
}
// send the request
request.send();
This is the most basic version of this solution, and includes no handling for errors when retrieving the XML. Better error handling is demonstrated in this inline-svg handler (circa line 110) from which I derived part of this method.
This isn't the most robust solution, but this hack worked for our purposes. Extract viewBox data and use these dimensions for the width/height attributes.
This only works if the first viewBox encountered has a size that accurately can represent the size of the SVG document, which will not be true for all cases.
// #svgDoc is some SVG document.
let svgSize = getSvgViewBox(svgDoc);
// No SVG size?
if (!svgSize.width || !svgSize.height) {
console.log('Image is missing width or height');
// Have size, resolve with new SVG image data.
} else {
// Rewrite SVG doc
let unit = 'px';
$('svg', svgDoc).attr('width', svgSize.width + unit);
$('svg', svgDoc).attr('height', svgSize.height + unit);
// Get data URL for new SVG.
let svgDataUrl = svgDocToDataURL(svgDoc);
}
function getSvgViewBox(svgDoc) {
if (svgDoc) {
// Get viewBox from SVG doc.
let viewBox = $(svgDoc).find('svg').prop('viewBox').baseVal;
// Have viewBox?
if (viewBox) {
return {
width: viewBox.width,
height: viewBox.height
}
}
}
// If here, no viewBox found so return null case.
return {
width: null,
height: null
}
}
function svgDocToDataURL(svgDoc, base64) {
// Set SVG prefix.
const svgPrefix = "data:image/svg+xml;";
// Serialize SVG doc.
var svgData = new XMLSerializer().serializeToString(svgDoc);
// Base64? Return Base64-encoding for data URL.
if (base64) {
var base64Data = btoa(svgData);
return svgPrefix + "base64," + base64Data;
// Nope, not Base64. Return URL-encoding for data URL.
} else {
var urlData = encodeURIComponent(svgData);
return svgPrefix + "charset=utf8," + urlData;
}
}
I've been tasked with testing some pretty heavy duty functions and unfortunately I have no idea where to start with this one.
The function in question is this one:
export async function getCroppedImg(imageSrc, pixelCrop) {
const image = await createImage(imageSrc);
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
// set width to double image size to allow for a safe area for the
// image to rotate in without being clipped by canvas context
canvas.width = image.width * 2;
canvas.height = image.height * 2;
// translate canvas context to a central location to allow rotating around the center.
ctx.translate(image.width, image.height);
ctx.translate(-image.width, -image.height);
// draw rotated image and store data.
ctx.drawImage(image, image.width / 2, image.height / 2);
const data = ctx.getImageData(0, 0, image.width * 2, image.height * 2);
// set canvas width to final desired crop size - this will clear existing context
canvas.width = pixelCrop.width;
canvas.height = pixelCrop.height;
// paste generated rotate image with correct offsets for x,y crop values.
ctx.putImageData(data, 0 - image.width / 2 - pixelCrop.x, 0 - image.height / 2 - pixelCrop.y);
// As Base64 string
// return canvas.toDataURL('image/jpeg');
// As a blob
const preview = new Promise(resolve => {
canvas.toBlob(file => {
resolve(URL.createObjectURL(file));
}, "image/jpeg");
});
const base64String = canvas.toDataURL();
return Promise.all([preview, base64String]);
}
The other function called in this one is the createImage function that looks like this:
export const createImage = url =>
new Promise((resolve, reject) => {
const image = new Image();
image.addEventListener("load", () => resolve(image));
image.addEventListener("error", error => reject(error));
image.setAttribute("crossOrigin", "anonymous"); // needed to avoid cross-origin issues on CodeSandbox
image.src = url;
});
This has already been tested to 100% coverage so I know I've got to mock it to test the getCroppedImage function but I haven't got a clue where to start with this one...
You can consider spying on createImage and mock the response as a resolved promise.
const spy = jest.spyOn(yourMockedModule, 'createImage').mockImplementation(() => Promise.resolve(....));
The drawImage function is working fine if <canvas> is defined in HTML.
Please check my JSFiddle
But, When I create the canvas using createElement('canvas') it does not work.
I have tried to convert the image to canvas in the following ways
Try 1:
$scope.canvas = document.createElement('canvas');
$scope.canvas.width = 500;
$scope.canvas.height =1000;
var ctx = $scope.canvas.getContext('2d');
var img = new Image();
img.onload = function() {
alert("image is loaded");
ctx.drawImage(img, 0, 0);
};
img.src="img/default_subject.png";
In this way the canvas shows only blank screen when tried to display using $scope.canvas.toDataURL()
Try 2:
In this try , I have just moved img.src inside of onload() function
img.onload = function() {
img.src="img/default_subject.png";
ctx.drawImage(img, 0, 0);
};
This try also not working.
Try 3:
In this try, I changed var img = new Image(); to var img = document.createElement('img')
$scope.canvas = document.createElement('canvas');
$scope.canvas.width = 500;
$scope.canvas.height =1000;
var ctx = $scope.canvas.getContext('2d');
var img = document.createElement('img');
img.onload = function() {
alert("image is loaded");
ctx.drawImage(img, 0, 0);
};
img.src="img/default_subject.png";
But, there is no breakthrough .
Please help me find the solution.
After creating the canvas element, you need to add the canvas element to the document. I have modified your JSFiddle example to use JavaScript to create the canvas element.
var canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height =1000;
document.getElementById("canvasContainer").appendChild(canvas);
var ctx = canvas.getContext('2d');
var img = document.createElement('img');
img.onload = function() {
alert("image is loaded");
ctx.drawImage(img, 0, 0);
};
img.src="http://www.download-free-wallpaper.com/img88/xpwwiirymrkfcacywpax.jpg";
<div id="canvasContainer"></div>