Unknown background green lines in React downloaded image? - javascript

I'm using the below code to download screenshots of my application:
download = filename => {
const a = document.createElement('a');
a.download = filename;
getDownloadURL().then(url => {
a.href = url;
document.body.appendChild(a);
a.click();
a.remove();
});
};
getDownloadURL = async () => {
const svg = document.querySelector('#widget svg'),
canvas = new OffscreenCanvas(svg.clientWidth * 3, svg.clientHeight * 3),
svgString = new XMLSerializer().serializeToString(svg),
ctx = canvas.getContext('2d'),
v = await Canvg.fromString(ctx, svgString, presets.offscreen());
await v.render();
const blob = await canvas.convertToBlob(),
pngUrl = URL.createObjectURL(blob);
return pngUrl;
},
The downloaded image has few unknown green lines at the background, what are these?
And how can these be removed?
This element appears fine in the application without these unknown lines.

Related

Convert Image uri into Base64 [duplicate]

Using an Image File, I am getting the url of an image, that needs be to send to a webservice. From there the image has to be saved locally on my system.
The code I am using:
var imagepath = $("#imageid").val();// from this getting the path of the selected image
that var st = imagepath.replace(data:image/png or jpg; base64"/"");
How to convert the image url to BASE64?
HTML
<img id="imageid" src="https://www.google.de/images/srpr/logo11w.png">
JavaScript
function 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\/?[A-z]*;base64,/);
}
var base64 = getBase64Image(document.getElementById("imageid"));
Special thanks to #Md. Hasan Mahmud for providing an improved regex that works with any image mime type in my comments!
This method requires the canvas element, which is perfectly supported.
The MDN reference of HTMLCanvasElement.toDataURL().
And the official W3C documentation.
View this answer: https://stackoverflow.com/a/20285053/5065874 by #HaNdTriX
Basically, he implemented this function:
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
And in your case, you can use it like this:
toDataUrl(imagepath, function(myBase64) {
console.log(myBase64); // myBase64 is the base64 string
});
In todays JavaScript, this will work as well..
const getBase64FromUrl = async (url) => {
const data = await fetch(url);
const blob = await data.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
const base64data = reader.result;
resolve(base64data);
}
});
}
getBase64FromUrl('https://lh3.googleusercontent.com/i7cTyGnCwLIJhT1t2YpLW-zHt8ZKalgQiqfrYnZQl975-ygD_0mOXaYZMzekfKW_ydHRutDbNzeqpWoLkFR4Yx2Z2bgNj2XskKJrfw8').then(console.log)
This is your html-
<img id="imageid" src="">
<canvas id="imgCanvas" />
Javascript should be-
var can = document.getElementById("imgCanvas");
var img = document.getElementById("imageid");
var ctx = can.getContext("2d");
ctx.drawImage(img, 10, 10);
var encodedBase = can.toDataURL();
'encodedBase' Contains Base64 Encoding of Image.
You Can Used This :
function ViewImage(){
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
var file = document.querySelector('input[type="file"]').files[0];
getBase64(file).then(data =>$("#ImageBase46").val(data));
}
Add To Your Input onchange=ViewImage();
I try using the top answer, but it occur Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
I found this is because of cross domain problems, the solution is
function convert(oldImag, callback) {
var img = new Image();
img.onload = function(){
callback(img)
}
img.setAttribute('crossorigin', 'anonymous');
img.src = oldImag.src;
}
function getBase64Image(img,callback) {
convert(img, function(newImg){
var canvas = document.createElement("canvas");
canvas.width = newImg.width;
canvas.height = newImg.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(newImg, 0, 0);
var base64=canvas.toDataURL("image/png");
callback(base64)
})
}
getBase64Image(document.getElementById("imageid"),function(base64){
// base64 in here.
console.log(base64)
});
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<script type='text/javascript'>
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
let baseImage = new Image;
baseImage.setAttribute('crossOrigin', 'anonymous');
baseImage.src = your image url
var canvas = document.createElement("canvas");
canvas.width = baseImage.width;
canvas.height = baseImage.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(baseImage, 0, 0);
var dataURL = canvas.toDataURL("image/png");
Additional information about "CORS enabled images": MDN Documentation
imageToBase64 = (URL) => {
let image;
image = new Image();
image.crossOrigin = 'Anonymous';
image.addEventListener('load', function() {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
try {
localStorage.setItem('saved-image-example', canvas.toDataURL('image/png'));
} catch (err) {
console.error(err)
}
});
image.src = URL;
};
imageToBase64('image URL')
Here's the Typescript version of Abubakar Ahmad's answer
function imageTo64(
url: string,
callback: (path64: string | ArrayBuffer) => void
): void {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
xhr.onload = (): void => {
const reader = new FileReader();
reader.readAsDataURL(xhr.response);
reader.onloadend = (): void => callback(reader.result);
}
}
Just wanted to chime in and post how I did it. This is basically #Haialaluf's approach but a bit shorter:
const imageUrlToBase64 = async (url) => {
const data = await fetch(url)
const blob = await data.blob();
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = () => {
const base64data = reader.result;
return base64data
}
}

How to download a GIF from a given URL using Javascript

I am trying to download a GIF from Giphy (just need to download it, I don't need to display it on the browser).
I tried using the solution in this question this question however it downloads a static image:
function download_img(e, link){
var image = new Image();
image.crossOrigin = "anonymous";
image.src = link;
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
var blob;
// ... get as Data URI
if (image.src.indexOf(".jpg") > -1) {
blob = canvas.toDataURL("image/jpeg");
} else if (image.src.indexOf(".png") > -1) {
blob = canvas.toDataURL("image/png");
} else if (image.src.indexOf(".gif") > -1) {
blob = canvas.toDataURL("image/gif");
} else {
blob = canvas.toDataURL("image/png");
}
tempbtn = document.createElement('a');
tempbtn.href = blob;
tempbtn.download = 'giphy.gif'; // or define your own name.
tempbtn.click();
tempbtn.remove();
};
}
<a href="#" onclick="download_img(this,'https://media2.giphy.com/media/DvyLQztQwmyAM/giphy.gif?cid=e9ff928175irq2ybzjyiuicjuxk21vv4jyyn0ut5o0d7co50&rid=giphy.gif')" > Descargar gif </a>
I also wonder why it's needed to create a new Image(); and create a canvas tag
This works for me, I took some of the code from here
https://randomtutes.com/2019/08/02/download-blob-as-file-in-javascript/
(async () => {
//create new a element
let a = document.createElement('a');
// get image as blob
let response = await fetch('https://media2.giphy.com/media/DvyLQztQwmyAM/giphy.gif?cid=e9ff928175irq2ybzjyiuicjuxk21vv4jyyn0ut5o0d7co50&rid=giphy.gif');
let file = await response.blob();
// use download attribute https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Attributes
a.download = 'myGif';
a.href = window.URL.createObjectURL(file);
//store download url in javascript https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes#JavaScript_access
a.dataset.downloadurl = ['application/octet-stream', a.download, a.href].join(':');
//click on element to start download
a.click();
})();
I managed to get this working in Chrome and Firefox too by appending a link to the to document.
var link = document.createElement('a');
link.href = 'images.jpg';
link.download = 'Download.jpg';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

How to create an Image file from dataURL and save it?

I have found a way to save it as PDF but now I need to save it as Image.
This is my code:
function downloadCert()
{
html2canvas($('#canvas'), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL("image/jpeg");
console.log(imgData);
var pdf = new jsPDF();
pdf.addImage(imgData, 'JPEG', 0, 0, -180, -180);
pdf.save("download.pdf");
}
});
}
const downloadFile = () => {
const imgUri = 'data:image/gif;base64,R0lGODlhPQBEA....' //Image base64 uri
const link = document.createElement('a')
document.body.appendChild(link)
link.href = imgUri
link.target = '_self'
link.fileName = 'test_file_download.gif'
link.download = true
link.click()
}
The format in base64 string and the file extension should match for file to open properly. In above case, it's gif
Use this:
function blobCallback(fileName) {
return function(b) {
var a = document.createElement('a');
a.download = fileName+ '.jpeg';
a.href = window.URL.createObjectURL(b);
a.click();
}
}
$('#canvas').toBlob(blobCallback('DownloadFileName'), 'image/jpeg');

Download canvas as image not working in firefox and microsoft edge

I want to download canvas as image but not working in firefox and microsoft edge but working with chrome
This is my code :
DownloadImage = (i) => {
var _this = this;
this.modeler.saveSVG(function (err, svg) {
if (err) console.log(err)
_this.setState({ datasvg: svg }, function () {
const canvas = _this.refs.canvasforimage;
const options = {
log: false,
ignoreMouse: true,
};
canvg(canvas, this.state.datasvg, options);
const image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
const element = document.createElement("a");
element.setAttribute('download', 'diagram.png');
element.setAttribute('href', image);
element.click();
are there any solution ?
This is the code I use to save canvas contents as PNG image file:
canvas.toBlob(blob => {
var a = document.createElement("a"),
url = URL.createObjectURL(blob);
a.href = url;
a.download = "image.png";
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
});

how to add text in canvas with react and canvg library?

i'm trying to add text in canvas ( bottom right ) with react and canvg lib
This is what i try :
DownloadImage = (i) => {
var _this = this;
this.modeler.saveSVG(function (err, svg) {
if (err) console.log(err)
_this.setState({ datasvg: svg }, function () {
const canvas = _this.refs.canvasforimage;
console.log(canvas)
const options = {
log: false,
ignoreMouse: true
};
canvg(canvas, this.state.datasvg, options);
const image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
const element = document.createElement("a");
element.setAttribute('download', 'diagram.png');
element.setAttribute('href', image);
element.click();
})
})
}
render = () => {
return (
<canvas ref="canvasforimage" id="canvasforimage">
{/* <div style="position:absolute;right:0;bottom:0">Text</div> */} Not working
</canvas>
)
function above is working... i can download as image but code at render the one i commented not working
thanks for the comment #Chris G
so i already solve the problem by adding code after canvg
canvg(canvas, this.state.datasvg, options);
const ctx = canvas.getContext('2d');
ctx.fillText('Hello world',50, 50);

Categories