Tag Archives: jpeg

Computer Algorithms: Lossy Image Compression with Run-Length Encoding

Introduction

Run-length encoding is a data compression algorithm that helps us encode large runs of repeating items by only sending one item from the run and a counter showing how many times this item is repeated. Unfortunately this technique is useless when trying to compress natural language texts, because they don’t have long runs of repeating elements. In the other hand RLE is useful when it comes to image compression, because images happen to have long runs pixels with identical color.

As you can see on the following picture we can compress consecutive pixels by only replacing each run with one pixel from it and a counter showing how many items it contains.

Lossless RLE for Images
Although lossless RLE can be quite effective for image compression, it is still not the best approach!

In this case we can save only counters for pixels that are repeated more than once. Such the input stream “aaaabbaba” will be compressed as “[4]a[2]baba”.

Actually there are several ways run-length encoding can be used for image compression. A possible way of compressing a picture can be either row by row or column by column, as it is shown on the picture below.

Row by row or column by column compression
Row by row or column by column compression.
Continue reading Computer Algorithms: Lossy Image Compression with Run-Length Encoding

PHP Strings: How to Get the Extension of a File

EXE or GIF or DLL or …

Most of the code chunks I’ve seen about getting a file extension from a string are based on some sort of string manipulation.

Get the Filename Extension with PHP
If you want to get the filename extension with PHP is better to use pathinfo() than string manipulations

$filename = '/my/path/image.jpeg';
echo substr($filename, strrpos($filename, '.') + 1);

Howerver there is a more elegant solution.

$filename = '/my/path/image.jpeg';
echo strtolower(pathinfo($filename, PATHINFO_EXTENSION));

Thus you rely on PHP built in functions and it’s harder to overlook the exact string manipulation approach.

Download Files with Zend Framework

Download a File

The title may sound unclear enough, but the task is simple. You’ve to make a file download process within a Zend Framework’s controller. Let’s assume we’ve the DownloadController setup:

<?php
 
class DownloadController extends Zend_Controller_Action
{
	public function indexAction()
	{}	
}

In PHP there are at least three simple lines of code that will do the job of downloading a file.

header('Content-Type: image/jpeg');
header('Content-Disposition: attachment; filename="logo.jpg"');
readfile('images/logo.jpg');

Note that here there is a content-type header, which is important cause the browsers understands what kind of file is supposed to be downloaded. The second line suggests a name of the downloaded file and the third one returns the file to the client.

Download a File … within Zend Framework

Those three lines wont work alone in a ZF application, because there’s no view, but even if you create a .phtml (view) file for this action it won’t work, because the header of the returned file is modified.

The question is how to possibly return the file for download, perhaps write some statistics to the database and if there’s a problem (some permission issues for instance) return a message to the user.

The Basic Solution

The solution is simple. First make it work by disabling the view and possibly the layout for this action:

public function indexAction()
{
	header('Content-Type: image/jpeg');
	header('Content-Disposition: attachment; filename="logo.jpg"');
	readfile('images/logo.jpg');
 
	// disable the view ... and perhaps the layout
	$this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
}

Than add some code where you can check the permissions. Just because there’s no view for this action you can redirect to another – errorAction():

public function indexAction()
{
    if (userHasNoPermissions) {
        $this->view->msg = 'This file cannot be downloaded!';
        $this->_forward('error', 'download');
    }
 
    header('Content-Type: image/jpeg');
    header('Content-Disposition: attachment; filename="logo.jpg"');
    readfile('images/logo.jpg');
 
    // disable layout and view
    $this->view->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender(true);
}

But that still will prompt you a file to download, so there should be a return statement that will return false:

public function indexAction()
{
    if (userHasNoPermissions) {
        $this->view->msg = 'This file cannot be downloaded!';
        $this->_forward('error', 'download');
        return FALSE;
    }
 
    header('Content-Type: image/jpeg');
    header('Content-Disposition: attachment; filename="logo.jpg"');
    readfile('images/logo.jpg');
 
    // disable layout and view
    $this->view->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender(true);
}

So here’s the complete source of DownloadController.php:

<?php
 
class DownloadController extends Zend_Controller_Action
{
	public function indexAction()
	{
	    if (userHasNoPermissions) {
	        $this->view->msg = 'This file cannot be downloaded!';
	        $this->_forward('error', 'download');
	        return FALSE;
	    }
 
	    header('Content-Type: image/jpeg');
	    header('Content-Disposition: attachment; filename="logo.jpg"');
	    readfile('images/logo.jpg');
 
	    // disable layout and view
	    $this->view->layout()->disableLayout();
	    $this->_helper->viewRenderer->setNoRender(true);
	}	
 
	public function errorAction()
	{}
}

and the error.phtml:

<?php echo $this->msg ?>

Optimize your images – improve the performance

Overview

In a series of articles I’ll share what’s my experience with image optimization. Of course the most images you have the most page weight you have. That’s why optimizing your images should be your primary task.

Image Formats

First, I’m gonna mention several formats, which everyone of the webdevs are using widely. There are GIF, JPEG and PNG, where PNG can be either PNG8 and PNG24 (PNG32 is also available as name of that format).

What are the differences between them and when to use one or another?

Well some of us just use one or another even without knowing the difference or without thinking about the optimization. I remember when I just put the images in JPEG with no idea what are the other formats before.

In fact all the formats has pros and cons.

JPEG

The JPEG format can be either progressive or baseline. The difference is that the progressive JPEG can be loaded directly in the browser with very low quality and then to load with better quality. Some experts insist that this is old school, but I don’t think so. When the image is not the required one (think of a wallpaper preview) the user can skip and go to another without waiting the hole image. The baseline JPEG is loading the good quality image but starting from top to bottom. With portions of the image.

IE and progressive JPEGs

Of course the Internet Explorer 6 don’t support the progressive downloading of an JPEG even if it’s progressive. Well this is no issue till the IE loads the image like a baseline JPEG.

Which JPEG is progressive and which is baseline

You can certainly make some test to determine which JPEG is progressive and which is baseline, from the loading behaviour in your browser. If you’d like to convert an image to a progressive JPEG or baseline you can use a free open source programs out there in the wild online space. Once they are converted to one or another format you can use them widely. Because most of the tools are comand line open source tools you can automate them on the server where the user uploads it’s images. Now every big image can be converted to be progressive.

When to use progressive and baseline JPEGs?

Well the tests show that for images small than 10 K best compression you get with baseline, and for bigger images the small size you get is with progressive JPEGs. There’s the rule use the baseline for thumbs and progressive for any other big image.

GIF

This format is well known from the early ages of the web. It allows transparency and animation. Actually the problem with the GIF images is that they don’t support semi-transparency which is a problem nowadays. Today the web users are used to good quality images and somehow the GIF is not suitable. But it’s still the most used format for icons and of course animations.

When should I use GIF?

Well as I’ll mention in a while the PNG8 is a better format than GIF for transparent small icons. But if you should use some kind of an animation like ajax loading circle (or bar) the GIF format is suitable for you. Than you must use a GIF.

PNG

As I said PNG can be either PNG8 or PNG24 (which is also called PNG32). Actually PNG8 acts just like GIF, with the important exception that it supports semi-transparency, but yet again on every browser except IE6. In IE6 the PNG8 is just the same like GIF which is not so bad. If you’d like to use GIF for an icon, you should make it PNG8. There are semi-transparent pixels (except IE6 and above) and you get better experience on other browsers than GIF.

PNG32 transparency?

In fact PNG32 is not transparent on IE6 (on transparent pixels IE puts some kind of gray pixels). There you can use AlphaImageLoader filter, but that can dramaticaly slow down your browser, so it’s not a good idea.

You should avoid the PNG32 transparent images and the usage of AlphaImageLoader filter.

Conclusion

For every of these formats there lots of tools that remove system information from the image crash and crunch the files so that they become smaller. They can be automated and used on the server.

Now when you use different formats you can be aware of the differences between them and to use the appropriate ones.