How to Add a List of Images to the Document from an Array of Urls

How to add a list of images to the document from an array of URLs?

One way to do this is to loop over your array of images, create an img element for each, set the element's src to the current image source in your array, then append it to your container. This would look like:

var imgs = ['http://lorempizza.com/380/240', 
'http://dummyimage.com/250/ffffff/000000',
'http://lorempixel.com/g/400/200/',
'http://lorempixel.com/g/400/200/sports/'];
var container = document.getElementById('imageContainer');

for (var i = 0, j = imgs.length; i < j; i++) {
var img = document.createElement('img');
img.src = imgs[i]; // img[i] refers to the current URL.
container.appendChild(img);
}

However, this isn't particularly efficient:

  • We're using an unnecessary loop
  • We're querying the dom on every iteration
  • We're introducing the global i and j variables
  • We're not using JavaScript's wonderful Array methods!

Instead, let's use a documentFragment and JavaScript's forEach Array method.

var imgs = ['http://lorempizza.com/380/240', 
'http://dummyimage.com/250/ffffff/000000',
'http://lorempixel.com/g/400/200/',
'http://lorempixel.com/g/400/200/sports/'];
var container = document.getElementById('imageContainer');
var docFrag = document.createDocumentFragment();

imgs.forEach(function(url, index, originalArray) {
var img = document.createElement('img');
img.src = url;
docFrag.appendChild(img);
});

container.appendChild(docFrag);

This way we're:

  • Only hitting the DOM once
  • Not introducing global variables
  • Maintaining cleaner, easier to read code!

Then just to make sure your new images look nice, add a bit of CSS to the mix:

#imageContainer img {
width: 20%;
height: auto;
}

Bam! Here's a fiddle

How can i write multiple images URLs in one list array of query . Flutter Firebase

You can have a list that holds the list of image urls and you can just add the list to the collection.
See below:

     Future uploadInfo() async {
List<String> imageUrlList = [];
for (var img in _image) {
ref = firebase_storage.FirebaseStorage.instance
.ref()
.child('images/${Path.basename(img.path)}');
await ref.putFile(img);
final String downloadUrl = await ref.getDownloadURL();
imageUrlList.add(downloadUrl);
}
posts.doc(FirebaseAuth.instance.currentUser!.uid).collection('userPosts')
.add(
{
'imageUrlList': imageUrlList,
},
);

}

Check out: https://firebase.google.com/docs/firestore/manage-data/add-data

How can I make an array of image urls, append them to an existing array, and get the page to load the image using jQuery?

The easiest way to achieve what you want is to save objects as opposed to strings in your array. That way, you can create objects that have a title field and an imageUrl field like so:

var myarray= new Array(
{
title: "The Santa Claus",
imageUrl: "https://upload.wikimedia.org/wikipedia/en/thumb/e/e7/Video-x-generic.svg/90px-Video-x-generic.svg.png"
},
{
title: "Random Movie",
imageUrl: "https://upload.wikimedia.org/wikipedia/commons/thumb/a/ad/BolexH16.jpg/220px-BolexH16.jpg"
},
// you can add as many comma-separated objects as you want
);

Add an img element to your HTML and give it id picture. In your JS, you can set your movie's title and image like so:

document.getElementById("message").innerHTML=random.title;

// the element with id picture is an image element
document.getElementById("picture").src = random.imageUrl;

I have modified your codepen here with the proposed changes.

How can I get mongoose to push an array of urls to an array subdocument

With trial, error, and trawling through mongoose documentation I eventually found the answer I was looking for. I hope the answer helps you out if you have the same problem.

First, I needed to change how I defined my schema because it wasn't meant to be an array of objects, but just an array:

//Defining the Post Schema
const postSchema = {
title: String,
content: String,
imageUrls: [ String ]
};

The former url and id field were unnecessary for my purposes so I removed them as well.
Then I looked in the mongoose documentation enough that I stumbled across $addToSetand read about what it does. This seemed like the answer, and it turns out it is. To save my image urls to the document I ended up with this code:

app.post("/post-images", (req, res) => {
//const post=req
var postImages = req.body;
const postID = postImages.shift();
console.log(postImages);
Post.updateOne(
{ _id: postID },
{
$addToSet: { imageUrls: { $each: postImages } }
},
function(err, foundPost) {
if (!err) {
console.log(foundPost);
res.redirect("/");
} else {
console.log("error: " + err);
}
}
);

Now my code saved my array of urls properly, with each being a separate String under the imageUrls Subdocument.

How to append img as a li to a ul

You need both a new li and img element. And if you would like to present the GIF itself you should set the src attribute of the image to singleGiff.images.downsized.url.

const button = document.querySelector("#search-btn");
button.addEventListener("click", (event) => {
event.preventDefault();

const giffTitle = document.querySelector("#giffTitle").value;

axios;
const giffSection = document.querySelector(".giffs");
const giffList = document.querySelector(".list");

axios
.get(
`https://api.giphy.com/v1/gifs/search?api_key=iVwoS0brONsmkA6sWVqHgJ9D7g2WYDmv&q=${giffTitle}&limit=10&offset=0&rating=g&lang=en`
)
.then((res) => {
const giff = res.data;
// const giffUrl = giff.data[0].embed_url;
const giffUrl = giff.data;
//console.log(giffUrl);

giffUrl.forEach(function(singleGiff) {
let li = document.createElement("li");
let img = document.createElement("img");
img.src = singleGiff.images.downsized.url;
li.appendChild(img);
giffList.appendChild(li);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.26.0/axios.min.js" integrity="sha512-bPh3uwgU5qEMipS/VOmRqynnMXGGSRv+72H/N260MQeXZIK4PG48401Bsby9Nq5P5fz7hy5UGNmC/W1Z51h2GQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<h1>Giffs</h1>
<form action="">
<label for="">Search</label>
<input type="text" id="giffTitle" />
<button id="search-btn">Search</button>
</form>
<iframe id="iframe" src="${giffUrl}" width="480" height="270" frameborder="0" class="giphy-embed" allowfullscreen></iframe>

<section class="giffs"></section>
<ul class="list"></ul>

How to display an image through an array?

You are to place the html for the image, this way:

document.write('<img src="'+random.image+'" width="203" height="350" />');

Otherwise your random.image only shows the output of the array, which is text with "file path" written in it.

Download Images from image url stored in array with javascript or best alternative

Using the download attribute of an anchor should do the trick...

EDIT

download only works for same-origin URLs, or the blob: and data: schemes. ref

Since this is not your case, you will have to create a blob with each image and fortunately, that is easy with the fetch API.

const downloadAll = async () => {
// Create and append a link
let link = document.createElement("a");
document.documentElement.append(link);

const imgArr = document.querySelectorAll("img");
for (let i = 0; i < imgArr.length; i++) {
await fetch(imgArr[i].src)
.then(res => res.blob()) // Gets the response and returns it as a blob
.then(blob => {

let objectURL = URL.createObjectURL(blob);

// Set the download name and href
link.setAttribute("download", `image_${i}.jpg`);
link.href = objectURL;

// Auto click the link
link.click();
})
}
};

Tested on CodePen.

Javascript: Using Loop to Fill Array with URL's for Images

if your filenames are always like n+.jpg you could do the following:

var container = document.getElementById('comicPages');

var images = 23;

for (var i = 0; i < images; i++) {
// this will create and insert the corresponding image
// new Image() creates a new <img> element. there is not much of a difference
// to document.createElement('img'). additional you can call it as:
// new Image(width, height) in case you already know its dimensions.
var node = new Image();
// additional you can also do the following as: node.src = i + '.jpg';
node.setAttribute('src', i + '.jpg'); // but i like conventions
container.appendChild(node);

// this will ensure to insert a line break between each image
if (i < images - 1) {
container.appendChild(document.createElement('br'));
}
}

keep in mind you have to run this after you inserted <div id="comicPages"></div> into your body.



Related Topics



Leave a reply



Submit