thumbGen

WordPress Plugin
Version 2.7.2

This WordPress plugin is made for developers. It creates a function named thumbGen() that allows to show any image in the specified size. Additionally you can specify values like crop, center, rotation and effects.

It saves all generated thumbs in a cache folder, so it won’t overload your server at all.

Download last version from WordPress repository
(or search for it on your “add plugins” page)

What’s new in this version

  • FIXED: Problem with black when using with WordPress on folders (now is working on multisite installations and WordPress installed in the root or folders)
  • IMPROVED: Minor code changes

License

Attribution – You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).

Share Alike – If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one.

Buy me a beer! 🙂

Well… I put this at the begining not because I’m doing this plugin to make some money, but because this is a lot of incentive to make more plugins like this. As every developer, I will always be happy to recieve your donations for my work and it will make me happier to keep updating this plugin.

Is very easy to donate… try it!

Documentation

Installation

Just donwload the zip file, upload it to your wordpress via install plugins page (or uncompress it to your wordpress wp-content/plugins/ folder) and activate it. Once activated se the main folder and default iage (in settings/thumbGen) and the plugin is ready to be used by calling its main function (see “Usage” section below).

Requirements

This plugin has been tested under the 2.9.0+ version of WordPress. Anyway, since this doesn’t use any wordpress function (just PHP) I thing it could work under any version of WordPress.

The basic configuration needed includes:

  • GD2 Library activated on the server
  • Fopen enabled on the server

The generated images are saved under the cache folder specified in the config page. If you have any problem you should check your settings (you must configurate the plugin before start using it).

Probably this plugin will work in almost every servers. If your server doesn’t support this plugin, please check the folder configuration. Otherwise please let me know.

Usage

To use this function you just need to use this line code:

<?php thumbGen(image,width,height,additional_parameters); ?>

image: the full URL of the original image you need to create a thumbnail from (needed).
width:
the width you need for the generated thumbnail (default=0 – if not specified it gets the proportional value from the specified height).
height:
the height you need for the generated thumbnail (default=0 – if not specified it gets the proportional value from the specified width).
note: if you don’t specify the with AND height (or if you set both to 0), the image will be generated in the source size.

Additional parameters

filename: some people have troubles with duplicated names, so I’ve added this parameter for you to specify a new filename (or ID or something like that) in order to differentiate each file (if not set it will use the source filename).
md5: by default, the images are generated with an md5 encode filename. If you don’t want the generated file to have an encoded name set this to 0
force: force thumb creation, even if it already exists (default=0) (NOT RECOMENDED! – use it just for testing or debugging)
crop: if you want the thumbnail to be cropped (no image deformation) if the width and height are different from the original image, set this value as 1 or true. If you want the content of the thumbnail to be resized to fit the space (image deformation) set this to 0 or false (default=1).
halign: horizontal align of the croped image. You can set it to left, center or right (default=center)
valign: vertical align of the croped image. You can set it to top, center or bottom (default=center)
effect: you can apply two effects: grayscale and sephia
rotate: you can specify a rotation angle
background: hex color (like #ffffff) to apply on the background ONLY when you rotate the image. If you don’t want a color applied you can set this to transparent (default=transparent)
return: if set to 1 (or true) the image name will be returned instead of printed (default=0).
preserveAnimation: if set to 1 it preserves animation in .gif files (all other args won’t work)
quality: 0 to 9 (default=7)

Examples

In this example I’ll not explain detailed how this WordPress code works, but I’ll show this as an example of this plugin usage:

<?php
$img="";
$args = array(
'post_parent'    => $post->ID,
'post_type'      => 'attachment',
'numberposts'    => 1,
'post_mime_type' => 'image'
);
$attachs = get_posts($args);
if ($attachs) {
$img=wp_get_attachment_image_src($attachs[0]->ID,'full');
}
if(!empty($img)){
?>
<img
src='<?php thumbGen($img[0],171,56,"effect=grayscale&halign=left&valign=top"); ?>'
alt='' />
<?php
}
?>

This example reads the first attached image of a post and save it’s information in a variable called $img. In the thumbGen function the first parameter is $img[0] and that’s the image URL. The second and third parameters are the width and height of the generated thumbnail we need. The rest of the parameters are defined in the string in the format parameter=value, concatenated with an &. the values not specified will use their default value.

Common errors and solutions

The most common error is that the image is not showing anything. If this happens to you, it could be solved following this steps:

  1. Be sure that the plugin is correctly configured (the folder must exists and should have the right permissions)
  2. Print the image URL before generate the thumb. If you copy and paste that URL in a new tab and you can see the image, then everything is OK.
  3. If the step 2 was ok but the image is not generated yet, then the problem could be one of this:
  • Your server has not enabled the GD2 library
  • Your server has not enabled the fopen wrapper (to check if this is enabled (and the GD issue) you could upload a .php file with the code <?php phpinfo(); ?> on it and there you have all the information you need)
  • The server from where you are trying to get the original picture does not allows you to retrieve it via php or fopen (it could happens on your server too – and that was the fix for the version 2.5.6)

To do

  • Recieve a lot of donations!: I have faith in you!
  • And, of course, if you have any idea on how to improve this plugin, please let me know

I hope you enjoy this plugin… and please let me know any bug you find!!! … thanks 😉

132 comments on “thumbGen
  1. Alejandro dice:

    Hola Sebastián

    Estoy implementando tu plugin (muy útil, por cierto) en un sitio que está en una carpeta de un sitio y me tira error ya que supone que el sitio está en el root.
    Lo arreglé modificando la linea 37:

    $sitePath=WP_CONTENT_DIR.”/..”;

    Saludos

  2. Ian dice:

    I think this is great! Took me a while to get working as on local host in a sub dir, but its working now!

    Im using it to size the post thumbnail, so had to make sure I was getting the image source path correct in order to generate the cached thumb otherwise the image was black.

  3. Adrian dice:

    Hola Sebastian necesito comunicarme contigo para hacer un plugin. Ya sabes mi correo

  4. Jérémie dice:

    HI, how can i do if i want to show the first image Thumbnail instead of the last image entered ?
    By default it take the last image entered in the article…

  5. Jérémie dice:

    Hola Sebastian,
    como yo puedo visualizar la primera imagen entrada en mi articulo, y no la ultima entrada (pienso que es el ID que cuenta).
    Gracias.

    • Sebastian Barria dice:

      En teoría debería ser modificando el ORDER en la consulta (pidiendo todos los posts ordenados por fecha descendente).
      Suerte!

  6. Alejandro dice:

    Hola Sebastián

    Creo que el parámetro crop no está bien establecido. Crop=0 debería de hacer que la imagen encaje dentro de las dimensiones sin deformar. Por ejemplo si tengo una imagen de 1000×500 y la quiero meter en un 200×200 debería quedar en 200×100. Al fin y al cabo es mucho más útil eso que deformar la imagen.

    Saludos

  7. Jon dice:

    Is there a non wordpress version, just plain php?

  8. Javier dice:

    Hola Sebastián, estaba teniendo problemas para cargar imágenes remotas que tuviese caratéres raros, como espacios o ñ.
    Para arreglarlo, he “urlencodeado” el nombre de la imagen remota, de manera que la función “imagecreatefromjpeg” acepta las imágenes.

    Para resolverlo, he añadido en la línea 57 del fichero thumbGen.php lo siguiente:

    $openImage=str_replace($fileName,rawurlencode($fileName),$openImage);

    Espero que os sea de ayuda, para mí ha sido importantísimo para el “clon” de Pinterest que estoy desarrollando en WordPress: http://elembarazo.net/cosas-bonitas, por si os interesa.

    Un saludo y gracias por el plugin!

    • Sebastian Barria dice:

      Hola Javier.
      Muchas gracias por tu excelente aporte. Voy a implementarlo en la próxima versión (para que actualices con confianza).

  9. Nicholas dice:

    hey my man, remember me, any plans to incorporate compression ?

  10. Olá, gostei do plugin e era exatamente o que eu estava procurando.

    Apenas tive problemas com a instalação Multi-site. Pesquisando fiz a seguinte alteração na linha #62:

    if (preg_match('/^(http|ftp|https)\:\/\/' . addslashes($_SERVER['HTTP_HOST']) . '/i', $img)) {
    $uploads = wp_upload_dir();
    $openImage = str_replace($uploads['baseurl'], $uploads['basedir'], $img);
    } else {
    $openImage = $img;
    }

    Não pensei muito na solução, acho que dá pra reescrever a definição dos diretórios de uma forma melhor. Mas daí é com você 🙂

    Esta solução foi baseada no seguinte post:
    http://kovshenin.com/2011/attachments-filename-and-directory-in-wordpress/

    Obrigado pelo plugin.

  11. Kid dice:

    IT would be nice to have an example of a simple line of code :/ I don’t have any idea how I can get this working now??

  12. Sunil Salunkhe dice:

    hey hi Sebastian Barria, awesome plugin but getting some problem with png images, is anything wrong on my side ……

  13. Cistian dice:

    Hola Sebastián,
    Te cuento que estuve arreglando problemas en uno de mis WordPress en modo debug y encontré un pequeño problema en tu plugin lo que hacia que apareciera un error (has_cap), las opciones de página ya no se utiliza por jerarquía sino que por privilegios

    Cambie esto
    add_options_page(‘thumbGen’, ‘thumbGen’, 10, ‘thumbGen’, ‘thumbgen_options_page’);

    Por esto
    add_options_page(‘thumbGen’, ‘thumbGen’, ‘edit_pages’, ‘thumbGen’, ‘thumbgen_options_page’);

    Y ahora funciona sin el error en modo debug 🙂

    Saludos!

  14. Andras dice:

    Hi Sebastian,
    Suddenly my thumbGen generated totally black thumbnails (for greyscale, brown for sephia). I don’t know what did trigger the error, but tracked down that line in your plugin.

    Commented out line #60 because it was validated as true, and added the site’s path ($sitePath) at the beginning of the image ($openImage). And it looked something like this: /var/www/mysite//var/www/mysite/wp-content/uploads/theimage.png

    I don’t know what’s that condition for, but in my case, it was causing the error.

    • Sebastian Barria dice:

      Hi Andras. I sent you an email to get more info about the url. In fact I installed a multisite (folder) wordpress to check if the plugin worked fine and it did… So with more info I could check it more accurately.
      Thanks 😉

  15. borisa dice:

    Hi Sebastian,
    Let me introduce myself. My name is Borisa Djuraskovic. I am associated with Web Hosting Hub. Your thumbGen plugin at http://www.sebastianbarria.com/plugins/thumbgen/ is very interesting. I want to translate it to my native language Serbo-Croatian.
    Do you mind if I do so?
    Please let me know!!!
    Regards,
    Borisa Djuraskovic

  16. MetalMatze dice:

    Hey devs,

    I think there’s a bug regarding quality. On the line where imagejpeg() is called to create the new image, $args[‘quality’] is multiplied by 100 instead of 10. Resulting the give imagejpeg a quality of 200 instead of 20 for quality=2.

  17. dinko dice:

    Hola Sebastian Barrias, un gran plugins, pero tengo un problema actualice mi wordpress, y también actualice el plugin, y ahora las imágenes se me fueron a negro. hay alguna solución? para volver a ver las imágenes normalmente.

    • Sebastian Barria dice:

      Hola dinko. La verdad es que no se porqué se puede deber. Fíjate que tengas bien configurado el plugin (sobre todo que exista la carpeta) y si aún así no funciona intenta mostrar las url original de las fotos que estás intentando miniaturizar… si copias la url de una foto que esté en negra y la pegas en la barra de direcciones de tu navegador y carga la foto sin problemas, entonces se debe a un problema de configuración del plugin… sino se debe ser algo con las fotos originales que estás intentando mostrar.
      Suerte!

  18. Julia dice:

    Hola, estoy usando el plugin y me crea las imagenes, tanto la miniatura como la imagen original completamente en negro. Borra la foto y lo convierte en un fondo negro! ¿sabes porque puede ser? Gracias

    • Sebastián Barría dice:

      He escuchado varios comentarios iguales… ¿tienes WordPress instalado en una carpeta dentro del dominio (por ejemplo tusitio.com/blog)?
      Creo que eso debe ser el problema… si es así, confírmame para hacer algunos cambios en el plugin y que lo puedas actualizar 😉
      Gracias!

      • Julia dice:

        Hola, he conseguido corregirlo pero no me acaba de convencer lo que he cambiado. El tema wordpress lo he heredado del desarrollo anterior y no puedo cambiarlo porque asi lo necesita el cliente, pero viene de un WP con versiones mas atiguas.. quizas eso es el cambio que hace que no funcione porque antes si que funcionaba.
        Ahora lo que he hecho es modificar varios php que estaban creados a medida en ese theme.

        Antes estaba este codigo:

        <img title=" | nombre de imagen” alt=” | nombre de imagen” src=”” alt=”” title=”” width=”215″ height=”110″ />

        <img title=" | nombre de imagen” alt=” | nombre de imagen” src=”” width=”215″ height=”110″ />

        AHORA está este y me funciona solo con esta linea (sustituyendo todo lo anterior)

        Saludos y ya me dices

  19. Hola, tengo en un sitio la Versión 2.5.6, cuando intento actualizar se me ven todas las imágenes en Negro, reemplazo la carpeta por la version anterior y se arregla

  20. Sebastián Barría dice:

    Hola a todos… he recibido varios comentarios diciendo que el plugin genera imágenes negras. Esto se debía a que el plugin tenía una falla al detectar la raíz del sitio en WordPress instalados en carpetas (por ejemplo: misitio.com/blog). Les comento que ya está solucionado y que pueden actualizar tranquilamente a la nueva versión 2.7.
    Que estén bien
    (y recuerden… las donaciones son siempre bienvenidas)

    Hi everyone… I’ve recieved a few comments saying that this plugin is generating balck images. This was because a problem on detecting the root of the site when using on WordPress installed on folders (like mysite.com/blog). Now it’s fixed, and you can safely upgrade yout plugins to the new version 2.7.
    Have a nice day
    (and remember… donations are allways welcome)!

  21. Hello!

    Thank you for a great plugin!

    I had a problem though.

    $folders[“sitePath”]=rtrim(ABSPATH,”/”);
    $folders[“baseFolder”]=str_replace($_SERVER[‘DOCUMENT_ROOT’],””,$folders[“sitePath”]);

    On my host, DOCUMENT_ROOT had a trailing slash, so the above code gave me the same values for sitePath and baseFolder. This fixed it:

    $folders[“baseFolder”]=str_replace(rtrim($_SERVER[‘DOCUMENT_ROOT’],”/”),””,$folders[“sitePath”]);

  22. jplow dice:

    Hi Sebastian,

    I’ve been using this plugin for years now. I love it! There’s nothing like it in my opinion. But I’m having an issue with using it through localhost (wamp). I’m getting a php error saying: “failed to open stream: HTTP wrapper does not support writeable connections in…” Do you have any suggestions?

    • Sebastián Barría dice:

      Good to hear that!… This kind of comments motivate me! (and also a donation).
      About your issue, I would have to investigate, since I didn’t hear about it. In the meanwhile, if you have further information please let me know

Deja un comentario