Creating one pixel image for Magento by using GD library

March 2nd, 2014 by in Backend, Frontend, Magento 0
Creating one pixel image for Magento by using GD library

So you are building a Magento module and need a one pixel image for some reason. Maybe you have dynamically loaded images somewhere in the module that do not have their src attribute at all times (you should definitively avoid this situation). Or you need a tracking pixel, which I will cover some other time. Or you need to fill in some nasty bad pixel in your perfect design (I’m just making things up now as I go at this moment :) ). Sometimes you don’t have control of what folders you will have at your disposal on the destination server, so a best solution would naturally be to deploy your image when your module is installed. This quick and easy post will show you how to do that.

 

The first thing you need to know is that Magento itself uses GD library for processing images. This means that you can safely use GD library yourself without having to worry about compatibility issues. So with that in mind let’s run straight to the code. This should go in your module’s installation/upgrade script:

 

$dir = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS . 'your_module' . DS . 'system';
mkdir($dir, 0775, true);

$image = imagecreate(1, 1);
imagecolorallocate($image, 255, 255, 255);
$filename = $dir . DS . 'empty.gif';
imagegif($image, $filename);
imagedestroy($image);

 

The process is fairly simple:

  • set the directory where you want to save your image;
  • create the directory;
  • define 1 x 1 pixel image resource;
  • set color of your pixel (RGB);
  • define name of your image file;
  • create and save your image;
  • destroy image resource to free the associated memory.

 

I have experimented a bit with different settings. Different image types will produce different results when it comes to actual image size in bytes. Here is a comparison for lowest quality settings of all 3 major image types:

 

// gif image: 35 bytes
imagegif($image, $filename);

// png image: 82 bytes
imagepng($image, $filename, 9);

// jpeg image: 690 bytes
imagejpeg($image, $filename, 0);

Have fun :)

Written by Nikola Stojiljkovic

Nikola is a Certified Magento Backend Developer with a passion for high quality code that follows standards and best practices. He also leads our Magento development teams so you can expect excellent Magento articles from him.


See all articles from this author »

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>