Check image dimensions before upload - php

Hi I based this function from the one I've found on web and tried modifying it up for my PHP page for uploading of their icons but I want to limit the user from uploading an image which should only size 100x100px. Well I just call it using this:
uploadImage($id,$_FILES['upload']['name'],$_FILES['upload']['tmp_name']);
This is the function I made:
function uploadImage($new_name,$imagename,$tmp_name){
if($tmp_name!=null||$tmp_name!=""){
list($width, $height, $type, $attr) = getimagesize($tmp_name);
if($width==100&&$height==100){
$image1 = $imagename;
$extension = substr($image1, strrpos($image1, '.') + 1);
$image = "$new_name.$extension";
$folder = "Images/";
if($image) {
$filename = $folder.$image;
$copied = copy($tmp_name, $filename);
}
else echo "image not uploaded.";
}
else
echo "upload only 100x100px image!";
}
}
Now the problem is that even if I uploaded an image which exceeds the 100 x 100px dimensions it still proceeds without returning any errors and now I'm lost with it.

You probably need to re-factor your code a bit; have a function that checks whether the uploaded image is valid, and then one actually does the upload. Alternatively, you could create a class.
<?php
class ImageUpload
{
public $tmpImage;
public $maxWidth = 100;
public $maxHeight = 100;
public $errors = [];
public function __construct($image)
{
$this->tmpImage = $image;
}
public function upload()
{
// Check image is valid; if not throw exception
// Check image is within desired dimensions
list($width, $height) = getimagesize($this->tmpImage);
if ($width > $this->maxWidth || $height > $this->maxHeight) {
throw new Exception(sprintf('Your image exceeded the maximum dimensions (%d×%d)', $this->maxWidth, $this->maxHeight));
}
// Create filename
// Do the upload logic, i.e. move_uploaded_file()
}
}
You can then use this class as follows:
<?php
$imageUpload = new ImageUpload($_FILES['upload']['tmp_name']);
try {
$imageUpload->upload();
} catch (Exception $e) {
echo 'An error occurred: ' . $e->getMessage();
}
This was written off the cuff, so they may be errors. But hopefully it demonstrates a better way to handle file uploads, and errors that may occur during upload.

well, you can also resize the image after upload.
function createFixSizeImage( $pathToImages, $pathToFixSizeImages, $Width )
{
// open the directory
$dir = opendir( $pathToImages );
// loop through it, looking for any/all JPG files:
while (false !== ($fname = readdir( $dir ))) {
$image_info = getimagesize( "path/to/images/".$fname );
$image_width = $image_info[0];
$image_height = $image_info[1];
$image_type = $image_info[2];
switch ( $image_type )
{
case IMAGETYPE_JPEG:
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'jpeg' )
{
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// give the size,u want
$new_width = 100;
$new_height = 100;
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save Fix Size Images into a file
imagejpeg( $tmp_img, "{$pathToFixSizeImages}{$fname}" );
}
break;
case IMAGETYPE_PNG:
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'png' )
{
// load image and get image size
$img = imagecreatefrompng( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
$new_width = 100;
$new_height = 100;
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save Fix Size Images into a file
imagejpeg( $tmp_img, "{$pathToFixSizeImages}{$fname}" );
}
break;
case IMAGETYPE_BMP:
echo "bmp";
break;
default:
break;
}
}
}
// close the directory
closedir( $dir );
}
createFixSizeImage("path","path/to/images/to/be/saved",100);

Extending more or less unknown code and then debugging it, is like you wrote some code weeks ago and you don't understand it any longer.
In your case you are extending some existing code (you have not posted the original code, but your wrote that you did it that way) by adding the feature of checking the image size.
So that you do not need to edit much of the (unknown but) working code, create the new feature as a function of it's own:
/**
* #param string $file
* #param int $with
* #param int $height
* #return bool|null true/false if image has that exact size, null on error.
*/
function image_has_size($file, $width, $height)
{
$result = getimagesize($file);
if ($count($result) < 2) {
return null;
}
list($file_width, $file_height) = $result;
return ($file_width == (int) $width)
&& ($file_height == (int) $height);
}
You now have the new functionality in a single function you can much more easily integrate into the original (hopefully otherwise working) code.
Usage:
$imageHasCorrectSize = image_has_size($tmp_name, 100, 100);
So whenever you change code, do it like a surgeon, keeping the cuts as small as possible.

Related

How to set aspect ratio in below code using PHP

I tried 2 implementations, shown below. Both are working well but when I tried to mix them it is not working anymore.
$output['status']=FALSE;
set_time_limit(0);
$allowedImageType = array("image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/x-png" );
if ($_FILES['image_file_input']["error"] > 0) {
$output['error']= "File Error";
}
elseif (!in_array($_FILES['image_file_input']["type"], $allowedImageType)) {
$output['error']= "Invalid image format";
}
elseif (round($_FILES['image_file_input']["size"] / 1024) > 4096) {
$output['error']= "Maximum file upload size is exceeded";
} else {
$temp_path = $_FILES['image_file_input']['tmp_name'];
$file = pathinfo($_FILES['image_file_input']['name']);
$fileType = $file["extension"];
$photo_name = $productname.'-'.$member_id."_".time();
$fileName1 = $photo_name . '-125x125' . ".jpg";
$fileName2 = $photo_name . '-250x250' . ".jpg";
$fileName3 = $photo_name . '-500x500' . ".jpg";
$small_thumbnail_path = "uploads/large/";
createFolder($small_thumbnail_path);
$small_thumbnail = $small_thumbnail_path . $fileName1;
$medium_thumbnail_path = "uploads/large/";
createFolder($medium_thumbnail_path);
$medium_thumbnail = $medium_thumbnail_path . $fileName2;
$large_thumbnail_path = "uploads/large/";
createFolder($large_thumbnail_path);
$large_thumbnail = $large_thumbnail_path . $fileName3;
$thumb1 = createThumbnail($temp_path, $small_thumbnail,$fileType, 125, 125 );
$thumb2 = createThumbnail($temp_path, $medium_thumbnail, $fileType, 250, 250);
$thumb3 = createThumbnail($temp_path, $large_thumbnail,$fileType, 500, 500);
if($thumb1 && $thumb2 && $thumb3) {
$output['status']=TRUE;
$output['small']= $small_thumbnail;
$output['medium']= $medium_thumbnail;
$output['large']= $large_thumbnail;
}
}
echo json_encode($output);
Function File
function createFolder($path)
{
if (!file_exists($path)) {
mkdir($path, 0755, TRUE);
}
}
function createThumbnail($sourcePath, $targetPath, $file_type, $thumbWidth, $thumbHeight){
$source = imagecreatefromjpeg($sourcePath);
$width = imagesx($source);
$height = imagesy($source);
$tnumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($tnumbImage, $source, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);
if (imagejpeg($tnumbImage, $targetPath, 90)) {
imagedestroy($tnumbImage);
imagedestroy($source);
return TRUE;
} else {
return FALSE;
}
}
Aspect ratio code, which is another one I tried to mix this code. But I was unsuccessful
$fn = $_FILES['image']['tmp_name'];
$size = getimagesize($fn);
$ratio = $size[0]/$size[1]; // width/height
$photo_name = $productname.'-'.$member_id."_".time();
{
if( $ratio > 1) {
$width1 = 500;
$height1 = 500/$ratio;
}
else {
$width1 = 500*$ratio;
$height1 = 500;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor($width1,$height1);
$fileName3 = $photo_name . '-500x500' . ".jpg";
imagecopyresampled($dst,$src,0,0,0,0,$width1,$height1,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst,$fileName3); // adjust format as needed
imagedestroy($dst);
if( $ratio > 1) {
$width2 = 250;
$height2 = 250/$ratio;
}
else {
$width2 = 250*$ratio;
$height2 = 250;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor($width2,$height2);
$fileName2 = $photo_name . '-250x250' . ".jpg";
imagecopyresampled($dst,$src,0,0,0,0,$width2,$height2,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst,$fileName2); // adjust format as needed
imagedestroy($dst);
}
What I need is to save my image after resizing but in second code there is no condition check, and I can't get image upload folder path. That's why I need to merge these 2 codes.
Basically I need need to save my image in 3 size formats: 500x500,250x250 and 125x125. Width is fixed, but height is set as per aspect ratio and set upload folder and condition in second code block.
Try this thumbnail function, which takes your source image resource and thumbnail size, and returns a new image resource for the thumbnail.
function createThumbnail($src, int $width = 100, int $height = null) {
// Ensure that src is a valid gd resource
if (!(is_resource($src) && 'gd' === get_resource_type($src))) {
throw new InvalidArgumentException(
sprintf("Argument 1 of %s expected type resource(gd), %s supplied", __FUNCTION__, gettype($src))
);
}
// Extract source image width, height and aspect ratio
$source_width = imagesx($src);
$source_height = imagesy($src);
$ratio = $source_width / $source_height;
// We know that width is always supplied, and that height can be null
// We must solve height according to aspect ratio if null is supplied
if (null === $height) {
$height = round($width / $ratio);
}
// Create the thumbnail resampled resource
$thumb = imagecreatetruecolor($width, $height);
imagecopyresampled($thumb, $src, 0, 0, 0, 0, $width, $height, $source_width, $source_height);
return $thumb;
}
Given your code above, you can now use the function like this
// Get uploaded file information as you have
// Create your source resource as you have
$source = imagecreatefromstring(file_get_contents($fn));
// Create thumbnails and save + destroy
$thumb = createThumbnail($source, 500);
imagejpeg($thumb, $thumb500TargetPath, 90);
imagedestroy($thumb);
$thumb = createThumbnail($source, 250);
imagejpeg($thumb, $thumb250TargetPath, 90);
imagedestroy($thumb);
$thumb = createThumbnail($source, 125);
imagejpeg($thumb, $thumb125TargetPath, 90);
imagedestroy($thumb);
// Don't forget to destroy the source resource
imagedestroy($source);

Path to send resized images on upload php

I have a simple multiple image upload script that resizes images maintaining the aspect ratio. The resizing is working fine. however, I can't seem to send the images to the correct folder, even though the syntax is correct.
Here is what i'm doing in a nutshell:
if file input "Image" is not empty then create a new folder within "../company_images" the name of the created folder is a uniqid defined by the "$photo_directory_name" variable. after this run the resize function for each of the images then put the resized images in to the upload folder defined by the "$total_path" variable.
if(!empty($_FILES["Image"])){
$photo_directory_name = uniqid(rand(100, 1000));
$photos_path = "company_images/" . $photo_directory_name;
$directory = "../company_images/";
if (!file_exists($directory . $photo_directory_name)) {
$upload_dir = mkdir($directory . $photo_directory_name, 0777, TRUE);
}else{
$upload_dir = $directory . $photo_directory_name;
}
function resize($width, $height){
/* Get original image x y*/
list($w, $h) = getimagesize($_FILES['Image']['tmp_name']);
/* calculate new image size with ratio */
$ratio = max($width/$w, $height/$h);
$h = ceil($height / $ratio);
$x = ($w - $width / $ratio) / 2;
$w = ceil($width / $ratio);
/* new file name */
$path = $width.'x'.$height.'_'.$_FILES['Image']['name'];
$total_path = $directory . $photo_directory_name . $path;
/* read binary data from image file */
$imgString = file_get_contents($_FILES['Image']['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $image,
0, 0,
$x, 0,
$width, $height,
$w, $h);
/* Save image */
switch ($_FILES['Image']['type']) {
case 'image/jpeg':
imagejpeg($tmp, $total_path, 100);
break;
case 'image/png':
imagepng($tmp, $total_path, 0);
break;
case 'image/gif':
imagegif($tmp, $total_path);
break;
default:
exit;
break;
}
return $total_path;
/* cleanup memory */
imagedestroy($image);
imagedestroy($tmp);
}
$max_file_size = 1024*1000; // 1mb
$valid_exts = array('jpeg', 'jpg', 'png', 'gif');
// thumbnail sizes
$sizes = array(1200 => 1000);
if ($_SERVER['REQUEST_METHOD'] == 'POST' AND isset($_FILES['Image'])) {
if( $_FILES['Image']['size'] < $max_file_size ){
// get file extension
$ext = strtolower(pathinfo($_FILES['Image']['name'], PATHINFO_EXTENSION));
if (in_array($ext, $valid_exts)) {
/* resize image */
foreach ($sizes as $w => $h) {
$files[] = resize($w, $h);
}
} else {
$response["message"] = 'photos_invalid_format';
$errors++;
}
} else{
$response["message"] = 'photos_file_too_large';
$errors++;
}
}
echo $total_path;
}
Any help is much appreciated. Thanks
You have some global variables that you're using inside the resize function:
$directory
$photo_directory_name
They need to be either passed in as parameters, or declared as globals within that function:
function resize($width, $height){
global $directory, $photo_directory_name;
// rest of function

PHP createThumbnail function troubleshooting

I'm using this function, to create thumbnails of images uploaded by the user, that I found here: http://webcheatsheet.com/php/create_thumbnail_images.php :
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
{
// open the directory
$dir = opendir( $pathToImages );
// loop through it, looking for any/all JPG files:
if (false !== ($fname = readdir( $dir ))) {
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'jpg' )
{
echo "Creating thumbnail for {$fname} <br />";
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresampled( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
}
}
// close the directory
closedir( $dir );
}
This function works fine and does exactly what I want it to, but, despite this, I'm still getting errors from it. See errors below:
Warning: opendir(images/008/01/0000288988r.jpg,images/008/01/0000288988r.jpg) [<a href='function.opendir'>function.opendir</a>]: The directory name is invalid. (code: 267)
Warning: opendir(images/008/01/0000288988r.jpg) [<a href='function.opendir'>function.opendir</a>]: failed to open dir: No error
Warning: readdir() expects parameter 1 to be resource, boolean given
The problem, I think, is that I'm passing an actual file, not just a directory, into the parameters for the function. This is the case for $pathtoimages and $pathtothumbs. The function is supposed to search through the directory passed to it to find all images with the .jpg extension. But I would like to just perform the function on the one image uploaded at the time of upload. Is there someway to edit this function to allow for this?
Thanks in advance
the $pathToImage must point to image file
remove
$dir = opendir( $pathToImages );
if (false !== ($fname = readdir( $dir ))) {
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
add $info = pathinfo($pathtoImages); // for the file name
$fname = $info['filename']
replace {$pathToImages}{$fname} with $pathToImages only, since its the image file.
btw, this code is not verbose.
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
{
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresampled( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}" );
}
Think I prematurely posted this question. Thanks for help from everyone.
#csw looks like your solution may have worked, but I got mine working too so I didn't test it.
Quick and dirty:
function createThumb( $pathToImage, $pathToThumb, $thumbWidth )
{
$fname = $pathToImage;
echo "Creating thumbnail for {$fname} <br />";
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImage}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresampled( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumb}{$fname}" );
}
You have to use that function like this:
createThumbs("path_to_image", "path_to_thumb", "thumb_width");
Replacing the arguments. Notice the word "path", it's a directory, like "../images/02", and you are using probably the path along with the picture name, like this:
createThumbs("images/008/01/0000288988r.jpg", " ......
And it should be:
createThumbs("images/008/01/" ...

create thumbnail of image and then save it into database

i am creating a thumbnail of an image and then save it into the database but i don't know how to do so. here is my code
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
{
$pathToImages = "../uploads/images/";
// open the directory
$dir = opendir( $pathToImages );
// loop through it, looking for any/all JPG files:
while (false !== ($fname = readdir( $dir ))) {
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'jpg' )
{
$pathToThumbs = "../uploads/images/thumbs/";
//echo "Creating thumbnail for {$fname} <br />";
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width,$new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
$thumbimage = $fname;
}
}
// close the directory
closedir( $dir );
}
createThumbs("/uploads/documents","/uploads/images/thumbs/",100);
creation of thumbnail is fine but now i dont know how to save it in db(lack of skills)
why you don't save the results in file?
i think you must select the text type in database field, then save the content of image there,
and read the data in a diffrent php file with "Content-type: image/jpg" header.
for example:
$query = "SELECT image FROM youtablename WHERE id = 10";
$result = mysql_query($query) or die('Error, query failed');
$content=mysql_result($result,0,"image");
header("Content-type: image/jpg");
echo $content;
You can use the Dropbox API that automatically generates thumbnails. I think that save binary files in a database is the worst mistake we can make. Especially for the performance and files management becomes difficult.

Resize images with PHP

I have a quick question that I'm not quite sure to set up. I've seen examples elsewhere but nothing specifically like my situation. I would like to resize images using PHP so they're readable and not just wonkily stretched like if you use HTML. If they're not 250 pixels wide, or 160 pixels tall, how can I resize the picture so it's proportionate but fits within that space?
Thanks!
PHP does not manipulate images directly. You will need to use an image manipulation library such as gd or ImageMagick to accomplish this goal.
In ImageMagick, image resizing is accomplished like this:
$thumb = new Imagick('myimage.gif');
$thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');
With GD, you can do it like this:
<?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);
?>
Ok, so below is an Image object that I use in my store. It maintains scale - requires GD
<?php
class Store_Model_Image extends My_Model_Abstract
{
const PATH = STORE_MODEL_IMAGE_PATH;
const URL = "/store-assets/product-images/";
public function get_image_url($width, $height)
{
$old_file = self::PATH . $this->get_filename();
$basename = pathinfo($old_file, PATHINFO_FILENAME);
$new_name = sprintf("%s_%sx%s.jpg", $basename, $width, $height);
if(file_exists(self::PATH . $new_name))
{
return self::URL . $new_name;
}
else
{
list($width_orig, $height_orig, $image_type) = #getimagesize($old_file);
$img = FALSE;
// Get the image and create a thumbnail
switch($image_type)
{
case 1:
$img = #imagecreatefromgif($old_file);
break;
case 2:
$img = #imagecreatefromjpeg($old_file);
break;
case 3:
$img = #imagecreatefrompng($old_file);
break;
}
if(!$img)
{
throw new Zend_Exception("ERROR: Could not create image handle from path.");
}
// Build the thumbnail
if($width_orig > $height_orig)
{
$width_ratio = $width / $width_orig;
$new_width = $width;
$new_height = $height_orig * $width_ratio;
}
else
{
$height_ratio = $height / $height_orig;
$new_width = $width_orig * $height_ratio;
$new_height = $height;
}
$new_img = #imagecreatetruecolor($new_width, $new_height);
// Fill the image black
if(!#imagefilledrectangle($new_img, 0, 0, $new_width, $new_height, 0))
{
throw new Zend_Exception("ERROR: Could not fill new image");
}
if(!#imagecopyresampled($new_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig))
{
throw new Zend_Exception("ERROR: Could not resize old image onto new bg.");
}
// Use a output buffering to load the image into a variable
ob_start();
imagejpeg($new_img, NULL, 100);
$image_contents = ob_get_contents();
ob_end_clean();
// lastly (for the example) we are writing the string to a file
$fh = fopen(self::PATH . $new_name, "a+");
fwrite($fh, $image_contents);
fclose($fh);
return self::URL . $new_name;
}
}
}
I resize the image at request time, so the first time the page loads an image will be resized to the required size for the template. (this means I don't have to crash a shared host trying to regenerate image thumbnails everytime my design changes)
So in the template you pass your image object, and when you need a image thumb,
<img src="<?php echo $image->get_image_url(100, 100); ?>" />
you now have a 100x100 thumb, which is saved to the Server for reuse at a later date
gd and imagemagick are two tools that may work for you
http://php.net/manual/en/book.image.php
http://php.net/manual/en/book.imagick.php
Here is something I used to use
class cropImage{
var $imgSrc,$myImage,$cropHeight,$cropWidth,$x,$y,$thumb;
function setImage($image,$moduleWidth,$moduleHeight,$cropPercent = "1") {
//Your Image
$this->imgSrc = $image;
//getting the image dimensions
list($width, $height) = getimagesize($this->imgSrc);
//create image from the jpeg
$this->myImage = imagecreatefromjpeg($this->imgSrc) or die("Error: Cannot find image!");
if($width > $height) $biggestSide = $width; //find biggest length
else $biggestSide = $height;
//The crop size will be half that of the largest side
//$cropPercent = 1.55; // This will zoom in to 50% zoom (crop)
if(!$cropPercent) {
$cropPercent = 1.50;
}
$this->cropWidth = $moduleWidth*$cropPercent;
$this->cropHeight = $moduleHeight*$cropPercent;
//$this->cropWidth = $biggestSide*$cropPercent;
//$this->cropHeight = $biggestSide*$cropPercent;
//getting the top left coordinate
$this->x = ($width-$this->cropWidth)/2;
$this->y = ($height-$this->cropHeight)/2;
}
function createThumb($moduleWidth,$moduleHeight){
$thumbSize = 495; // will create a 250 x 250 thumb
$this->thumb = imagecreatetruecolor($moduleWidth, $moduleHeight);
//$this->thumb = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($this->thumb, $this->myImage, 0, 0,$this->x, $this->y, $moduleWidth, $moduleHeight, $this->cropWidth, $this->cropHeight);
//imagecopyresampled($this->thumb, $this->myImage, 0, 0,$this->x, $this->y, $thumbSize, $thumbSize, $this->cropWidth, $this->cropHeight);
}
function renderImage(){
header('Content-type: image/jpeg');
imagejpeg($this->thumb);
imagedestroy($this->thumb);
}
}
Call it by using
$image = new cropImage;
$image->setImage($imagepath,$moduleWidth,$moduleHeight,$scaleRelation);
$image->createThumb($moduleWidth,$moduleHeight);
$image->renderImage();
Use GD or ImageMagick. Here you may find a real production example of code (used by MediaWiki) that supports consoled ImageMagick interface (transformImageMagick method), ImageMagick extension interface (transformImageMagickExt method) and GD (transformGd method).
There a simple to use, open source library called PHP Image Magician that will can help you out.
Example of basis usage:
$magicianObj = new imageLib('racecar.jpg');
$magicianObj -> resizeImage(100, 200, 'crop');
$magicianObj -> saveImage('racecar_small.png');

Categories