PHP GD Library, Crop images dynamically in php

PHP image GD library.

imagejpeg() creates a JPEG file from the given image.

bool imagejpeg ( resource $image [, string $filename [, int $quality ]] )

  • image :- An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().
  • filename :- The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.
  • quality :- quality is optional, and ranges from 0 to 100. The default is the default IJG quality value 75.
  • Syntax :-

    bool imagejpeg ( resource $image [, string $filename [, int $quality ]] )

    File name index1.php

    <?php
    // Create a blank image and add some text
    $im = imagecreatetruecolor(300, 120); // set image dimension
    $text_color = imagecolorallocate($im, 255, 255, 255); // set text color.

    imagestring($im, 20, 100, 5, 'A Simple Text String', $text_color);

    // // Set the content type header - in this case image/jpeg
    header('Content-Type: image/jpeg');

    // Output the image
    imagejpeg($im);

    // Free up memory
    imagedestroy($im);
    ?>

    Output :-

    here $im is the image and first cordinate is the font size, second is the x coordinate and third is the y coodinate.

    Save images into your project directory.

    File name index1.php

    <?php
    // Create a blank image and add some text
    $im = imagecreatetruecolor(120, 20);
    $text_color = imagecolorallocate($im, 233, 14, 91);
    imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);

    // Save the image as 'simpletext.jpg'
    imagejpeg($im, 'simpletext.jpg');

    // Free up memory
    imagedestroy($im);
    ?>

    How to get image name with extension or without extension.

    File name index1.php

    <?php
    $url ='img/mahtab.jpg';
    $name = basename($url);
    echo $name;
    echo "OR";
    echo "<br/>";
    $img = explode(".", basename($url));

    echo $img['0'];
    ?>

    Save images into your directory with quality.

    File name index1.php

    <?php
    // Create a blank image and add some text
    $dest = imagecreatetruecolor(120, 20);
    $text_color = imagecolorallocate($dest, 233, 14, 91);
    imagestring($dest, 1, 5, 5, 'A Simple Text String', $text_color);

    // Save the image as 'simpletext.jpg'
    imagejpeg($dest, 'simpletext.jpg');
    $name = "simple";

    imagejpeg($dest, "img/".$name.".jpg", 80);
    // Skip the filename parameter using NULL, then set the quality to 75%
    imagejpeg($dest, NULL, 75);

    // Free up memory
    imagedestroy($dest);
    ?>

    imagescreate () function.

    imagecreate ( int $width , int $height )

    imagecreate() returns an image identifier representing a blank image of specified size.

    we recommend the use of imagecreatetruecolor() instead of imagecreate() so that image processing occurs on the highest quality image possible. If you want to output a palette image, then imagetruecolortopalette() should be called immediately before saving the image with imagepng() or imagegif().

    File name index1.php

    <?php
    header("Content-Type: image/png");
    $im = @imagecreate(300, 200)
    or die("Cannot Initialize new GD image stream");
    $background_color = imagecolorallocate($im, 0, 0, 0);
    $text_color = imagecolorallocate($im, 233, 14, 91);
    imagestring($im, 20, 50, 50, "mahtab habib", $text_color);
    imagepng($im);
    imagedestroy($im);
    ?>

    imagedestroy() function

    bool imagedestroy ( resource $image )
    imagedestroy() frees any memory associated with image image.

    image :- An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

    File name : index.php

    <?php
    // create a 100 x 100 image
    $im = imagecreatetruecolor(100, 100);

    // alter or save the image

    // frees image from memory
    imagedestroy($im);
    ?>

    imagecreatetruecolor() function

    imagecreatetruecolor ( int $width , int $height )
    imagecreatetruecolor() returns an image identifier representing a black image of the specified size.

    File name : index.php

    <?php
    header ('Content-Type: image/png');
    $im = imagecreatetruecolor(120, 20)
    or die('Cannot Initialize new GD image stream');
    $text_color = imagecolorallocate($im, 233, 14, 91);
    imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
    imagepng($im);
    imagedestroy($im);
    ?>

    create transparent image

    If you want to create a *transparent* PNG image, where the background is fully transparent, and all draw operations happen on-top of this, then do the following:

    File name : index.php

    <?php
    $png = imagecreatetruecolor(800, 600);
    imagesavealpha($png, true);

    $trans_colour = imagecolorallocatealpha($png, 0, 0, 0, 127);
    imagefill($png, 0, 0, $trans_colour);

    $red = imagecolorallocate($png, 255, 0, 0);
    imagefilledellipse($png, 400, 300, 400, 300, $red);

    header("Content-type: image/png");
    imagepng($png);
    ?>

    What you do is create a true colour image, make sure that the alpha save-state is on, then fill the image with a colour that has had its alpha level set to fully transparent (127). The resulting PNG from the code above will have a red circle on a fully transparent background (drag the image into Photoshop to see for yourself)


    File name : index.php

    <?php
    // Set the content-type

    header('Content-type: image/png');

    // Create the image
    $im = imagecreatetruecolor(200, 100);
    imagesavealpha($im, true);

    // Create some colors
    $white = imagecolorallocate($im, 255, 255, 255);
    $grey = imagecolorallocate($im, 128, 128, 128);
    $black = imagecolorallocate($im, 50, 123, 0);
    imagefilledrectangle($im, 0, 0, 150, 25, $black);
    $trans_colour = imagecolorallocatealpha($im, 0, 0, 0, 127);
    imagefill($im, 0, 0, $trans_colour);

    // The text to draw

    //$text = $_GET['text'];
    $text = "mahtab";

    // Replace path by your own font path
    $font = 'font.ttf';

    // Add some shadow to the text
    imagettftext($im, 9, 0, 13, 16, $black, $font, $text);

    // Add the text
    imagettftext($im, 9, 0, 12, 15, $white, $font, $text);

    // Using imagepng() results in clearer text compared with imagejpeg()
    imagepng($im);
    imagedestroy($im);
    ?>

    imagecreatefromjpeg() function

    imagecreatefromjpeg ? Create a new image from file or URL

    imagecreatefromjpeg ( string $filename )
    imagecreatefromjpeg() returns an image identifier representing the image obtained from the given filename.

    File name : index.php

    <?php

    $imgname = "img/simple.jpg";
    //$dest = imagecreatefromjpeg($imgname);
    $dest = imagecreatefromjpeg("simpletext.jpg");

    header('Content-Type: image/jpeg');
    imagejpeg($dest);

    ?>

    masking images

    File name : index.php

    <?php

    $imgname = "img/simple.jpg";
    //$dest = imagecreatefromjpeg($imgname);
    $dest = imagecreatefromjpeg("1.jpg");

    $src = imagecreatefromjpeg($imgname);


    $width = imagesx($src);
    $height = imagesy($src);
    $newwidth = 190;
    $newheight = 190;
    $image = imagecreatetruecolor($newwidth, $newheight);
    imagealphablending($image,true);
    imagecopyresampled($image,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

    // create masking
    $mask = imagecreatetruecolor($width, $height);
    $mask = imagecreatetruecolor($newwidth, $newheight);
    $transparent = imagecolorallocate($mask, 255, 0, 0);
    imagecolortransparent($mask, $transparent);
    imagefilledellipse($mask, $newwidth/2, $newheight/2, $newwidth, $newheight, $transparent);
    $red = imagecolorallocate($mask, 0, 0, 0);
    imagecopymerge($image, $mask, 0, 0, 0, 0, $newwidth, $newheight,100);
    imagecolortransparent($image, $red);
    imagefill($image,0,0, $red);


    imagecopymerge($dest, $image, 50, 115, 0, 0, $newwidth, $newheight,100);

    ?>

    File name : index.php

    <?php
    function LoadJpeg($imgname)
    {
    /* Attempt to open */
    $im = imagecreatefromjpeg($imgname);

    /* See if it failed */
    if(!$im)
    {
    /* Create a black image */
    $im = imagecreatetruecolor(150, 30);
    $bgc = imagecolorallocate($im, 255, 255, 255);
    $tc = imagecolorallocate($im, 0, 0, 0);

    imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

    /* Output an error message */
    imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
    }

    header('Content-Type: image/jpeg');

    $img = LoadJpeg('1.jpg');

    imagejpeg($img);
    imagedestroy($img);
    ?>

    imagecreatefrompng() function

    imagecreatefrompng ? Create a new image from file or URL

    imagecreatefrompng ( string $filename )
    imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.

    File name : index.php

    <?php

    $imgname = "img/simple.jpg";
    //$dest = imagecreatefrompng($imgname);
    $dest = imagecreatefrompng("simpletext.jpg");

    header('Content-Type: image/png');
    imagepng($dest);

    ?>

    File name : index.php

    <?php
    function Loadpngimage($imgname)
    {
    /* Attempt to open */
    $im = imagecreatefrompng($imgname);

    /* See if it failed */
    if(!$im)
    {
    /* Create a black image */
    $im = imagecreatetruecolor(150, 30);
    $bgc = imagecolorallocate($im, 255, 255, 255);
    $tc = imagecolorallocate($im, 0, 0, 0);

    imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

    /* Output an error message */
    imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
    }

    header('Content-Type: image/png');

    $img = Loadpngimage('1.png');

    imagepng($img);
    imagedestroy($img);
    ?>

    images create from string.

    imagecreatefromstring ( string $image )
    imagecreatefromstring() returns an image identifier representing the image obtained from the given image. These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, WBMP, and GD2.

    image :- A string containing the image data.

    File name : index.php

    <?php
    $data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
    . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
    . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
    . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
    $data = base64_decode($data);

    $im = imagecreatefromstring($data);
    if ($im !== false) {
    header('Content-Type: image/png');
    imagepng($im);
    imagedestroy($im);
    }
    else {
    echo 'An error occurred.';
    }
    ?>

    File name : index.php

    <?php


    $src = "http://itechtuto.com/logo/itechaio_logo.png";
    $image = imagecreatefromstring(file_get_contents($src));
    header('Content-Type: image/png');
    imagepng($image);


    ?>

    File name : index.php

    <?
    $loadFile = "http://itechtuto.com/images/php.gif";

    $im = imagecreatefromstring(file_get_contents($loadFile));
    // identical to imagecreatefromgif($loadFile);
    imagegif($im);
    ?>

    file_get_contents()

    file_get_contents() returns the file in a string.

    Syntax
    file_get_contents(path,include_path,context,start,max_length)

    File name : index.php


    <?php
    $homepage = file_get_contents('http://www.example.com/');
    echo $homepage;
    $file = file_get_contents('./people.txt', true); ?>

    imagecopymerge() function

    imagecopymerge ? Copy and merge part of an image

    imagecopymerge ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct )

    Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

    pct : The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy() for pallete images, except for ignoring alpha components, while it implements alpha transparency for true colour images.

    File name : index.php

    <?php
    // Create image instances
    $dest = imagecreatefromjpeg("1.jpg");
    $src = imagecreatefromjpeg("simpletext.jpg");

    // Copy and merge
    imagecopymerge($dest, $src, 10, 10, 0, 0, 100, 47, 75);

    // Output and free from memory
    header('Content-Type: image/gif');
    imagejpeg($dest);

    imagedestroy($dest);
    imagedestroy($src);
    ?>

    imagecopy() function

    imagecopy ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h )

    Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

    File name : index.php

    <?php
    // Create image instances

    $src = imagecreatefromjpeg("1.jpg");


    $dest = imagecreatetruecolor(500, 400);

    // Copy
    imagecopy($dest, $src, 50, 50, 200, 200, 150, 200);

    // Output and free from memory
    header('Content-Type: image/jpeg');
    imagejpeg($dest);

    imagedestroy($dest);
    imagedestroy($src);
    ?>

    imagettftext() function.

    imagettftext ? Write text to the image using TrueType fonts

    imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )

    Parameters

  • image :- An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().
  • size :- The font size. Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2).
  • angle :- The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text.
  • x :- The coordinates given by x and y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x and y define the upper-left corner of the first character. For example, "top left" is 0, 0.
  • y :- The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.
  • color :- The color index. Using the negative of a color index has the effect of turning off antialiasing. See imagecolorallocate().
  • fontfile :- The path to the TrueType font you wish to use.
  • File name : index.php

    <?php
    // Set the content-type
    header('Content-Type: image/png');

    // Create the image
    $im = imagecreatetruecolor(400, 30);

    // Create some colors
    $white = imagecolorallocate($im, 255, 255, 255);
    $grey = imagecolorallocate($im, 128, 128, 128);
    $black = imagecolorallocate($im, 0, 0, 0);
    imagefilledrectangle($im, 0, 0, 399, 29, $white);

    // The text to draw
    $text = 'Testing...';
    // Replace path by your own font path
    $font = 'font.ttf';

    // Add some shadow to the text
    imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

    // Add the text
    imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

    // Using imagepng() results in clearer text compared with imagejpeg()
    imagepng($im);
    imagedestroy($im);
    ?>

    File name : index.php

    <?php
    // Set the content-type
    header('Content-Type: image/png');
    // Create the image
    $im = imagecreatefromjpeg("1.jpg");
    // Create some colors
    $black = imagecolorallocate($im, 255, 255, 255);
    // The text to draw
    $text = 'mahtab habib';
    // Replace path by your own font path
    $font = 'font.ttf';
    // Add the text
    imagettftext($im, 25, 0, 70, 200, $black, $font, $text);
    // Using imagepng() results in clearer text compared with imagejpeg()
    imagepng($im);
    imagedestroy($im);
    ?>

    imagettfbbox() function

    imagettfbbox ? Give the bounding box of a text using TrueType fonts

    imagettfbbox ( float $size , float $angle , string $fontfile , string $text )
    This function calculates and returns the bounding box in pixels for a TrueType text.

    Parameters :-

  • size :- The font size. Note: In GD 1, this is measured in pixels. In GD 2, this is measured in points.
  • angle :- Angle in degrees in which text will be measured.
  • fontfile : The name of the TrueType font file (can be a URL). Depending on which version of the GD library that PHP is using, it may attempt to search for files that do not begin with a leading '/' by appending '.ttf' to the filename and searching along a library-defined font path.
  • text The string to be measured.
  • File name : index.php

    <?php
    // Create a 300x150 image
    $im = imagecreatetruecolor(300, 150);
    $black = imagecolorallocate($im, 0, 0, 0);
    $white = imagecolorallocate($im, 255, 0, 0);

    // Set the background to be white
    imagefilledrectangle($im, 0, 0, 299, 299, $white);

    // Path to our font file
    $font = 'font.ttf';

    // First we create our bounding box for the first text
    $bbox = imagettfbbox(10, 45, $font, 'Powered by PHP ' . phpversion());

    // This is our cordinates for X and Y
    $x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) - 25;
    $y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;

    // Write it
    imagettftext($im, 10, 45, $x, $y, $black, $font, 'Powered by PHP ' . phpversion());

    // Create the next bounding box for the second text
    $bbox = imagettfbbox(10, 45, $font, 'and Zend Engine ' . zend_version());

    // Set the cordinates so its next to the first text
    $x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) + 10;
    $y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;

    // Write it
    imagettftext($im, 10, 45, $x, $y, $black, $font, 'and Zend Engine ' . zend_version());

    // Output to browser
    header('Content-Type: image/png');

    imagepng($im);
    imagedestroy($im);
    ?>

    How to set text in center on image

    Using imagettfbbox()

    File name : index.php

    <?php
    // Create a 300x150 image
    //$im = imagecreatetruecolor(500, 300);
    $imgname = "img/1.jpg";
    $im = imagecreatefromjpeg($imgname);

    $black = imagecolorallocate($im, 255, 255, 255);
    $white = imagecolorallocate($im, 0, 0, 0);



    // Set the background to be white
    //imagefilledrectangle($im, 0, 0, 299, 299, $white);

    $name = "md mahtab alam";
    // Path to our font file
    $font = 'Xerox Sans Serif Wide Bold.ttf';

    // First we create our bounding box for the first text
    $box = ImageTTFBBox(15, 0, $font, $name);

    $xr = abs(max($box[2], $box[4]));
    $yr = abs(max($box[5], $box[7]));
    // compute centering
    $x = intval((800 - $xr) / 2);
    $y = intval((420 + $yr) / 2);

    imagettftext($im, 15, 0, $x, $y, $black, $font, $name);

    // Output to browser
    header('Content-Type: image/png');

    imagepng($im);
    imagedestroy($im);

    ?>

    How to set text in center on image

    Using imagettfbbox()

    File name : index.php

    <?php
    /* $image = imagecreate(400,300);
    $blue = imagecolorallocate($image, 0, 0, 255);
    $white = ImageColorAllocate($image, 255,255,255);

    if(!isset($_GET['size'])) $_GET['size'] = 20;
    if(!isset($_GET['text'])) $_GET['text'] = "Hello, world!";
    $font = 'Xerox Sans Serif Wide Bold.ttf';
    imagettftext($image, $_GET['size'], 15, 50, 200, $white, $font, $_GET['text']);
    header("content-type: image/png");
    imagepng($image);
    imagedestroy($image);

    */





    if(!isset($_GET['size'])) $_GET['size'] = 40;
    if(!isset($_GET['text'])) $_GET['text'] = "Hello, world!";

    $font = 'Xerox Sans Serif Wide Bold.ttf';

    $size = imagettfbbox($_GET['size'], 0, $font, $_GET['text']);
    $xsize = abs($size[0]) + abs($size[2]);
    $ysize = abs($size[5]) + abs($size[1]);

    $image = imagecreate($xsize, $ysize);
    $blue = imagecolorallocate($image, 0, 0, 255);
    $white = ImageColorAllocate($image, 255,255,255);
    imagettftext($image, $_GET['size'], 0, abs($size[0]), abs($size[5]), $white, $font, $_GET['text']);

    header("content-type: image/png");
    imagepng($image);
    imagedestroy($image);



    ?>

    File name : index.php

    <?php

    function calculateTextBox($text,$fontFile,$fontSize,$fontAngle) {
    /************
    simple function that calculates the *exact* bounding box (single pixel precision).
    The function returns an associative array with these keys:
    left, top: coordinates you will pass to imagettftext
    width, height: dimension of the image you have to create
    *************/
    $rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text);
    $minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
    $maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6]));
    $minY = min(array($rect[1],$rect[3],$rect[5],$rect[7]));
    $maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7]));

    return array(
    "left" => abs($minX) - 1,
    "top" => abs($minY) - 1,
    "width" => $maxX - $minX,
    "height" => $maxY - $minY,
    "box" => $rect
    );
    }

    // Example usage - gif image output

    $text_string = "Hello World";
    $font_ttf = "font.ttf";
    $font_size = 22;
    $text_angle = 0;
    $text_padding = 10; // Img padding - around text

    $the_box = calculateTextBox($text_string, $font_ttf, $font_size, $text_angle);

    $imgWidth = $the_box["width"] + $text_padding;
    $imgHeight = $the_box["height"] + $text_padding;

    $image = imagecreate($imgWidth,$imgHeight);
    imagefill($image, imagecolorallocate($image,200,200,200));

    $color = imagecolorallocate($image,0,0,0);
    imagettftext($image,
    $font_size,
    $text_angle,
    $the_box["left"] + ($imgWidth / 2) - ($the_box["width"] / 2),
    $the_box["top"] + ($imgHeight / 2) - ($the_box["height"] / 2),
    $color,
    $font_ttf,
    $text_string);

    header("Content-Type: image/gif");
    imagegif($image);
    imagedestroy($image);

    ?>

    imagecopyresampled() Function

    imagecopyresampled ? Copy and resize part of an image with resampling

    syntax :
    imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )

    imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity. In other words, imagecopyresampled() will take a rectangular area from src_image of width src_w and height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x,dst_y).

    File name : index.php

    <?php
    // The file
    $filename = 'test.jpg';
    $percent = 0.5;

    // Content type
    header('Content-Type: image/jpeg');

    // Get new dimensions
    list($width, $height) = getimagesize($filename);
    $new_width = $width * $percent;
    $new_height = $height * $percent;

    // Resample
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($filename);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    // Output
    imagejpeg($image_p, null, 100);
    ?>

    File name : index.php

    <?php
    // The file
    $filename = 'test.jpg';

    // Set a maximum height and width
    $width = 200;
    $height = 200;

    // Content type
    header('Content-Type: image/jpeg');

    // Get new dimensions
    list($width_orig, $height_orig) = getimagesize($filename);

    $ratio_orig = $width_orig/$height_orig;

    if ($width/$height > $ratio_orig) {
    $width = $height*$ratio_orig;
    } else {
    $height = $width/$ratio_orig;
    }

    // Resample
    $image_p = imagecreatetruecolor($width, $height);
    $image = imagecreatefromjpeg($filename);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

    // Output
    imagejpeg($image_p, null, 100);
    ?>

    Image resized

    File name : index.php

    <?php
    // File and new size
    $filename = 'test.jpg';
    $percent = 0.5;

    // Content type
    header('Content-Type: image/jpeg');

    // Get new sizes
    list($width, $height) = getimagesize($filename);
    $newwidth = $width * $percent;
    $newheight = $height * $percent;

    // Load
    $thumb = imagecreatetruecolor($newwidth, $newheight);
    $source = imagecreatefromjpeg($filename);

    // Resize
    imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    // Output
    imagejpeg($thumb);
    ?>

    imagealphablending()

    imagealphablending ? Set the blending mode for an image.

    imagealphablending() allows for two different modes of drawing on truecolor images. In blending mode, the alpha channel component of the color supplied to all drawing function, such as imagesetpixel() determines how much of the underlying color should be allowed to shine through. As a result, gd automatically blends the existing color at that point with the drawing color, and stores the result in the image. The resulting pixel is opaque. In non-blending mode, the drawing color is copied literally with its alpha channel information, replacing the destination pixel. Blending mode is not available when drawing on palette images.

    File name : index.php

    <?php
    // Create image
    $im = imagecreatetruecolor(100, 100);

    // Set alphablending to on
    imagealphablending($im, true);

    // Draw a square
    imagefilledrectangle($im, 30, 30, 70, 70, imagecolorallocate($im, 255, 0, 0));

    // Output
    header('Content-type: image/png');

    imagepng($im);
    imagedestroy($im);
    ?>

    PHP / GD Text Watermarking Example

    Text watermarking functions are,
    imagestring() ? Adding text string into images.
    imagettftext() ? Adding text into images using True Type Fonts.

    Syntax
    imagestring($image, $font, $x, $y, $watermarkText, $watermarkColor);
    imagettftext($image, $fontSize, $watermarkAngle, $x, $y, $watermarkColor, $fontFilePath, $watermarkText);
    The imagestring() function is sufficient for adding simple watermark without more gimmicks. To add effects like angled text as watermark, imagettftext() function can be used. It provides rich set of effects.

    File name : index.php

    <?php
    $imageURL = "bg.png";
    list($width,$height) = getimagesize($imageURL);
    $imageProperties = imagecreatetruecolor($width, $height);
    $targetLayer = imagecreatefrompng($imageURL);
    imagecopyresampled($imageProperties, $targetLayer, 0, 0, 0, 0, $width, $height, $width, $height);
    $WaterMarkText = 'itechtuto.com';
    $watermarkColor = imagecolorallocate($imageProperties, 191,191,191);
    imagestring($imageProperties, 5, 130, 117, $WaterMarkText, $watermarkColor);
    header('Content-type: image/jpeg');
    imagepng ($imageProperties);
    imagedestroy($targetLayer);
    imagedestroy($imageProperties);
    ?>

    How to create captcha image using php gd.

    File name : index.php

    session_start();
    $random_alpha = md5(rand());
    $captcha_code = substr($random_alpha, 0, 6);
    $_SESSION["captcha_code"] = $captcha_code;
    $target_layer = imagecreatetruecolor(70,30);
    $captcha_background = imagecolorallocate($target_layer, 255, 160, 119);
    imagefill($target_layer,0,0,$captcha_background);
    $captcha_text_color = imagecolorallocate($target_layer, 0, 0, 0);
    imagestring($target_layer, 5, 5, 5, $captcha_code, $captcha_text_color);
    header("Content-type: image/jpeg");
    imagejpeg($target_layer);

    Php image resize using php gd.

    some step of image resizing.

  • Get image resource id for source image.
  • Get resource id for target image layer.
  • Resizing and reassembling the image.
  • Save resized image into given target location.
  • These functions are used to get image file resource id. For example, imagecreatefromjpeg(), imagecreatefromgif(), imagecreatefrompng(), used to get the resource identifier for JPEG, GIF and PNG images.

    Get Image Resource Id for Source Image.

    first we need to get image type by using PHP function getimagesize(), which is used for getting entire list of image properties, including width, height

    $file = "christmas.jpg";
    $source_properties = getimagesize($file);
    $image_type = $source_properties[2];
    if( $image_type == IMAGETYPE_JPEG ) {
    $image_resource_id = imagecreatefromjpeg($file);
    }
    elseif( $image_type == IMAGETYPE_GIF ) {
    $image_resource_id = imagecreatefromgif($file); }
    elseif( $image_type == IMAGETYPE_PNG ) {
    $image_resource_id = imagecreatefrompng($file); }

    The constants used in conditional statements are predefined with appropriate integer value denotes image type. For example, IMAGETYPE_JPEG defined with value 2 which is used for indicating JPEG image.

    Get Resource Id for Target Image Layer

    we need to create new image as a target layer. This image will be created with the dimensions to what the original image is expected to be resized.
    PHP built-in function, named as, imagecreatetruecolor() is used for this purpose, by accepting required dimensions, that is, the width and height of the target image. For example,
    $target_width =200;
    $target_height =200;
    $target_layer=imagecreatetruecolor($target_width,$target_height);

    imagecreatetruecolor() function will create empty image. Added to that, it will return resource data identifier as a reference to the newly created image with specified width and height parameter. This reference will be used in subsequent steps, for mentioning target, on top of which the resized image will be assembled.

    Resizing and Reassembling

    imagecopyresampled() for such resizing and reassembling process. For example,
    imagecopyresampled($target_layer,$image_resource_id,0,0,0,0,$target_width,$target_height, $source_properties[0],$source_properties[1]);

    Save Resized Image into Target Location

    imagejpeg($target_layer,"christmas_thump.jpg");
    Code sample shown in each step is applicable only for JPEG image. We can replicate the same for other image types by using appropriate PHP functions.

    File name : index.php

    <?php
    if(isset($_POST["submit"])) {
    if(is_array($_FILES)) {
    $file = $_FILES['myImage']['tmp_name'];
    $source_properties = getimagesize($file);
    $image_type = $source_properties[2];
    if( $image_type == IMAGETYPE_JPEG ) {
    $image_resource_id = imagecreatefromjpeg($file);
    $target_layer = fn_resize($image_resource_id,$source_properties[0],$source_properties[1]);
    imagejpeg($target_layer,$_FILES['myImage']['name'] . "_thump.jpg");
    }
    elseif( $image_type == IMAGETYPE_GIF ) {
    $image_resource_id = imagecreatefromgif($file);
    $target_layer = fn_resize($image_resource_id,$source_properties[0],$source_properties[1]);
    imagegif($target_layer,$_FILES['myImage']['name'] . "_thump.gif");
    }
    elseif( $image_type == IMAGETYPE_PNG ) {
    $image_resource_id = imagecreatefrompng($file);
    $target_layer = fn_resize($image_resource_id,$source_properties[0],$source_properties[1]);
    imagepng($target_layer,$_FILES['myImage']['name'] . "_thump.png");
    }
    }
    }
    function fn_resize($image_resource_id,$width,$height) {
    $target_width =200;
    $target_height =200;
    $target_layer=imagecreatetruecolor($target_width,$target_height);
    imagecopyresampled($target_layer,$image_resource_id,0,0,0,0,$target_width,$target_height, $width,$height);
    return $target_layer;
    }
    ?>

    imagesx() and imagesy()

    The imagesx() and imagesy() are used to extract the width and height of the images respectively. For that, it accept the resource type of data which will be returned on creating new images dynamically using PHP script.

    getimagesize()

    This PHP method that returns array of image properties like width, height, image type, mime type and etc. This method will return limited amount of image data.

    <?php
    if(isset($_POST["submit"])) {
    if(is_array($_FILES)) {
    $image_properties = getimagesize($_FILES['myImage']['tmp_name']);
    print "<PRE>";
    print_r($image_properties);
    print "</PRE>";
    }
    }
    ?>

    This script will be executed on submitting the form, and the image file is added with PHP global array, that is, $_FILES. After ensuring that the $_FILES is not empty, then, we should specify the name of the file to getimagesize() as shown above. Finally, image properties are returned as an array and displayed to the browser.

    Array
    (
    [0] => 1024
    [1] => 768
    [2] => 2
    [3] => width="1024" height="768"
    [bits] => 8
    [channels] => 3
    [mime] => image/jpeg
    )

    exif_read_data()

    getimagesize() functions will return limited set of properties, exif_read_data() is used to get more information further associated with images. So, added to the width, height information, it will return huge list of additional information such as image created date, last modified date, File name, size, orientation, resolution and etc.
    This function will be used to extract properties of digital images in which Exif data is stored into its header. Exif is a standard format, that can be expanded as Exchangeable Image Format.
    Image types are of 16 totally, which varies based on the devices used to capture images. Image types are returned as numbers that are associated with the available types of images like gif, png and etc. For example, if image type returned as 2 denotes that, it is JPEG image.


    File name : index.php

    $image_properties = getimagesize($_FILES['myImage']['tmp_name']);
    $image_properties = exif_read_data($_FILES['myImage']['tmp_name']);

    How to rotate image using php gd.

    File name : index.php

    <?php
    function create_image($img) {
    $im = @imagecreatefromjpeg($img) or die("Cannot Initialize new GD image stream");
    //$rotate = imagerotate($im, 180, 0);
    $rotate = imagerotate($im, 20, 0);

    imagejpeg($rotate);
    imagedestroy($rotate);
    imagedestroy($im);
    }

    header('Content-Type: image/jpeg');
    $image = "1.jpg";
    create_image($image);
    ?>
    //$rotate = imagerotate($source, 0, 5);
    //imagecopymerge($dest, $rotate,602,50, 5, 0, $newwidth, $newheight,100);


    File name : index.php

    $src = imagecreatefromjpeg($path);


    $width = imagesx($src);
    $height = imagesy($src);
    $newwidth = 190;
    $newheight = 190;
    $image = imagecreatetruecolor($newwidth, $newheight);
    imagealphablending($image,true);
    imagecopyresampled($image,$src,0,0,0,0,$newwidth,$newheight,$width,$height);


    $rotate = imagerotate($image, 10, 0);

    imagecopymerge($dest, $rotate, 200, 80, 0, 0, $newwidth, $newheight,100);

    File name : index.php

    <?php
    $filename = '1.jpg';
    $rotang = 20; // Rotation angle
    $source = imagecreatefromjpeg($filename) or die('Error opening file '.$filename);
    imagealphablending($source, false);
    imagesavealpha($source, true);

    $rotation = imagerotate($source, $rotang, imageColorAllocateAlpha($source, 255, 255, 255, 127));
    imagealphablending($rotation, false);
    imagesavealpha($rotation, true);

    header('Content-type: image/jpeg');
    imagejpeg($rotation);
    imagedestroy($source);
    imagedestroy($rotation);
    ?>

    Howo to Rotate Text using php GD

    File name : index.php

    $angle = 10; $ar = array('how r u','i am fine','what happen','i m going','why r u going');
    $ran = $ar[array_rand($ar, 1)];

    $result = $profilename1." " .$ran;

    imagettftext( $dest, 20, $angle, 136, 106, $fontcolor1, $font, $result);

    How to filter images.

    you can color effect on images using php gd.

    File name : index.php

    $src = imagecreatefromjpeg($path);

    if(imagefilter($src, IMG_FILTER_GRAYSCALE))
    {
    imagejpeg($src, "bwimg/".$fbid.".jpg", 80);
    }
    $src_bw = "http://billicat.me/alcohaltest/bwimg/".$fbid.".jpg";
    $src1 = imagecreatefromjpeg($src_bw);

    $width = imagesx($src1);
    $height = imagesy($src1);
    $newwidth = 200;
    $newheight = 200;
    $image = imagecreatetruecolor($newwidth, $newheight);
    imagealphablending($image,true);
    imagecopyresampled($image,$src1,0,0,0,0,$newwidth,$newheight,$width,$height);

    imagecopymerge($dest, $image, 45, 115, 0, 0, $newwidth, $newheight,100);

    <?php


    $im = imagecreatefromjpeg('img/1.jpg');

    if($im && imagefilter($im, IMG_FILTER_GRAYSCALE))
    {
    echo 'Image converted to grayscale.';

    header('Content-type: image/jpeg');
    // Output
    //imagejpeg($im, '1.jpg');
    imagejpeg($im,'1.jpg');

    }
    else
    {
    echo 'Conversion to grayscale failed.';
    }
    imagedestroy($im);
    ?>

    How to put stroke on text of images.

    you can color effect on images using php gd.

    File name : index.php

    $font = "fonts/font.ttf";
    $font1 = "fonts/font1.ttf";
    $fontcolor1 = imagecolorallocate($dest, 0,0,0);
    $font_color = imagecolorallocate($dest, 255, 255, 255);
    $stroke_color = imagecolorallocate($dest, 250, 128, 114);

    function imagettfstroketext(&$image, $size, $angle, $x, $y, &$textcolor, &$strokecolor, $fontfile, $text, $px) {
    for($c1 = ($x-abs($px)); $c1 <= ($x+abs($px)); $c1++)
    for($c2 = ($y-abs($px)); $c2 <= ($y+abs($px)); $c2++)
    $bg = imagettftext($image, $size, $angle, $c1, $c2, $strokecolor, $fontfile, $text);
    return imagettftext($image, $size, $angle, $x, $y, $textcolor, $fontfile, $text);
    }

    imagettfstroketext($dest, 35, 0, 20, 375, $fontcolor1, $stroke_color, $font1, $profilename1, 2);


    //imagettftext( $dest, 30, 0, 20, 375, $fontcolor1, $font1, $profilename1);





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here