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
})
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 ?
Blob link is created, but the link returns 404 error
About this code; I am making markdown text editor, and am working on copy/paste image functionality, such as from screenshot. When paste action is made, this code should console.log blob url of a pasted image. But it looks like image doesn't exsists when I go to blob link.
What I did wrong for passing the image as blob?
code
import { useState } from 'react'
import { ReactMarkdown } from 'react-markdown/lib/react-markdown'
export default function Home() {
const [input, setInput] = useState('')
const handlePaste = async(e) => {
var items = e.clipboardData.items;
let image = [].slice.call(items).filter((obj)=> {
// Filter the image items only
return obj.type.indexOf('image') !== -1;
})
const item = image[0];
console.log(item)
// Get the blob of image
const blob = await item.getAsFile();
let blobURL = URL.createObjectURL(blob);
console.log(blobURL)
};
return (
<>
<textarea
name=""
id=""
cols="30"
rows="10"
value={input}
onPaste={handlePaste}
onChange={(e)=>setInput(e.target.value)}
/>
<ReactMarkdown childrenhow ={input}/>
</>
)
}
You can't "go to the link". You can access the blob as a File object, and you can use the object URL as e.g. the src attribute of an img tag within the same document. But the object URL stops referring to anything as soon as you leave the page.
So I have the following function vanilla JS code:
function get_menu(menu_id) {
wp.api.loadPromise.done(function() {
const menus = wp.api.collections.Posts.extend({
url: wpApiSettings.root + 'menus/v1/menus/' + menu_id,
});
const Menus = new menus();
Menus.fetch().then(
posts => {
let post_list = posts.items;
console.log(post_list);
});
});
}
get_menu(4);
This gives me a object of objects as shown below:
What is the best way to loop through these objects and render HTML within? So let's say I want to loop through each object and grab the post_title and output HTML <div> + post_title + </div>.
All help would be appreciated!
Update:
Need to render this in a loop:
<div class="column is-one-third is-flex py-0">
<a href=" ***url*** " class="dropdown-item px-2 is-flex is-align-items-center">
<figure class="image is-32x32 is-flex">
<img src=" ***image*** + ***post_title*** '.svg'; ?>">
</figure>
<span class="pl-2"><?= ***post_title*** ?></span>
</a>
</div>
You can iterate through the array and create a dom tree
function get_menu(menu_id) {
wp.api.loadPromise.done(function () {
const menus = wp.api.collections.Posts.extend({
url: wpApiSettings.root + 'menus/v1/menus/' + menu_id,
});
const Menus = new menus();
Menus
.fetch()
.then(posts => {
let post_list = posts.items;
// Map through response data and turn objects into elements
const postElements = post_list.map(createDomTree)
// spread all elements from array into arguments for the append method
document.body.append(...postElements)
});
});
}
function createDomTree(post) {
// I'm not sure if these values are available in the response data, but can be replaced
const { post_url, post_title, post_image } = post
const container = document.createElement('div')
container.className = 'column is-one-third is-flex py-0'
const anchor = document.createElement('a')
anchor.href = post_url
anchor.className = 'dropdown-item px-2 is-flex is-align-items-center'
const figure = document.createElement('figure')
figure.className = 'image is-32x32 is-flex'
const img = document.createElement('img')
img.src = `${post_image}${post_title}.svg`
const span = document.createElement('span')
span.className = 'pl-2'
span.textContent = post_title
figure.appendChild(img)
anchor.append(figure, span)
container.appendChild(anchor)
return container
}
get_menu(4);
I am new to React and would like to use my method (works fine in plain js). I have got a problem with assigning createElement to variable.
class UploadBar extends Component {
state = {
selectedFile: null
};
fileSelectedHandler = event => {
this.setState({
selectedFile: event.target.files[0]
});
};
fileLocalHandler = event => {
event.preventDefault();
let link = URL.createObjectURL(this.selectedFile);
let link = document.createElement("a");
link.href = URL.createObjectURL(this.selectedFile);
document.body.appendChild(link);
link.download = this.selectedFile.name;
link.click();
document.body.removeChild(link);
};
render() {
return (
<div id="uploadBar">
<input
multiple
type="file"
accept="application/pdf"
onChange={this.fileSelectedHandler}
/>
<button id="uploadBtn" onClick={this.fileLocalHandler}>
Upload a file
</button>
</div>
);
}
}
Could you help me with proper use of my fileLocalHandler method?
You want to access the selected file from this.state, not directly from this:
fileLocalHandler = event => {
event.preventDefault();
const { selectedFile } = this.state;
let link = document.createElement("a");
link.href = URL.createObjectURL(selectedFile);
document.body.appendChild(link);
link.download = selectedFile.name;
link.click();
document.body.removeChild(link);
};
I'm trying to use a weather api for a basic website and I'd like to use the icons too. The request works in both environments, but in my local environment I get an error for the icon
GET file://cdn.apixu.com/weather/64x64/night/116.png net::ERR_FILE_NOT_FOUND
I thought it was related to https but probably not since it's only the image that won't load.
const key = 'b7e1e81e6228412cbfe203819180104';
const url = `https://api.apixu.com/v1/current.json?key=${key}&q=auto:ip`
const main = document.getElementById('main');
$.getJSON( url, function(json) {
const loc = json.location;
const cur = json.current;
const condition = {text: cur.condition.text, icon: cur.condition.icon}
main.innerHTML = `<img src = ${condition.icon}><div>${condition.text}</div>`
}
so ${cur.condition.text} will display "partly cloudy" but the icon does not display. Any advice?
update: seems to be working fine with live-server.
It may be because the Cross-Origin Request Policy (CORS) may not allow it. Please make sure that you are allowed to access those resources.
https://enable-cors.org/ to read up more about CORS.
Secondly,
<img src = ${condition.icon}>
should be
<img src="${condition.icon}">
You are forgetting the quotation marks.
https://www.w3schools.com/tags/tag_img.asp - Read more on image tags.
Additionally use the code below:
Also add http: to image src like <img src=http:${condition.icon}>.
const key = 'b7e1e81e6228412cbfe203819180104';
const url = `https://api.apixu.com/v1/current.json?key=${key}&q=auto:ip`
const main = document.getElementById('main');
$.getJSON(url, function(json) {
const loc = json.location;
const cur = json.current;
const condition = {
text: cur.condition.text,
icon: cur.condition.icon
}
main.innerHTML = `<img src="http:${condition.icon}"><div>${condition.text}</div>`
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main"></div>
As icon return in JSON as protocol-relative URL (without the scheme) //url.
Locally it will use the file:// protocol and that assumes the resource you’re referring to is on the local machine, But it's not.
To avoid this issue locally add http: or https:to image src like <img src=http:${condition.icon}>.
const key = 'b7e1e81e6228412cbfe203819180104';
const url = `https://api.apixu.com/v1/current.json?key=${key}&q=auto:ip`
const main = document.getElementById('main');
$.getJSON(url, function(json) {
const loc = json.location;
const cur = json.current;
const condition = {
text: cur.condition.text,
icon: cur.condition.icon
}
main.innerHTML = `<img src =http:${condition.icon}><div>${condition.text}</div>`
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main"></div>