Implement Instagram filter effect using PHP

Source: Internet
Author: User
Tags imagemagick server hosting
Note: This article involves image processing and is very interesting. It can also be used to build a mobile photo App on the cloud plus side. Tutorial details program: PHPImageMagick difficulty: Intermediate estimated completion time: 45 minutes you will create the final File Download source file in this tutorial, I will demonstrate how to use PHP and ImageMagick to create an image that works like Instagram

Note: This article involves image processing and is very interesting. It can also be used to build a mobile photo App on the cloud plus side. Tutorial details program: PHP/ImageMagick difficulty: Intermediate estimated completion time: 45 minutes you will create the final File Download source file in this tutorial, I will demonstrate how to use PHP and ImageMagick to create an image that works like Instagram

Note: This article involves image processing and is very interesting. It can also be used to build a mobile photo App on the cloud plus side.

Tutorial details

  • Program: PHP/ImageMagick
  • Difficulty: Intermediate
  • Estimated Completion Time: 45 minutes

You will createFinal work


Download source file

In this tutorial, I will demonstrate how to use PHP and ImageMagick to create old photos with the same effect as Instagram. Yes, you can use PHP and ImageMagick to accomplish this, and this is just the simplest thing!

We create digital photos and make them cool.

A few years ago (five years ago in PHP), ImageMagick was born. Since then, it has developed into an independent software platform to create, edit, generate, or convert grating images (supporting more than 100 formats !). You can use it to adjust the image size, create an image, flip, rotate, twist, cut, and convert the image, adjust the image color, and apply a variety of special effects, you can also draw text, lines, polygon, oval, and SEL curves. It has everything you need to process images, process videos, and generate panorama in Web development. However, it is not a GUI image editor.

ImageMagick is the Photoshop command line on the Web.

PHP Image Processing

PHP is bundled with GD (GIF Rendering/graphic rendering), which is a dynamic image creation library. It can be used for simple image operations, such as scaling, cropping, adding watermarks, creating thumbnails (written by Jeffrey), applying basic photo filters-you may have used it. Unfortunately, if you want to create more complex effects like the Instagram filter, GD cannot. Fortunately, we have ImageMagick!

GD vs. ImageMagick

They cannot be compared at a high level, so we will use a simple example, such as resizing. We have uploaded a new 640-480-inch photo.jpg image. We need to dynamically adjust the image size to X pixels.

GD

In the following example, we must call six functions. If we have a variable aspect ratio, some calculations may be executed.

$im= imagecreatefromjpeg('photo.jpg'); $ox= imagesx($im);$oy= imagesy($im);  $nx= 640;$ny= 480; $nm= imagecreatetruecolor($nx, $ny);  imagecopyresized($nm,$im,0,0,0,0,$nx,$ny,$ox,$oy);  imagejpeg($nm, 'photo.jpg');

ImageMagick

IM (short for ImageMagick) has a beautiful package called Imagick-native PHP extension. It uses ImageMagick's API to create and modify images. The only drawback is that you may use PECL for installation. Its shared host may sometimes have connection problems.

$image= newImagick('photo.jpg');$image->resizeImage(640, 480,imagick::FILTER_LANCZOS, 0.9);

The simpler method is to use the PHP Command Line (which we will also use ).

exec('mogrify -resize 640x480 photo.jpg');

That's it! Perfect.

Install ImageMagick

Although almost every good server hosting service provider provides ImageMagick installation, you may not install it on the local server because it is not bundled by PHP.

However, installing ImageMagick is easy. Visit the ImageMagick download page, select the Operating System (Unix/Mac/Win) of your server, and select the recommended package. As long as you follow the simple instructions, you will not make mistakes.

Once the installation is complete, go to the terminal Command prompt and enter "convert" and press Enter. If you get a series of options instead of "Command not found", it means that you have successfully installed them. Note that you do not need to perform any configuration in PHP.

How does Instagram work?

To be honest, I don't know what technology the Instagram team uses for image processing. ImageMagick is also available in iOS. Maybe this is the magic source of Instagram? The following is a reference to Instagram CEO and co-founder Kevin Rom.

"It is indeed a combination of many different methods. In some cases, we draw images; in other cases, we perform pixel operations. It really depends on what we want ."

For example, Lomo-fi is not very effective on high-contrast images, while Toaster is one of the most complex (and very slow, very popular) filters.

I will not describe more information, but it will be our secret weapon :) maybe one day...

"Maybe one day ..." Not enough for us, Mr. Systrom. We accept the challenge.

Show Me The Code!

We will simulate the gotham, toaster, nashville, lomo, and kelvin filters.

Instagraph-PHP class

I once created a small PHP packaging class to make the image processing process as simple as possible. As you know, there are many filters:

  • Colortone: colors an image with highlight or shadow. For example, we want to change the black color to purple.
  • Vignette: fades out or gradually fades out the edge of the image. We can even flip or color shadow.
  • Border: Add a Border for the image. For example, we want a black or white border or any colored border with a certain width. Note that the Border width will increase the image size.
  • Frame: Read and stretch the specified photo Frame to fit the image. Nashville and kelvin filters are required.
  • Tempfile: create a temporary file (a copy of the original image ).
  • Output: simply rename the working copy.
  • Execute: we will use this method to send all commands to prevent errors when using shell scripts.

I mentioned this so that we can jump to the interesting part. Create a new file named instagraph. php, but copy and paste the following code.

/** * Instagram filters with PHP and ImageMagick * * @package    Instagraph * @author     Webarto 
 
   * @copyright  NetTuts+ * @license    http://creativecommons.org/licenses/by-nc/3.0/ CC BY-NC */class Instagraph{     public $_image = NULL;    public $_output = NULL;    public $_prefix = 'IMG';    private $_width = NULL;    private $_height = NULL;    private $_tmp = NULL;     public static function factory($image, $output)    {        return new Instagraph($image, $output);    }     public function __construct($image, $output)    {        if(file_exists($image))        {            $this->_image = $image;            list($this->_width, $this->_height) = getimagesize($image);            $this->_output = $output;        }        else        {            throw new Exception('File not found. Aborting.');        }    }     public function tempfile()    {        # copy original file and assign temporary name        $this->_tmp = $this->_prefix.rand();        copy($this->_image, $this->_tmp);    }     public function output()    {        # rename working temporary file to output filename        rename($this->_tmp, $this->_output);    }     public function execute($command)    {        # remove newlines and convert single quotes to double to prevent errors        $command = str_replace(array("\n", "'"), array('', '"'), $command);        $command = escapeshellcmd($command);        # execute convert program        exec($command);    }     /** ACTIONS */     public function colortone($input, $color, $level, $type = 0)    {        $args[0] = $level;        $args[1] = 100 - $level;        $negate = $type == 0? '-negate': '';         $this->execute("convert        {$input}        ( -clone 0 -fill '$color' -colorize 100% )        ( -clone 0 -colorspace gray $negate )        -compose blend -define compose:args=$args[0],$args[1] -composite        {$input}");    }     public function border($input, $color = 'black', $width = 20)    {        $this->execute("convert $input -bordercolor $color -border {$width}x{$width} $input");    }     public function frame($input, $frame)    {        $this->execute("convert $input ( '$frame' -resize {$this->_width}x{$this->_height}! -unsharp 1.5×1.0+1.5+0.02 ) -flatten $input");    }     public function vignette($input, $color_1 = 'none', $color_2 = 'black', $crop_factor = 1.5)    {        $crop_x = floor($this->_width * $crop_factor);        $crop_y = floor($this->_height * $crop_factor);         $this->execute("convert        ( {$input} )        ( -size {$crop_x}x{$crop_y}        radial-gradient:$color_1-$color_2        -gravity center -crop {$this->_width}x{$this->_height}+0+0 +repage )        -compose multiply -flatten        {$input}");    }     /** RESERVED FOR FILTER METHODS */ }
 

Instagram filter

We will create a filter effect one by one. I will explain the necessary PHP functions and ImageMagick commands, including examples. Make sure that you have updated the PHP class to support the following new methods. The downloaded package provides image frames, all of which are PNG transparent images. Let's start.

Original Image

This is a picture of my dog enjoying his life on the beach. It is a work of my camera.


Gotham

The filter generates a black/white, light blue background high contrast image. In real life, this will be done with the Holga camera and Ilford X2 film.

public function gotham(){    $this->tempfile();    $this->execute("convert $this->_tmp -modulate 120,10,100 -fill '#222b6d' -colorize 20 -gamma 0.5 -contrast -contrast $this->_tmp");    $this->border($this->_tmp);    $this->output();}


Text explanation: Create a working file, load the image to the memory, increase the brightness and saturation, change the remaining color to dark purple, Gamma Correction, and increase the contrast, save all changes to a file. Add a black border of 20 pixels. Is it easy?

Toaster

The Toaster filter is similar to the effect of the old Polaroid camera, which has bright colors centered on pink or orange. According to CEO of Instagram, it is one of the most difficult effects to achieve.

public function toaster(){    $this->tempfile();    $this->colortone($this->_tmp, '#330000', 100, 0);     $this->execute("convert $this->_tmp -modulate 150,80,100 -gamma 1.2 -contrast -contrast $this->_tmp");     $this->vignette($this->_tmp, 'none', 'LavenderBlush3');    $this->vignette($this->_tmp, '#ff9966', 'none');     $this->output();}

Tip: You can even add a white border for the complete effect.$this->output();BeforeAdd code$this->border($this->_tmp,'white');.

Text explanation: Create a working file, load the image to the memory, change the black to dark red, increase the brightness, set the saturation to 1/5, and perform Gamma Correction (to make the image brighter ), add more contrast and save. Finally, add a gray shadow (with a little saturation removed from the edge) and an orange flip shadow that achieves the color burning effect.


Nashville

Nashville has a great photo of the 1980s fashion. It generates images in the magenta and pink colors. In addition, it adds a photo frame to get the appearance of the slide. This is one of the easiest and most popular Instagram filters to implement.

public function nashville(){    $this->tempfile();     $this->colortone($this->_tmp, '#222b6d', 100, 0);    $this->colortone($this->_tmp, '#f7daae', 100, 1);     $this->execute("convert $this->_tmp -contrast -modulate 100,150,100 -auto-gamma $this->_tmp");    $this->frame($this->_tmp, __FUNCTION__);     $this->output();}

Text description: Create a working file, load the image to the memory, turn black into indigo, turn white into pink, enhance the contrast, increase the saturation by half, and perform gamma automatic correction. Add a photo frame from a PNG file.


Lomo

Lomography is used to create a high-contrast photo by using the photo frame and focus. In real life, this effect is mostly achieved through Holga, LOMO LC-A or so-called toy camera (camera with plastic lenses. This effect is quite easy to reproduce. We simply increase the contrast of the Red and Green Channels by 1/3 and add a picture frame. You can perform experiments at will.

public function lomo(){    $this->tempfile();     $command = "convert {$this->_tmp} -channel R -level 33% -channel G -level 33% $this->_tmp";     $this->execute($command);    $this->vignette($this->_tmp);     $this->output();}

Tip: If you like the Lomo effect without shadow, you only need to comment out or remove the corresponding code. Text explanation: Create a working file, load the image to the memory, increase the contrast of the red channel by 1/3, increase the contrast of the red channel by 1/3 again, and apply a shadow.


Kelvin

This effect is named Darwin. It uses a strong peach and orange covering layer and adds a fade photo frame.

public function kelvin(){    $this->tempfile();     $this->execute("convert    ( $this->_tmp -auto-gamma -modulate 120,50,100 )    ( -size {$this->_width}x{$this->_height} -fill 'rgba(255,153,0,0.5)' -draw 'rectangle 0,0 {$this->_width},{$this->_height}' )    -compose multiply    $this->_tmp");    $this->frame($this->_tmp, __FUNCTION__);     $this->output();}

Text explanation: Create a working file, load the image to the memory, normalize, increase the brightness by 1/5, increase the saturation by half, create a peach and orange covering layer, and apply the multi-mixed mode. Finally, add a photo frame using a PNG file.


How to Use

You can easily use these effects! I assume that you will save all the code in the instagraph. php file. Create a file named filter. ph and copy the following code.

If you only want to apply a filter to an image, you can do this:

require 'instagraph.php'; try{    $instagraph = Instagraph::factory('input.jpg', 'output.jpg');}catch (Exception $e){    echo $e->getMessage();    die;} $instagraph->toaster(); // name of the filter

It is. Now, if you want to use all the filters for an image, use the following code.

require 'instagraph.php'; try{$instagraph = Instagraph::factory('input.jpg', 'output.jpg');}catch (Exception $e){    echo $e->getMessage();    die;} // loop through all filters foreach(array('gotham', 'toaster', 'nashville', 'lomo', 'kelvin') as $method){    $instagraph->_output = $method.'.jpg'; // we have to change output file to prevent overwrite    $instagraph->$method(); // apply current filter (from array)}

Now you only need to open this page in the browser to get the desired result.

Performance

Performance must be an important part of every application. Because the average time used to apply a filter to an image is about one second, we can say it is quite fast!

ImageMagick Resources

To learn more

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.