Manipulate all images from a directory without having to access

Asked

Viewed 1,666 times

1

The Script below, is in charge of showing a sequence of images at a certain amount rate (one), so it is necessary to define a number of images. Check out:

Code

<html>
  <body>
    <script>

     var dir = 'imagens' // Pasta Minhas imagens

      var num = '5' // Limite a mostrar

      window.onload = function(){

      for (var i = 1; i <= num; i++) {

      document.body.innerHTML += "<img src='"+dir+"/"+i+".jpg'>";

        }
    }

    </script>
   </body>
</html>

This routine (code block) has two parameters, the first is the say(directory) defined in the tag that will be responsible for storing the images.

The second parameter is referring to the display options, this parameter is a in a(number) that has the maximum amount to show on the page


I don’t want to set a limit number, I want the script itself to bring up the last image of the folder

NOTE - All images within the respective directory/folder should follow the same concept, all of which should be named by ordinal number, Exemplo: 1.jpg 2.jpg 3.jpg 4.jpg 5.jpg etc... Only then can you successfully show them.

  • 2

    Javascript only on the front is not able to directly access the disk. Are you using Node.js, php? Why does the code you posted not do what it says it does.

  • 1

    The file count (to know the total) has to be with a server-side language. PHP, for example. But if you’re going to use php to count, you can use it to display as well. I don’t see any other solution.

  • @Diegohenrique what matters from the linked answer is not the limite but rather the "impossibility" of doing what you want with guarantee of success. Although the answer I gave can work - is not at all the best way to solve the present problem.

2 answers

3


After thinking... (theoretically) There’s a way to do this client-side. It’s not, at all, advisable.

window.loadPatternImages = function() {

  var _this = this;
  this.fileTemplate = "%.jpg";
  this.fileDirectory = "/images/";
  this.imageIndex = 0;

  this.loadImage = function loadImage(src, index) {
    var image = new Image();
    image.src = src.replace('%', index);
    image.onload = function() {
      _this.imageIndex++;
      _this.loadImage(_this.fileDirectory + _this.fileTemplate, _this.imageIndex);
      //document.querySelector('.loaded-images').appendChild(image);
    };
    image.onerror = function(e) {
        var textNode = document.createTextNode('Loaded ' + _this.imageIndex + ' images from ' + src);
      //document.querySelector('.loaded-images').appendChild(textNode);
      _this.errorOccurred(e)
    };
  };

  this.errorOccurred = function(error) {
    console.log(error);
  };

  this.loadImage(_this.fileDirectory + _this.fileTemplate, _this.imageIndex);

};

What you have to do is create a self-recurring-function who calls himself in order to make a new image in the GIFT and to give it a src. When this image loads, then load the next one. If this image does not exist, it returns an error then ending the recursion.

You can then use image to make append on the DOM. Fiddlejs

However, it’s much easier to get a server to tell you which images to load.

0

Moshmage said - "There is a way to do this client-side. What you have to do is create a "self-recurring-Function" that calls itself"

In a free translation self-recurring-Function, that is to say - recursive function

Well, in Javascript there are two built-in timer functions (built-in timer functions), setTimeout and setInterval which can be used to call return functions (callback functions) after a certain time. See an example of using this:


setTimeout(function recursiva() { 

document.body.innerHTML += "."; 

setTimeout(recursiva, 1000); 

}, 1000); 

jsbin - Demonstration in operation


As you can see this code above, calls the function recursiva which, when processed, makes a call to setTimeout(recursiva,1000); what call recursiva again after 1 second, thus having almost the same effect as setInterval while remaining more resistant to unintentional errors that may occur.


Moshmage stressed - "You can then use image to append to the DOM"


So I decided to do it like this:

var numero = 0;

numero++;

var figura = document.createElement('img');

figura.src = "/images/'+numero+'.jpg";

document.body.appendChild(figura);

Now in a pre-assembled structure auto-recorrente-função would look this way:

var numero = 0;

numero++;


setTimeout(function recursiva() { 


    var figura = document.createElement('img');

    figura.src = "/images/'+numero+'.jpg";

    document.body.appendChild(figura);


setTimeout(recursiva, 1000); 

}, 1000); 

But according to setInterval() is the best way in this case. While the setInterval() calls the function "infinitely" always in the same time interval. And to pause the function is used clearInterval(). Passing as parameter the name of your range.

var intervalo = window.setInterval(function() {

document.body.innerHTML += "."; 

}, 50);

window.setTimeout(function() {

    clearInterval(intervalo);

}, 3000);

jsbin - Example of clearInterval event in operation


Moshmage ended by saying - "If this image does not exist, it returns an error then ending the recursion."


Great, he wanted to demonstrate something by the method OnError, kind of:

figura = document.createElement('img'); 

figura.onload = function() { 

document.body.appendChild(figura);
}
figura.onerror = function() {  

//display error

alert('Erro Fatal!')
}
figura.src = 'http://www.monkie.com.br/logo.png'; 

// Para prever tal comportamento na prática onError, 
// altere a url de destino retirando "logo.png"
// deixando-o http://www.monkie.com.br/ e teste novamente.

jsbin - Example of the Onerror event in operation


However this we can see running the final result, check out:

const figura = document.createElement('img');

var diretorio = 'http://mplayer.xpg.uol.com.br/img/'

var numero = 0;

var intervalo = window.setInterval(visualizar, 1000)
function visualizar() {
figura.src = diretorio+numero+'.jpg'
document.getElementById("foto").appendChild(figura);
    numero++;
}

figura.onerror = function() 
{  
clearInterval(intervalo);
alert('Há '+numero+' fotos em '+diretorio);
} 
<span id="foto">&nbsp;</span>


Snippet explanation

Detail, if you know the variable value figura will not change, the reserved declaration is used const.

It is not possible to call an anonymous function if it is not assigned to a variable. In this case the anonymous function is assigned to the variable figura preceded by point "." followed by the method onerror, becoming accessible only when this variable is accessible, if the image does not exist, the browser interprets a loading(load) error of an image, triggered by the Onerror method. This anonymous function is used clearInterval() which in turn is exactly to allow you to pass as parameter the name of your range, thus killing the continuous(recursive) process of the function visualizar(). Then the event alert() that displayed the total of successfully uploaded Images, that is, the exact amount of what is in the directory.


REMINDER - "All images must be named in ordinal numerals, otherwise impossible."


Finally, I had to clarify in practice the theory given for each paragraph said by Moshmage.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.