I'm getting svg flag from the json api and converting it into base64 svg but I want the result base64 in png format, is this possible to get base64 in png from svg image url?
Here is my code
let tabsCol = document.createElement('div');
tabsCol.className = 'tabsColumn';
function countries(){
let fetchRes = fetch(
"https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/index.json");
// fetchRes is the promise to resolve
// it by using.then() method
fetchRes.then(res =>
res.json()).then(d => {
// console.log(d)
for(let i=0;i<d.length;i++){
// console.log(`${d[i]['image']}`)
flag += `<fieldset id="orientationform">
<div>
<input type="radio" id="${d[i]['code']}" class="orientation-input" name="orientation4" value="${d[i]['name']}" onchange="getSelectedFlag('${d[i]['image']}')">
<label for="${d[i]['code']}"><span></span></label>
</div>
<div>
<strong>${d[i]['name']}</strong> <br>
</div>
<img src="${d[i]['image']}" srcset="${d[i]['image']},
${d[i]['image']}" width="40" height="40" alt="${d[i]['value']}">
</fieldset>
`
}
})
}
flagTab.onclick = function(){
flag = ``;
countries()
setTimeout(() => {
// console.log('flag',flag)
if(flagTabContent.children.length == 0){
tabsCol.innerHTML = flag;
flagTabContent.append(tabsCol);
}
}, 100);
}
function getSelectedFlag(url){
// console.log(url)
getBase64FromUrl(url).then(data=>{
console.log(`flag:${data}`);
app.contentWindow.postMessage(`flag:${data}`,'*');
});
}
The data variable returns the base64 in svg format but I want base64 in png format.
How can I do this?
Any help will be highly appriciated.
Thank you.
Related
Sir i'm creating a javascript application with face-api.js
Face-api.js working fine , but i don't know to place or add text filed which have written age and gender value,
here is my javascript code:
Promise.all([
faceapi.nets.faceRecognitionNet.loadFromUri('weights'),
faceapi.nets.faceLandmark68Net.loadFromUri('weights'),
faceapi.nets.ageGenderNet.loadFromUri('weights'),
faceapi.nets.ssdMobilenetv1.loadFromUri('weights')
])
.then(uploadImage)
// upload image
function uploadImage() {
console.log("Modals Loaded")
const con = document.querySelector('.container');
const input = document.querySelector('#myImg')
const imgFile = document.querySelector('#myFile')
var can;
var img;
imgFile.addEventListener("change", async ()=>{
if(can) {can.remove();}
if(img) {img.remove();}
// creating a html Element from Blob data
img = await faceapi.bufferToImage(imgFile.files[0])
input.src = img.src;
const result = await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceDescriptors().withAgeAndGender();
console.log(result)
const faceMatcher = new faceapi.FaceMatcher(result);
result.forEach(fd=>{
const { age, gender, genderProbability } = fd
const bestMatch= faceMatcher.findBestMatch(fd.descriptor)
console.log(bestMatch)
console.log(age, "age")
console.log(gender,"gender")
})
// canvas created
can = faceapi.createCanvasFromMedia(input);
con.append(can);
faceapi.matchDimensions(can,{width: input.width,height: input.height})
// resizing box
const detectionsForSize = faceapi.resizeResults(result,{width: input.width,height: input.height})
const box = result[0].detection.box;
console.log("detectionsForSize",detectionsForSize)
const facebox =new faceapi.draw.DrawBox(box);
faceapi.draw.drawDetections(can,detectionsForSize,Math.round(detectionsForSize[0].age));
})
}
And Here is Html Code
<div class="container">
<div id="im">
<img src="" alt="photo" id="myImg">
</div>
</div>
<input type="file" id="myFile" onchange="uploadImage()" accept=".jpg,.jpeg,.png">
I have tried but i can't achive that ?
I tried to get random images from unsplash api by given code below, now i am looking for to way to DOWNLOAD displayed image from that Api
const numItemsToGenerate = 1;
function renderItem(){
fetch(`https://source.unsplash.com/920x720?
beach`).then((response)=> {
let item = document.getElementById('container');
item.innerHTML = `
<img class="beach_image" src="${response.url}"
alt="beach image"/>
`
})
}
for(let i=0;i<numItemsToGenerate;i++){
renderItem();
}
I have created a function, that downloads the image from the unsplash. But the problem is, it doesn't work on Stackoverflow's snippet, since is creates null blob URL. You need to run this program on a server (like localhost), in order to work.
Try it on - https://jsfiddle.net/xt5wb2vn/
HTML
<div id="container">
</div>
<button class="download">Click to download</button>
JavaScript
const numItemsToGenerate = 1;
function downloadImage(url) {
let a = document.createElement("a");
a.href = url;
a.download = 'image.jpg';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
function renderItem() {
fetch(`https://source.unsplash.com/920x720?beach`)
.then(resp => resp.blob())
.then(image => {
const image_url = URL.createObjectURL(image)
let item = document.getElementById('container');
item.innerHTML = `<img class="beach_image" src="${image_url}" alt="beach image"/>`;
return image_url;
}).then(url=>document.querySelector(".download").onclick = ()=>downloadImage(url))
}
renderItem()
Use URL.createObjectURL
So, the function should look like
fetch(`https://source.unsplash.com/920x720?beach`)
.then(resp => resp.blob())
.then(image => {
const image_url = URL.createObjectURL(image)
const item = document.getElementById('container')
item.src = image_url
})
How can I read a stream from the api to display it in the src of an img tag ?
With this response I just want to display it in a <img src="myStream" />
My first error was to try to display a pdf file in an <img/> tag. I used an <iframe /> instead.
Also I had to use fetch to make the request and after use response.blob() :
const myFunctionToConvertHttpResponseToFileUrl = () => async {
const response = await fetch('myurl.com')
const myBlob = response.blob()
this.fileURL = URL.createObjectURL(myBlob);
}
And After in the html
<iframe :src="fileUrl" type="application/pdf" />
I wish to display an input element's selected image. Can this be performed on a local file, accessing the image client side, or would I need to upload the image to a server?
Here's my attempt in React. I can access the correct file name from the input element using inputElem.files[0].name. As soon as I am trying to set an image element to it, the broken image icon is displayed, and no error is surfaced.
const App = () => {
// state to keep track of img elements src. The default works fine.
const [imgSrc, setImgSrc] = useState('/images/test.jpg')
function handleImgUpload() {
const url = '/images/' + e.target.files[0].name
setImgSrc(url)
console.log(url) // /images/26e3e793-98f5-4720-9f82-8963276d5e27.JPG
}
function handleImgLoadSuccess() {
console.log('image loaded!')
}
function handleImgLoadError() {
console.log('image not loaded')
}
return (
<div>
<div>
<label htmlFor="img">Select an image:</label>
<input
type="file"
id="img"
name="img"
accept="image/png, image/jpeg"
onChange={(e) => handleImgUpload(e)}
/>
</div>
<img
src={imgSrc}
alt="Your upload"
onLoad={handleImgLoadSuccess}
onError={handleImgLoadError}
/>
</div>
)
}
In the console, however, the url seems to be correct.
<img src="/images/26e3e793-98f5-4720-9f82-8963276d5e27.JPG" height="100" width="200" alt="Input" class="jsx-855240488">
Hey – I see what you're trying to do, but it doesn't look like this will work. You need to create a new file reader.
const showTempImage = (e) => {
const file = e.target.files[0];
const img = document.createElement("img");
const reader = new FileReader();
reader.addEventListener('load', (e) => {
img.src = e.target.result;
});
reader.readAsDataURL(file);
// Append the img tag to the dom somewhere
}
This did the trick by creating a correct blob url.
const inputImg = e.target.files[0]
const url = URL.createObjectURL(inputImg)
// blob:http://localhost:3000/test-img.jpg
The resulting file stays in memory and needs to be removed in order to create memory leaks.
URL.revokeObjectURL(url)
This also seems to be accomplishable with FileReader, though there are differences.
When I run my snippet (shown below), it replace the dashes (-), the single quote, and the double quote with �.
var button = document.querySelector('#fileInput + button');
var input = document.getElementById('fileInput');
var text = null;
input.addEventListener("change", addDoc);
button.addEventListener("click", handleText);
function addDoc(event) {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(e) {
text = reader.result;
button.removeAttribute("disabled");
};
reader.onerror = function(err) {
console.log(err, err.loaded, err.loaded === 0, file);
button.removeAttribute("diabled");
};
a = reader.readAsText(event.target.files[0]);
console.log(a);
}
function handleText() {
addtoPreviousOutput();
changeOutputParagraph(text);
button.setAttribute("disabled", "disabled");
}
function changeOutputParagraph(newText) {
var element = document.getElementById("output");
element.innerHTML = newText;
}
function addtoPreviousOutput() {
var previousOutput = document.getElementById("output").innerHTML;
var previousOutput_sOutput = document.getElementById("previousOutput").innerHTML + "<br />";
console.log(previousOutput);
console.log(previousOutput_sOutput);
document.getElementById("previousOutput").innerHTML = previousOutput_sOutput + previousOutput;
}
<p id="previousOutput"></p>
<p id="output"></p>
<input type="text" id="textInput" onkeypress="getText(event)" />
<input type="file" id="fileInput" accept="text/*" />
<button type="button" id="addDoc">Add Document</button>
Why is that and how do I fix it?
Edit
I get this when I run my file which is 176 lines and 22 KB. Note: This isn't all of the text.
readAsText reads the text as utf-8 by default. The reason you see � instead of your expected characters is because your text file is not utf-8 encoded.
You can pass the encoding of your file to readAsText to properly read the text.
e.g. for latin 1
a = reader.readAsText(event.target.files[0], 'ISO-8859-1');
A FileReader can only read one file at the time, however you're trying to read the file twice:
reader.readAsText(event.target.files[0]);
console.log(reader.readAsText(event.target.files[0]));
There's no actual reason for you to do that. Just store the first read result - and print the data that you've already read.