ImageFlow en CodeIgniter

Publicado: 19/02/2010 en CodeIgniter, desarrollo, JavaScript, php
Etiquetas:, , , , ,

You can read the English version of this post in http://phpsblog.agustinvillalba.com/imageflow-codeigniter/

En esta ocasión voy a explicar cómo incluir la librería JavaScript llamada ImageFlow dentro del framework CodeIgniter y conseguir que funcione a la primera ¡lo cual no es fácil! A continuación explicaré unas pequeñas modificaciones en el código de la librería. Luego veremos un ejemplo de código de inlcusión y por último veremos el módulo PHP necesario para el correcto funcionamiento. Pero primero qué es la librería ImageFlow y para qué sirve.

Qué es ImageFlow y para qué sirve

ImageFlow es una librería JavaScript que nos permite añadir una galería de imágenes realmente elegante en nuestro sitio web de una forma muy sencilla, dándole un aspecto Flash sin los inconvenientes que esa tecnología puede acarrear. De esta forma podemos mostrar nuestra galería de imágenes cómo deseemos, dado que tiene un gran número de parámetros de configuración, para darle el aspecto y comportamiento que más nos guste o convenga a nuestro sitio. Pero dejémonos ya de hablar y vamos a lo importante, la integración en CodeIgniter.

Integrando ImageFlow en CodeIgniter

Partiremos de la base de que ya tenemos descargado e instalado el framework CodeIgniter en nuestro sitio web. Así que, lo primero que necesitamos es descargarnos la librería, la cual tiene licencia Creative Commons si la utilizaremos en un sitio web no comercial, en caso contrario hemos de abonar una licencia de explotación, podéis encontrar toda esta información sobre la licencia en la propia página de descarga. Una vez nos hemos descargado la librería, creamos un directorio «js» en la raíz de nuestro sitio web, al mismo nivel que el directorio «system» propio de CodeIgniter. Dentro de esa carpeta colocaremos el directorio «ImageFlow» tras descomprimirlo. Si queremos podemos prescindir del archivo index.html y del directorio img dentro de ImageFlow, dado que no son más que de ejemplo de uso de la librería.

Una vez tenemos la librería dentro de nuestra aplicación CodeIgniter podemos empezar a trabajar para hacer que funcione a la perfección. Lo primero que necesitamos es editar el archivo imageflow.js en dos líneas. La primera es añadir una nueva opción a la librería, para poder pasarle la URL de nuestra aplicación a ImageFlow, exactamente en la línea número 69:

...
startAnimation:     false,          /* Animate images moving in from the right on startup */
xStep:              150,
base_url:           ''
}
...

La siguiente modificación será en la línea número 157, donde añadimos la url para referenciar correctamente la imagen a añadir:

...
var src = node.getAttribute('src',2);
src =  thisObject.base_url + 'js/ImageFlow/reflect'+version+'.php?img='+src+thisObject.reflectionGET;
node.setAttribute('src',src);
...

Con esto ya tenemos preparada la librería para interactuar con CodeIgniter. Ahora vamos a llamar a la librería desde nuestra vista, para ello necesitamos el siguiente código:

<div id="slider" class="imageflow">
<img src="<?php echo base_url();?>img/imagen1.jpg" alt="Texto a mostrar con la imagen" logndesc="url_a_la_que_enlaza_la_img" width="100" height="50" />
<img src="<?php echo base_url();?>img/imagen2.jpg" alt="Texto a mostrar con la imagen" logndesc="url_a_la_que_enlaza_la_img" width="100" height="50" />
<img src="<?php echo base_url();?>img/imagen3.jpg" alt="Texto a mostrar con la imagen" logndesc="url_a_la_que_enlaza_la_img" width="100" height="50" />
</div>

<script type="text/javascript" src="<?php echo base_url();?>js/jquery-latest.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/ImageFlow/imageflow.js"></script>
<script type="text/javascript">
var url = "<?php echo base_url();?>";
$(document).ready(function(){
var imageFlow = new ImageFlow();
imageFlow.init({ ImageFlowID: 'slider',
buttons: true,slider: true,
base_url: url
});
});
</script>

Con esto ya tenemos integrada la librería en nuestra aplicación. Puedes encontrar más ayuda en la sección de documentación de la librería. Ya tan sólo nos falta configurar adecuadamente nuestro servidor.

Configurando nuestro servidor PHP

Dado que la librería necesita generar dinámicamente las imágenes finales a partir de las originales que nosotros le pasamos, nuestro servidor necesita tener instalado el módulo php5-gd para poder generar los gráficos.

Con esto ya tenemos integrada la librería ImageFlow en nuestra apliación construida con CodeIgniter.

You can read the English version of this post in http://phpsblog.agustinvillalba.com/imageflow-codeigniter/

comentarios
  1. uriel lujan dice:

    no muestra las imagenes

  2. Ari Azman dice:

    Hello, my name is ari. and i have a little problem over here. you see that i’m using imageflow 1.3.0. but the image didn’t showed up. can you tell me what i’m missed?

    btw, i didn’t know where to edit this «base_url» coz i’m download the Non-commercial imageflow. should i use Commercial Website imageflow or something?? please help…!!

    • Hello,

      Ok, I have defined the JavaScript variable «base_url» in my main_template view, where I have this code:
      var url = "<?php echo base_url(); ?>";
      so, this is a global variable in JavaScript you can access to it when you need it and stores the CI base_url of your site (e.g: http://www.example.com).
      I think this will fix your problem loading the images.
      I hope this answer solve your problem!

      • Ari Azman dice:

        Agustín, thnx for reply my comment. ^_^d it’s really helpfull.

        and for now the slider and the alt of the image is showed up. but still my image didn’t showed up. i’m using *.png file for the image. btw, i’m newbie in CI. so i just learned about controller, model, view, and the config.

        so in var url = «»; i should type the source of the image just like

        – var url = «»;

        or i should type the source of the file js?

        thnx…!

        • Hi Ari,
          in the var url you olny have to echo the base_url of CI. Just that.
          Then, in the init section of the ImageFlow variable, you set the base_url in order ImageFlow use the absolute url to get the images instead of using the relative url.
          I think if !you follow the article step by step you will be able to get your ImageFlow working perfectly in CI, if not, let me see your code and I will try to help you.
          Regards!

          • Ari Azman dice:

            Hi Agustín, i’m using this base url in config.php

            $root = «http://».$_SERVER[‘HTTP_HOST’];
            $root .= str_replace(basename($_SERVER[‘SCRIPT_NAME’]),»»,$_SERVER[‘SCRIPT_NAME’]);

            $config[‘base_url’] = $root;

            this script is very usefull if i want want to move my website from local server to production server. and i just copy paste the $root to the base url.

            var url = «»;
            $(document).ready(function(){
            var imageFlow = new ImageFlow();
            imageFlow.init({ ImageFlowID: ‘slider’,
            buttons: true,slider: true,
            base_url: url

            but it’s not working. help!!

            • Ok, one more thing: Have you edited the options of ImageFlow in the file imageflow.js? Because if you don’t do it, ImageFlow will not take into account your parameter «base_url». You have to add that option in the file imageflow.js just like I have explained in the article.
              I hope this help you!

              • Ari Azman dice:

                and where is it the options of the ImageFlow it self? can you show me the script?
                i already copy your scipt that in line 69 and 157. maybe if you could show me the scipt of base_url if i’m using this base_url on config :

                $root = “http://”.$_SERVER[‘HTTP_HOST’];
                $root .= str_replace(basename($_SERVER[‘SCRIPT_NAME’]),”»,$_SERVER[‘SCRIPT_NAME’]);

                $config[‘base_url’] = $root;

                sorry to keep you waiting. (´⌣`ʃƪ)

                • This is the base_url that I use in my config.php:
                  $config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
                  $config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
                  if (!isset($_SERVER['ORIG_SCRIPT_NAME']))
                  {
                  $config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
                  }
                  else
                  {
                  $config['base_url'] .= str_replace(basename($_SERVER['ORIG_SCRIPT_NAME']),"",$_SERVER['ORIG_SCRIPT_NAME']);
                  }

                  And this is how I call the imageFlow in my views:
                  $(function(){
                  var url = "";
                  var imageFlow = new ImageFlow();
                  imageFlow.init({ ImageFlowID: 'slider',
                  buttons: true,
                  slider: true,
                  reflectionGET: '&height=2%',
                  //captions: true,
                  reflectionP: 0.0,
                  imagesM: 1.7,
                  imagesHeight: 0.4,
                  aspectRatio: 2.4,
                  scrollbarP: 0.8,
                  startID: index,
                  imageCursor : 'pointer',
                  base_url: url
                  });
                  });

                  I hope this help you!

                  • Ari Azman dice:

                    ok. there are many things that i want to ask about :

                    1. is it true that base_url in imageflow.js line number 69 you didn’t insert anything just quotes??

                    2. in my imageflow.js line number 157 i write the script just like this

                    src = my.imagePath+node.getAttribute(‘src’,2);
                    src = my.reflectPath+’reflect’+version+’.php?img=’+src+my.reflectionGET;
                    thisObject.base_url + src = ‘js / ImageFlow / Reflect’ + version + ‘. php? img =’ + src +thisObject.reflectionGET;

                    var src = node.getAttribute(‘src’,2);
                    src = thisObject.base_url + ‘js/ImageFlow/reflect’+version+’.php?img=’+src+thisObject.reflectionGET;node.setAttribute(‘src’,src);

                    is it correct? if this script not correct, maybe you can write the correct one. thnx.

                    3. you write var url = «»; in your view. you sure didn’t insert anything just quotes?

                    4. can you tell me your email adress? coz i want to write some scipt via email. is it fine for you?

                    thank you…!!

    • Wow, I have seen in the article that I have defined the JavaScript variable «url», BEFORE use the ImageFlow library, so… If you copy exactly that code, it should work
      Please, let me see your code and I will be able to get an idea of what is going wrong in your code.
      Regards!

  3. yohit dice:

    hola Agustín.

    que tal, estoy intentando poner imagenflow en mi web y no logro que se vean las imagenes, me podrías ayudar por favor, debe ser el código jquery que me falta algo.
    gracias.

  4. Max dice:

    Fatal error: Call to undefined function base_url() in …
    bueno eso me sale, sera la version del imageflow 😦

    • Hola Max. Eso no tiene que ver con el ImageFlow sino con CodeIgniter. Probablemente no hayas cargado el url helper de CodeIgniter antes de hacer esa llamada a base_url(). Para que deje de darte ese error tan sólo tienes que editar el archivo application/config/autoload.php de tu aplicación e incluirlo en el array de helpers tal que así:
      $autoload['helper'] = array('url');
      Con esto ya no deberías tener problemas para incluir ImageFlow en CodeIgniter.

  5. Agustín, genial y directo al grano. Muchas gracias.

Replica a Ari Azman Cancelar la respuesta