What is problem in save files indexedDB in my code - javascript

Im just started learning indexedDB and have a task.So i need save 3 pictures in indexedDB and after show this pictures after click on button(1,2 or 3).In this code i save only one pictures but after click button 1 nothing is going.
`
<div class="flexi" >
<img src="" alt=''>
<button id="one">1</button>
<button class="two">2</button>
<button class="three">3</button>
</div>
<script src='./IDB.js'></script>
<script>
let db=idb.open("Gallery",1,(upgradeDB)=>{
let photo=upgradeDB.createObjectStore("Nature"/* ,{keypath:description} */)
})
.then((photos)=>{
let transaction=photos.transaction(["Nature"],"readwrite")
let store=transaction.objectStore("Nature")
let img=new Image();
img.src="img nat/christopher-czermak-AeiXAB8n8Mc-unsplash.jpg"
let BlobUpload = new Blob([img], {type: 'image/jpg'});
store.add(BlobUpload,1)
})
document.querySelector("#one").addEventListener("click",function(){
let bs=idb.open("Gallery",1)
.then((res)=>{
let transaction=res.transaction(["Nature"],"readwrite");
let store=transaction.objectStore("Nature");
return store.get(1)
})
.then((pic)=>{
let imgUrl=URL.createObjectURL(pic);
document.querySelector("img").setAttribute("src",imgUrl)
})
})
`
I think problem in blob file because i use
console.log(imgUrl)
and in console i see
blob:null/e8e0cf8f-0f36-4f3c-b688-029b33b256bf

Related

Why is my QR code cropped when extracting with base64?

im trying to copy the qr code from another windows but the left first line of the qr is missing
Script (renderer.js):
const loadQr = async () => {
const response = await window.loader.loadQr()
// console.log(response)
document.getElementById('qr').src = 'data:image/png;base64,' +
response
}
console.log('Index Loaded')
loadQr()
And my HTML is:
<div class="btns">
<button onclick="loadQr()">Load QR</button>
</div>
<br>
<img id ="qr" width="264" height="264" src="" alt="qr">
<script src='../renderer.js'></script>
And Im also adding a sc so you understand what im dealing with:
https://imgur.com/a/8y5izKx
Thanks in advance :)

Send Javascript Variable to HTML Img Source

I am utilizing a piece of JavaScript code to change image sources on a WordPress website (leveraging the Elementor editor), which is based on a button click updating the URL with a specific string. For example, this process would yield the following:
Before Click: www.website.com/acoolpage/
After Click: www.website.com/acoolpage/?picture=ws10m
This HTML constructor creates the dimension of the image, but does not update the image source with the desired result after the button click, when the URL switches to www.website.com/acoolpage/?picture=ws10m. What additional steps and/or edits are required? Thanks!
const urlParams = new URLSearchParams(window.location.search);
const pictureParam = urlParams.get('?picture=')
const pictureUrl =
switch (pictureParam) {
case 'ws10m':
return 'https://www.website.com/graphics/image_ws10m.png'
break
default:
return 'https://www.website.com/graphics/image_t2m.png'
break
}
<body>
<img src=pictureURL alt="Test" width="1920" height="1080">
</body>
Wrong call to get
image source is not assigned anywhere, img src=pictureURL is wishful thinking
switch does not return a value
The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.
You likely meant to do this
window.addEventListener("DOMContentLoaded", function() {
const urlParams = new URLSearchParams(window.location.search);
const pictureParam = urlParams.get('picture')
document.getElementById("img").src = `https://www.website.com/graphics/image_${pictureParam === 'ws10m' ? 'ws10m.png' : 't2m.png'}`
})
<img src="" id="img" alt="Test" width="1920" height="1080">
Alternative for more versions
window.addEventListener("DOMContentLoaded", function() {
const urlParams = new URLSearchParams(window.location.search);
const pictureParam = urlParams.get('picture');
document.getElementById("img").src = `https://www.website.com/graphics/image_${pictureParam ? pictureParam : 'default.png'}`
})
<img src="" id="img" alt="Test" width="1920" height="1080">
You can use the locationchange event to detect if the URL has been changed by a button click.
The code is as follows :
const obj = document.getElementById('#IDFromDOM');
function updateImage(){
const urlParams = new URLSearchParams(window.location.search);
const pictureParam = urlParams.get('picture')
const pictureUrl = pictureParam === 'ws10m' ? 'https://www.website.com/graphics/image_ws10m.png' : 'https://www.website.com/graphics/image_t2m.png'
obj.src = pictureUrl;
}
window.addEventListener('locationchange', updateImage);
updateImage(); //Fire a first time on page load

How can I save CSS property for the next JavaScript code(execution)?

I want to change the HTML element, which the ID is D-image, and use it as a prediction model. I tried to change CSS but it won't let me save it.
The only thing I want to do is change its CSS filter property and use a changed(means greyed) D-image element to predict.
Here is my BODY HTML code
<div>Teachable Machine Image Model</div>
<button type="button" onclick="init()">Start</button>
<button type="button" onclick="predict()">predict</button>
<script class="jsbin" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div class="file-upload">
<button class="file-upload-btn" type="button" onclick="$('.file-upload-input').trigger( 'click' )">Add Image</button>
<div class="image-upload-wrap">
<input class="file-upload-input" type='file' onchange="readURL(this);" accept="image/*" />
<div class="drag-text">
<h3>Drag and drop a file or select add Image</h3>
</div>
</div>
<div class="file-upload-content">
<img class="file-upload-image" id="D-image" src="#" alt="your image" />
<div class="image-title-wrap">
<button type="button" onclick="removeUpload()" class="remove-image">Remove
<span class="image-title">Uploaded Image</span>
</button>
</div>
</div>
</div>
<div id="webcam-container"></div>
<div id="label-container"></div>
Here is my original javascript code
<script type="text/javascript">
// More API functions here:
// https://github.com/googlecreativelab/teachablemachine-community/tree/master/libraries/image
// the link to your model provided by Teachable Machine export panel
const URL = "https://teachablemachine.withgoogle.com/models/ca88ZGYrw/";
let model, webcam, labelContainer, maxPredictions;
// Load the image model and setup the webcam
async function init() {
const modelURL = URL + "model.json";
const metadataURL = URL + "metadata.json";
// load the model and metadata
// Refer to tmImage.loadFromFiles() in the API to support files from a file picker
// or files from your local hard drive
// Note: the pose library adds "tmImage" object to your window (window.tmImage)
model = await tmImage.load(modelURL, metadataURL);
maxPredictions = model.getTotalClasses();
labelContainer = document.getElementById("label-container");
for (let i = 0; i < maxPredictions; i++) { // and class labels
labelContainer.appendChild(document.createElement("div"));
}
}
// run the webcam image through the image model
async function predict() {
// predict can take in an image, video or canvas html element
var image = document.getElementById("D-image")
const prediction = await model.predict(image, false);
for (let i = 0; i < maxPredictions; i++) {
const classPrediction =
prediction[i].className + ": " + prediction[i].probability.toFixed(2);
labelContainer.childNodes[i].innerHTML = classPrediction;
}
}
</script>
I also tried this but when I do prediction it won't let me use the changed D-image element.
<script type="text/javascript">
// More API functions here:
// https://github.com/googlecreativelab/teachablemachine-community/tree/master/libraries/image
// the link to your model provided by Teachable Machine export panel
const URL = "https://teachablemachine.withgoogle.com/models/ca88ZGYrw/";
let model, webcam, labelContainer, maxPredictions;
// Load the image model and setup the webcam
async function init() {
const modelURL = URL + "model.json";
const metadataURL = URL + "metadata.json";
// load the model and metadata
// Refer to tmImage.loadFromFiles() in the API to support files from a file picker
// or files from your local hard drive
// Note: the pose library adds "tmImage" object to your window (window.tmImage)
model = await tmImage.load(modelURL, metadataURL);
maxPredictions = model.getTotalClasses();
labelContainer = document.getElementById("label-container");
for (let i = 0; i < maxPredictions; i++) { // and class labels
labelContainer.appendChild(document.createElement("div"));
}
}
// run the webcam image through the image model
async function predict() {
// predict can take in an image, video or canvas html element
var image = document.getElementById("D-image").style.webkitFilter = "grayscale(100%)";
const prediction = await model.predict(image, false);
for (let i = 0; i < maxPredictions; i++) {
const classPrediction =
prediction[i].className + ": " + prediction[i].probability.toFixed(2);
labelContainer.childNodes[i].innerHTML = classPrediction;
}
}
</script>
Is there any way to save changed CSS property for the next javascript code(execution)?
CSS does not modify the image data so you can't use it to pass a modified image to a JS function. The resulting image data after CSS has been applied is not available to your JS code at all. All you can access is the original image data.
BTW, your code causes the image variable to be equal to the string "grayscale(100%)" because the result of any assignment expression is the value assigned, so document.getElementById("D-image").style.webkitFilter = "grayscale(100%)" returns "grayscale(100%)" , then you are assigning that result to your variable instead of the image element. That is why it breaks when you do that.
You have to modify the image data. There are ways to get the raw image data
Once you have that data, you have to do some processing to make it grayscale, CSS cannot serve as a shortcut here. Maybe this will help.
After you have modified the image data, you have to turn it into a format your function can accept. It looks like it accepts HTML elements so figure out how to change it back into an image element and you should be good.

JS Function to swap Image

Using a pre-trained model for image classification, I created a webpage that in theory will allow the user to browse their computer for a image and when that image is selected, it is automatically processed and the top three responses for what that image most likely is displayed on the webpage along with the probability for each. My JS function is probably very wrong, I’m somewhat self-taught. I’m also using materializecss and tensorflow.js if it helps.
I’m having trouble with changing the image I currently have hard coded there with the chosen image of the user.
HTML
<div name="imagePost" class="offset-s1 col s6">
<img class="responsive-img" id="changeImage" src="images/dog.jpg" alt="description">
<input type="file" name="pickImage" onchange="swapImage(pickImage)">
</div>
JS Function
function swapImage (pickImage) {
var image_toShow = pickImage;
document.getElementById('changeImage').innerHTML = image_toShow;
}
Here is how you can swap the image
function swapImage(event) {
var selectedFile = event.target.files[0];
var reader = new FileReader();
const img = document.getElementById("changeImage");
reader.onload = function(event) {
img.src = event.target.result;
};
reader.readAsDataURL(selectedFile);
}
Thanks for the help and suggestions. I ended up using a file reader, eventlisteners, and actually creating the img tag in another js function. Ill share it below incase it could help others. So the html part just has a empty div and js reads the input file and creates a img tag with the uploaded photo.
<div name="imagePost" class="offset-s1 col s6">
<fieldset>
<div id="changeImage">
</div>
</fieldset>
<input type="file" id="pickImage">
<a class="btn-large black col s4 offset-s1 unselect" onclick="app()">Calculate</a>
</div>
</div>
window.onload=function()
{
var y = document.getElementById("pickImage");
y.addEventListener('change', loadimage, false);
}
function imageHandler(e2)
{
var store = document.getElementById('changeImage');
store.innerHTML='<img id="newImage" class="responsive-img" src="' + e2.target.result +'" alt="The image here is interchangeable, allowing for users to process many different images using the machine learning model.">';
}
function loadimage(e1)
{
var filename = e1.target.files[0];
var fr = new FileReader();
fr.onload = imageHandler;
fr.readAsDataURL(filename);
}

retrieving gifs from tenor API json

i'm implementing this tenor API into my Site....the thing is that with this function I retrieve a single value single gif...How do I foreach() all of them?
How would need to be the html structure and the javascript loop
JAVASCRIPT/ JSON
function grab_data(anon_id)
{
// set the apikey and limit
var apikey = "*************";
var lmt = 8;
.....
// callback for trending top 10 GIFs
function tenorCallback_trending(responsetext)
{
// parse the json response
var response_objects = JSON.parse(responsetext);
top_10_gifs = response_objects["results"];
// load the GIFs -- for our example we will load the first GIFs preview size (nanogif) and share size (tinygif)
document.getElementById("preview_gif").src = top_10_gifs[1]["media"][0]["nanogif"]["url"];
document.getElementById("share_gif").src = top_10_gifs[6]["media"][0]["tinygif"]["url"];
return;
}
I would have this top_10_gifs variable loaded of content...how do I foreach it?
HTML
<h2 class="title">GIF loaded - preview image</h2>
<div class="container">
<img id="preview_gif" src="" alt="" style="">
</div>
<h2 class="title">GIF loaded - share image</h2>
<div class="container">
<img id="share_gif" src="" alt="" style="">
</div>
Depends on what exactly you're trying to do (which you haven't explained), but something like
response_objects.results.forEach((gifObj, i) => {
if (i >= 8) return;
// do something with each gifObj
document.querySelector('.container')
.appendChild(document.createElement('img'))
.src = gifObj.media[0].tinygif.url;
});
to iterate over all of them.

Categories

Resources