File Manipulation Code
  Home arrow File Manipulation Code arrow PHP Class: Image Snapshot 1.3
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Download TestComplete 
Forums Sitemap 
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
FILE MANIPULATION CODE

PHP Class: Image Snapshot 1.3
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    2006-08-28

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Inspired by Backpackit.com’s image management, Image Snapshot can take a portion of an image (crop) to specific dimensions, from different areas of the original image.

    This class has been created for the purpose of manipulating an uploaded image, and creating a Thumbnail image that does not alter the aspect ratio, and yet represents the contents of the original image. I’m sure other uses can be found for the Image Snapshot class, but I’ll leave that to you. I use it for Photo Galleries, and Shopping Cart systems.

    This class supports:

    * Jpg, Gif, Png files
    * Output to Jpg
    * Can resize images before applying the crop
    * Can crop from any part of the image

    An online manual exists for more customizations: http://blog.jc21.com/files/snapshot_manual.pdf

    By : jc21com

    <?php
    /*
    IMAGE SNAPSHOT CLASS - www.jc21.com
    VERSION 1.3 ------------------------------------------------------

    Can accept JPG, GIF and PNG files.
    Refer to manual if you're confused:
    http://blog.jc21.com/files/snapshot_manual.pdf

    WARNING
    ------------------------------------------------------

    Will save all images as JPG.

    USAGE: ------------------------------------------------------

    include('snapshot.class.php'); //this file
    $myimage = new ImageSnapshot; //new instance
    //if using this as an action to a form:
    $myimage->ImageField = $_FILES['userfile']; //uploaded file array
    //OR if you have the contents of the image as a variable:
    $myimage->ImageContents = $the_image_contents; //image data
    //OR if you want to use an image that is already saved:
    $myimage->ImageFile = $_SERVER['DOCUMENT_ROOT'] . '/images/myimage.jpg'; //image file, as an example. Path can be relative or absolute.

    $myimage->Width = 100; //width of output image
    $myimage->Height = 100; //height of output image
    $myimage->Resize = true; //resize image before crop
    $myimage->ResizeScale = 50; //between 1 and 100, 0 for no resizing before crop, 100 to shrink image completely before crop
    $myimage->Position = 'center'; //can be 'center' (default), 'random', 'topleft', 'topcenter', 'topright', 'bottomleft', 'bottomcenter', 'bottomright','custom'
    $myimage->CustomPositionX = 25; //0 to 100. Only needed it Position is 'custom'. This specifies the position of the Snapshot along the X axis, in percentage. 25, is 25% from the left.
    $myimage->CustomPositiony = 35; //0 to 100. Only needed it Position is 'custom'. This specifies the position of the Snapshot along the Y axis, in percentage. 35, is 35% from the top.
    $myimage->Compression = 80; //jpg compression level

    //if you want to save as a file:
    if ($myimage->SaveImageAs('temp.jpg')) {
    echo '<img src="temp.jpg" border="0" width="' . $myimage->ReturnedWidth . '" height="' . $myimage->ReturnedHeight . '" alt="test" />';
    } else {
    echo $myimage->Err;
    }

    //OR if you want to get the contents into a variable:
    if ($myimage->ProcessImage() !== false) {
    $img = $myimage->GetImageContents();
    } else {
    echo $myimage->Err;
    }




    CHANGE LOG:
    ------------------------------------------------------
    05-12-2005 1.3 Release
    05-12-2005 Added: ImageFile field, can now load image from saved file.
    05-12-2005 Added: custom position type, specify by percentages. Read updated manual for help with this.
    28-11-2005 1.2 Release
    28-11-2005 Added: ReturnedWidth and ReturnedHeight variables, for more feedback.
    28-11-2005 Fixed: if crop area was bigger than original image, mixed results occured.
    28-11-2005 1.1 Release
    28-11-2005 Added: support for Image input with a variable
    27-11-2005 1.0 Release

    */




    class ImageSnapshot {

    var $ImageField; // should be: $_FILES['imagefield'] array, OR set the next var.
    var $ImageFile; // location of an image file saved on the server.
    var $ImageContents; // Contents of an image in a variable.
    var $Compression; // JPG compression. Default is 75%

    var $Resize; //either true or false. wether to resize image, if true the uses the next 3 vars
    var $ResizeScale; //scale to resize the image to. 100 is as small as possible, 0 is effectively no resizing at all.

    var $Position; //position of the snapshot: random, center (default), topleft, topright, bottomleft, bottomright

    var $Width; // width (or max width) of image to output
    var $Height; // height (or max height) of image to output

    var $Err; // error if (and when) they occur

    var $InternalImage; // Internal variable for working with the image

    var $ReturnedWidth; //New in 1.2: this is the actual width of the image returned, will only differ to Width if the original image was smaller.
    var $ReturnedHeight; //New in 1.2: this is the actual height of the image returned, will only differ to Height if the original image was smaller.

    var $CustomPositionX; //New in 1.3: 0 to 100, this is the percentage of the custom position along the X scale. $Position must be 'custom' for this to apply.
    var $CustomPositionY; //New in 1.3: 0 to 100, this is the percentage of the custom position along the Y scale. $Position must be 'custom' for this to apply.


    function ImageSnapshot() {
    //set up some defaults
    $this->Width = '800';
    $this->Height = '600';
    $this->Resize = true;
    $this->ResizeScale = 100;
    $this->Position = 'center';
    $this->Err = '';
    $this->Compression = 75;
    $this->InternalImage = '';
    $this->ImageContents = '';
    $this->ReturnedWidth = 0; // New in 1.2
    $this->ReturnedHeight = 0; // New in 1.2
    $this->CustomPositionX = 50; // New in 1.3
    $this->CustomPositionY = 50; // New in 1.3
    }



    function SaveImageAs($destination) {
    //Saves the image to the desination. Returns true if successful, or false with Err specifying the error.
    //example: $myimage->SaveImageAs("/docroot/images/newimage.jpg
    if ($this->ProcessImage()) {

    if (!$handle = fopen($destination, 'w')) {
    $this->Err = 'Cannot open file (' . $destination . ')';
    return false;
    } else {
    if (fwrite($handle, $this->InternalImage) === FALSE) {
    $this->Err = 'Cannot write to file (' . $destination . ')';
    return false;
    } else {
    return true;
    }
    fclose($handle);
    }
    } else {
    return false;
    }
    }

    function GetImageContents() {
    // If not already processed, calls process image, and returns the contents for other manipulations or database entry.
    if (strlen($this->InternalImage) == 0) {
    $this->ProcessImage();
    }
    //return the contents of the variable.
    return $this->InternalImage;
    }

    function ProcessImage() {
    //Processes the image. Resize if needed. fills the internal image with the contents of the changed image.
    //Internal function

    if (strlen($this->ImageContents) > 0) {
    //LOAD FROM STRING!
    $tmp_image = @imagecreatefromstring($this->ImageContents);
    //END LOAD FROM STRING

    } elseif (strlen($this->ImageFile) > 0) {
    //LOAD FROM FILE
    //check that file exists
    if (file_exists($this->ImageFile)) {
    //load it!
    $data = getimagesize($this->ImageFile); //[0] = w, [1] = h, [2] = type, [3] = attr
    switch ($data[2]) {
    case 1:
    $tmp_image = @imagecreatefromgif($this->ImageFile);
    break;
    case 2:
    $tmp_image = @imagecreatefromjpeg($this->ImageFile);
    break;
    case 3:
    $tmp_image = @imagecreatefrompng($this->ImageFile);
    break;
    default:
    $this->Err = 'File is not a valid image type';
    return false;
    exit;
    break;
    }
    } else {
    $this->Err = 'File "' . $this->ImageFile . '" does not exist!';
    return false;
    }
    //END LOAD FROM FILE

    } elseif (count($this->ImageField) > 0) {
    //LOAD FROM FIELD FILE
    //check that file exists
    if (file_exists($this->ImageField['tmp_name'])) {
    //load it!
    $data = getimagesize($this->ImageField['tmp_name']); //[0] = w, [1] = h, [2] = type, [3] = attr
    switch ($data[2]) {
    case 1:
    $tmp_image = @imagecreatefromgif($this->ImageField['tmp_name']);
    break;
    case 2:
    $tmp_image = @imagecreatefromjpeg($this->ImageField['tmp_name']);
    break;
    case 3:
    $tmp_image = @imagecreatefrompng($this->ImageField['tmp_name']);
    break;
    default:
    $this->Err = 'File is not a valid image type';
    return false;
    exit;
    break;
    }
    } else {
    $this->Err = 'File "' . $this->ImageField['tmp_name'] . '" does not exist!';
    return false;
    }
    //END LOAD FROM FILE

    } else {
    $this->Err = 'No image was loaded, use ImageFile, ImageContents or ImageField before output';
    return false;
    exit;
    }

    $image_width = imagesx($tmp_image);
    $image_height = imagesy($tmp_image);

    //check a div by zero error.
    if ($this->Resize == true && $this->ResizeScale == 0) {
    //there is no point resizing, when the scale doesn't change the size anyway.
    $this->Resize = false;
    }


    //check if image is meant to be resized...
    if ($this->Resize == 'true' || $this->Resize == 1) {
    //Yes resize
    if ($image_width > $this->Width && $image_height > $this->Height) {
    //have to resize..
    //get the proportional dimensions, while allowing room for a snapshot, and according to the resizescale
    $w_ratio = $this->Width / ($image_width * ($this->ResizeScale / 100)); //width ratio.. ie: 0.1 = 80 / 800
    $h_ratio = $this->Height / ($image_height * ($this->ResizeScale / 100)); //height ratio. ie: 0.075 = 60 / 800
    $maxwidth = $this->Width; //maxwidth is the max width of the final snapshot
    $maxheight = $this->Height; //maxheight is the max height of the final snapshot
    if ($w_ratio < $h_ratio) {
    $maxheight = ceil($image_height * $h_ratio);
    $maxwidth = ceil($image_width * $h_ratio);
    } else {
    $maxwidth = ceil($image_width * $w_ratio);
    $maxheight = ceil($image_height * $w_ratio);
    }

    //now we either have a correctly sized image (compared to the thumb) or an oversized image, that has been shrink and waiting to be snaopshot'd

    $final_width = $maxwidth;
    $final_height = $maxheight;
    //end maintain aspect

    imagecopyresampled($tmp_image, $tmp_image,0,0,0,0, $final_width, $final_height, $image_width, $image_height);

    $image_width = $final_width;
    $image_height = $final_height;

    }

    // end resize
    }

    //SNAPSHOT
    //at this stage, $tmp_image should contain the image ready for snapshot.

    if ($image_width < $this->Width) {
    $this->Width = $image_width;
    }
    if ($image_height < $this->Height) {
    $this->Height = $image_height;
    }

    //create canvas
    $new_photo = imagecreatetruecolor($this->Width,$this->Height);
    //set return values.
    $this->ReturnedWidth = $this->Width;
    $this->ReturnedHeight = $this->Height;

    $source_y = 0;
    $source_x = 0;

    //we shall compare the snapshot dimensions to the image dimensions

    switch ($this->Position) {
    case 'random':
    //my favourite, random place on the image.
    if ($image_height > $this->Height) {
    // height is larger.
    //get the min and max room to play with
    $min = 0;
    $max = $image_height - $this->Height;
    $source_y = rand($min,$max);
    }
    if ($image_width > $this->Width) {
    // width is larger.
    $min = 0;
    $max = $image_width - $this->Width;
    $source_x = rand($min,$max);
    }
    break;

    case 'topright':
    //topright of the image
    $source_y = 0;
    if ($image_width > $this->Width) {
    // width is larger.
    $source_x = $image_width - $this->Width;
    }
    break;

    case 'topleft':
    //topleft of the image
    $source_y = 0;
    $source_x = 0;
    break;

    case 'topcenter':
    //topleft of the image
    $source_y = 0;
    if ($image_width > $this->Width) {
    // width is larger.
    $source_x = (($image_width - $this->Width) / 2);
    }
    break;

    case 'bottomright':
    //bottomright of the image
    if ($image_height > $this->Height) {
    // height is larger.
    $source_y = $image_height - $this->Height;
    }
    if ($image_width > $this->Width) {
    // width is larger.
    $source_x = $image_width - $this->Width;
    }
    break;

    case 'bottomleft':
    //bottom left of the image
    if ($image_height > $this->Height) {
    // height is larger.
    $source_y = $image_height - $this->Height;
    }
    $source_x = 0;
    break;

    case 'bottomcenter':
    //bottom left of the image
    if ($image_height > $this->Height) {
    // height is larger.
    $source_y = $image_height - $this->Height;
    }
    if ($image_width > $this->Width) {
    // width is larger.
    $source_x = (($image_width - $this->Width) / 2);
    }
    break;

    case 'custom':
    //new in 1.3
    //use custom positions as percentages to get the position.
    if (round($this->CustomPositionX) < 0 || round($this->CustomPositionX) > 100) {
    //x not a valid number. Reset:
    $this->CustomPositionX = 50;
    }
    if (round($this->CustomPositionY) < 0 || round($this->CustomPositionY) > 100) {
    //y not a valid number. Reset:
    $this->CustomPositionY = 50;
    }

    //get the digits!
    if (round($this->CustomPositionY) == 0 || $image_height <= $this->Height) {
    //does not meet credentials
    $source_y = 0;
    } else {
    //ok
    $source_y = (($image_height - $this->Height) * (round($this->CustomPositionY) / 100)) ;
    }
    if (round($this->CustomPositionX) == 0 || $image_width <= $this->Width) {
    //does not meet credentials
    $source_x = 0;
    } else {
    //ok
    $source_x = (($image_width - $this->Width) * (round($this->CustomPositionX) / 100)) ;
    }
    break;

    default:
    //center of the image
    if ($image_height > $this->Height) {
    // height is larger.
    $source_y = (($image_height - $this->Height) / 2);
    }
    if ($image_width > $this->Width) {
    // width is larger.
    $source_x = (($image_width - $this->Width) / 2);
    }
    break;
    }

    //copy specific portions of the image
    imagecopyresampled($new_photo, $tmp_image,0,0,$source_x,$source_y, $this->Width, $this->Height, $this->Width, $this->Height);
    ob_start();
    imagejpeg($new_photo,null,$this->Compression);
    $this->InternalImage = ob_get_contents();
    ob_end_clean();
    return true;
    //END SNAPSHOT

    }
    }
    ?>
    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More File Manipulation Code Articles
    More By Codewalkers

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! Driving Business Success with Rational Process Library

    Join this webcast, to learn how the Rational Process Library can help with compliance issues, drive process improvement, and assist in service-oriented architecture (SOA) or Agile development. We will take a peek into the Rational Process Library with content around software and systems engineering (including RUP), operations and systems management, program and portfolio management, and asset and SOA governance.
    FREE! Go There Now!


    NEW! IBM – Taking Web 2.0 to Work

    David Barnes, Lead Evangelist for IBM Emerging Internet Technologies will discuss aspects of Web 2.0 that bring value to corporations, academia, and government. He'll also discuss IBM's vision around Web 2.0, including the importance of remixability and consumability. The discussion will culminate with examples of various IBM Software Group solutions you can use to get ahead of the Web 2.0 adoption curve.
    FREE! Go There Now!


    NEW! BlammoSplat: Build a community Web site of OpenLaszlo animations, Part 3: The community animation

    Learn to enable users to both rate existing animations and to combine existing animations into new snippets. This is the third in a series of three tutorials that chronicle the building of a site that enables collaborative discussion and animation building using Domino and OpenLaszlo.
    FREE! Go There Now!


    NEW! Develop Systems Software Assets with IBM Rational Asset Manager

    Join us for this on demand webcast to learn about developing complex systems more quickly and efficiently. We'll cover market drivers for developing, governing and reusing systems software assets and how you can develop system software assets with Rational Asset Manager.
    FREE! Go There Now!


    NEW! Don't wait! Try the Rational Application Developer (RAD) v7.5 open beta code today

    Download the Rational Application Developer (RAD) v7.5 open beta code and start developing applications for the JEE5 standard which features EJB3.0, JPA, JSF 1.2, JSP 2.1 and Servlet 2.5 standards. When you use this beta you will see how you can increase developer productivity for already existing applications with improved support for refactoring, as well as adding new features to existing applications. In addition, the beta provides tooling for JD Edwards, Oracle, SAP, Siebel and PeopleSoft to improve the developer productivity with these enterprise systems.
    FREE! Go There Now!


    NEW! Download the free Web Application Security eKit

    Discover how IBM Rational AppScan Standard Edition can help you detext vulnerabilities in your web applications in the Web Application Security eKit. IBM Rational AppScan is a leading suite of automated web application security solutions that scan and test for common Web application vulnerabilities. The new Web Application Security eKit provides you with valuable resources, including white papers, demos, and additional information on the benefits of testing your Web applications.
    FREE! Go There Now!


    NEW! Evaluate WebSphere Extended Deployment Compute Grid V6.1

    Visit IBM developerWorks to download a free trial version of WebSphere Extended Deployment Compute Grid, which lets you schedule, execute, and monitor batch jobs. Because online transaction processing and batch jobs execute simultaneously on the same server resources, you can avoid costly duplication of resources. Compute Grid supports job types of Java transactional batch, compute-intensive and a new type called "native execution", which enables non-Java workloads to run on distributed end points.
    FREE! Go There Now!


    NEW! Hello World: Monitor a simple business process using WebSphere Business Monitor V6.0.2

    This tutorial shows new users of IBM WebSphere Business Monitor Version 6.0.2 how to perform the "Hello World" equivalent for monitoring business process applications. It is intended to help you get familiar with the capabilities of the product.
    FREE! Go There Now!


    NEW! Rational Modeling Extension for Microsoft.Net

    Rational Modeling Extension for Microsoft .NET enhances usability for code generation supporting a more intelligent refactoring. The latest enhancements enable organizations with Java and .NET systems and software development maintain architectural integrity across heterogeneous platforms.
    FREE! Go There Now!


    NEW! Try IBM Rational Asset Manager V7.0 online!

    You can now evaluate IBM Rational Asset Manager V7.0 online without installing or configuring it on your own system! Rational Asset Manager helps create, modify, govern, find, and reuse any type of development assets, including SOA and systems development assets. Rational Asset Manager helps you reduce software development costs and improve quality by facilitating the reuse of all types of software development-related assets. Visit developerWorks to learn more about this product and register to explore its capabilities online.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    FILE MANIPULATION CODE ARTICLES

    - Bandwidth Control with pure PHP
    - Eazy Gallery
    - file_get_contents for PHP < 4.3.0
    - PHP Class: Image Snapshot 1.3
    - Universal downloader
    - Image Gallery v2.0
    - Free/Used Disk Space
    - Directory Lister
    - Directory image view, with selective hidden
    - Move or Copy a Directory (and files and sub ...
    - Ensure_Sub_Directory_Exists
    - Wedit
    - Form Examples Text Boxes to Drop Downs
    - myFiles
    - List files in a directory, no subdirectories





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    Stay green...Green IT