Have this piece of code allowing me to charge an image on my webserver.
These two script works but not together. The first on is to charge the image on my server and the second one is to resize my image. I try out some post on SO but I can't find the right way to make it works with my original code.
<?php
$fileName = $_FILES['AddPhoto']['name'];
$tmpName = $_FILES['AddPhoto']['tmp_name'];
$fileSize = $_FILES['AddPhoto']['size']/1024;
$fileType = $_FILES['AddPhoto']['type'];
$fileExtension = end(explode(".", $fileName));
if(($fileType == "image/gif" || $fileType == "image/jpeg" || $fileType == "image/pjpeg" || $fileType == "image/png" || $fileType == "image/x-png") && $fileSize < 1000000) {
$newFileName = md5(date('u').rand(0,99)).".".$fileExtension;
$imagePath = "assets/picts/".$newFileName;
$result = #move_uploaded_file($tmpName, $imagePath);
$request = mysql_query("SELECT ".$TypeField."Images FROM $TypeFiche WHERE $TypeId='$cardId'");
$var2 = mysql_fetch_array($request);
mysql_query("UPDATE ".$TypeFiche." SET `".$TypeField."Images`='".$var2[$TypeField.'Images'].$newFileName.",' WHERE $TypeId='$cardId'");
if (!$result) {
$newImgMessError = "Error.<br />";
}
if ($result) {
$newImgMessError = "Valid.<br />";
}
}
?>
I want to have the possibility to resize the image.
Any clue and help will be very appreciated.
Thanks.
$_FILES['AddPhoto'] is your image file, transfered to server. You save it in $imagepath. This path is what you need when you create JPEG image (for others are different functions) with function like imagecreatefromjpeg($imagepath). From this point on you can use a lot of examples that you have found in StackOverflow. One was already published by Juan David Decano in this thread.
Heres a simple class
<?php
/**
* Resize image class will allow you to resize an image
*
* Can resize to exact size
* Max width size while keep aspect ratio
* Max height size while keep aspect ratio
* Automatic while keep aspect ratio
*/
class ResizeImage
{
private $ext;
private $image;
private $newImage;
private $origWidth;
private $origHeight;
private $resizeWidth;
private $resizeHeight;
/**
* Class constructor requires to send through the image filename
*
* #param string $filename - Filename of the image you want to resize
*/
public function __construct( $filename )
{
if(file_exists($filename))
{
$this->setImage( $filename );
} else {
throw new Exception('Image ' . $filename . ' can not be found, try another image.');
}
}
/**
* Set the image variable by using image create
*
* #param string $filename - The image filename
*/
private function setImage( $filename )
{
$size = getimagesize($filename);
$this->ext = $size['mime'];
switch($this->ext)
{
// Image is a JPG
case 'image/jpg':
case 'image/jpeg':
// create a jpeg extension
$this->image = imagecreatefromjpeg($filename);
break;
// Image is a GIF
case 'image/gif':
$this->image = #imagecreatefromgif($filename);
break;
// Image is a PNG
case 'image/png':
$this->image = #imagecreatefrompng($filename);
break;
// Mime type not found
default:
throw new Exception("File is not an image, please use another file type.", 1);
}
$this->origWidth = imagesx($this->image);
$this->origHeight = imagesy($this->image);
}
/**
* Save the image as the image type the original image was
*
* #param String[type] $savePath - The path to store the new image
* #param string $imageQuality - The qulaity level of image to create
*
* #return Saves the image
*/
public function saveImage($savePath, $imageQuality="100", $download = false)
{
switch($this->ext)
{
case 'image/jpg':
case 'image/jpeg':
// Check PHP supports this file type
if (imagetypes() & IMG_JPG) {
imagejpeg($this->newImage, $savePath, $imageQuality);
}
break;
case 'image/gif':
// Check PHP supports this file type
if (imagetypes() & IMG_GIF) {
imagegif($this->newImage, $savePath);
}
break;
case 'image/png':
$invertScaleQuality = 9 - round(($imageQuality/100) * 9);
// Check PHP supports this file type
if (imagetypes() & IMG_PNG) {
imagepng($this->newImage, $savePath, $invertScaleQuality);
}
break;
}
if($download)
{
header('Content-Description: File Transfer');
header("Content-type: application/octet-stream");
header("Content-disposition: attachment; filename= ".$savePath."");
readfile($savePath);
}
imagedestroy($this->newImage);
}
/**
* Resize the image to these set dimensions
*
* #param int $width - Max width of the image
* #param int $height - Max height of the image
* #param string $resizeOption - Scale option for the image
*
* #return Save new image
*/
public function resizeTo( $width, $height, $resizeOption = 'default' )
{
switch(strtolower($resizeOption))
{
case 'exact':
$this->resizeWidth = $width;
$this->resizeHeight = $height;
break;
case 'maxwidth':
$this->resizeWidth = $width;
$this->resizeHeight = $this->resizeHeightByWidth($width);
break;
case 'maxheight':
$this->resizeWidth = $this->resizeWidthByHeight($height);
$this->resizeHeight = $height;
break;
default:
if($this->origWidth > $width || $this->origHeight > $height)
{
if ( $this->origWidth > $this->origHeight ) {
$this->resizeHeight = $this->resizeHeightByWidth($width);
$this->resizeWidth = $width;
} else if( $this->origWidth < $this->origHeight ) {
$this->resizeWidth = $this->resizeWidthByHeight($height);
$this->resizeHeight = $height;
}
} else {
$this->resizeWidth = $width;
$this->resizeHeight = $height;
}
break;
}
$this->newImage = imagecreatetruecolor($this->resizeWidth, $this->resizeHeight);
imagecopyresampled($this->newImage, $this->image, 0, 0, 0, 0, $this->resizeWidth, $this->resizeHeight, $this->origWidth, $this->origHeight);
}
/**
* Get the resized height from the width keeping the aspect ratio
*
* #param int $width - Max image width
*
* #return Height keeping aspect ratio
*/
private function resizeHeightByWidth($width)
{
return floor(($this->origHeight/$this->origWidth)*$width);
}
/**
* Get the resized width from the height keeping the aspect ratio
*
* #param int $height - Max image height
*
* #return Width keeping aspect ratio
*/
private function resizeWidthByHeight($height)
{
return floor(($this->origWidth/$this->origHeight)*$height);
}
}
?>
Usage:
$resize = new ResizeImage('images/Be-Original.jpg');
$resize->resizeTo(100, 100, 'maxWidth');
$resize->saveImage('images/be-original-maxWidth.jpg');
Resource and more examples:
http://www.paulund.co.uk/resize-image-class-php
try this
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
echo $scr;
list($width,$height)=getimagesize($uploadedfile);
$newwidth=60;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=25;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
$filename = "images/". $_FILES['file']['name'];
$filename1 = "images/small". $_FILES['file']['name'];
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
Related
I let the user upload images using PHP. Now, I'd like for my app to also create a thumbnail of that same image. The problem is that once I do move_uploaded_file(), the temporary file is moved (obviously), and not copied. Once I want to resize the same image and then perform the same operation again, but to a filename with "-thumb" added to it, I get an error saying that the file doesn't exist.
What would be the best way of solving this? Thank you!
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newFileFullUrl)) { //Successfully stored image
$retArr['imgUrl'] = $_POST['fileTarget']['dir'] . $_POST['fileTarget']['name'];
//Needs to also create a thumb
if ($_POST['dimensionSettings']->thumb->create) {
$needsResize = true;
$resizeOptions = (object) [
'width' => $_POST['dimensionSettings']->thumb->width,
'height' => $_POST['dimensionSettings']->thumb->height,
'mode' => 'maxwidth',
'imageQuality' => 100
];
include_once($_SERVER['DOCUMENT_ROOT'] . '/lib/classes/ResizeImage.php');
$resize = new ResizeImage($_FILES['fileToUpload']['tmp_name']);
$resize->resizeTo($resizeOptions->width, $resizeOptions->height, $resizeOptions->mode);
$resize->saveImage($_FILES['fileToUpload']['tmp_name'], $resizeOptions->imageQuality);
//Add -thumb to end of filename
$thumbFileFullUrlArr = explode('.', $newFileFullUrl);
$thumbFileFullUrlArr[sizeof($thumbFileFullUrlArr) - 2] .= '-thumb';
$thumbFileFullUrl = implode('.', $thumbFileFullUrlArr);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $thumbFileFullUrl)) { //Successfully stored image
$retArr['success'] = true;
}
}
}
EDIT Here is the ResizeImage class:
<?php
/**
* Resize image class will allow you to resize an image
*
* Can resize to exact size
* Max width size while keep aspect ratio
* Max height size while keep aspect ratio
* Automatic while keep aspect ratio
*/
class ResizeImage
{
private $ext;
private $image;
private $newImage;
private $origWidth;
private $origHeight;
private $resizeWidth;
private $resizeHeight;
/**
* Class constructor requires to send through the image filename
*
* #param string $filename - Filename of the image you want to resize
*/
public function __construct( $filename )
{
if(file_exists($filename))
{
$this->setImage( $filename );
} else {
throw new Exception('Image ' . $filename . ' can not be found, try another image.');
}
}
/**
* Set the image variable by using image create
*
* #param string $filename - The image filename
*/
private function setImage( $filename )
{
$size = getimagesize($filename);
$this->ext = $size['mime'];
switch($this->ext)
{
// Image is a JPG
case 'image/jpg':
case 'image/jpeg':
// create a jpeg extension
$this->image = imagecreatefromjpeg($filename);
break;
// Image is a GIF
case 'image/gif':
$this->image = #imagecreatefromgif($filename);
break;
// Image is a PNG
case 'image/png':
$this->image = #imagecreatefrompng($filename);
break;
// Mime type not found
default:
throw new Exception("File is not an image, please use another file type.", 1);
}
$this->origWidth = imagesx($this->image);
$this->origHeight = imagesy($this->image);
}
/**
* Save the image as the image type the original image was
*
* #param String[type] $savePath - The path to store the new image
* #param string $imageQuality - The qulaity level of image to create
*
* #return Saves the image
*/
public function saveImage($savePath, $imageQuality = 100, $download = false)
{
switch($this->ext)
{
case 'image/jpg':
case 'image/jpeg':
// Check PHP supports this file type
if (imagetypes() & IMG_JPG) {
imagejpeg($this->newImage, $savePath, $imageQuality);
}
break;
case 'image/gif':
// Check PHP supports this file type
if (imagetypes() & IMG_GIF) {
imagegif($this->newImage, $savePath);
}
break;
case 'image/png':
$invertScaleQuality = 9 - round(($imageQuality/100) * 9);
// Check PHP supports this file type
if (imagetypes() & IMG_PNG) {
imagepng($this->newImage, $savePath, $invertScaleQuality);
}
break;
}
if ($download)
{
header('Content-Description: File Transfer');
header("Content-type: application/octet-stream");
header("Content-disposition: attachment; filename= ".$savePath."");
readfile($savePath);
}
imagedestroy($this->newImage);
}
/**
* Resize the image to these set dimensions
*
* #param int $width - Max width of the image
* #param int $height - Max height of the image
* #param string $resizeOption - Scale option for the image
*
* #return Save new image
*/
public function resizeTo( $width, $height, $resizeOption = 'default' )
{
switch(strtolower($resizeOption))
{
case 'exact':
$this->resizeWidth = $width;
$this->resizeHeight = $height;
break;
case 'maxwidth':
$this->resizeWidth = $width;
$this->resizeHeight = $this->resizeHeightByWidth($width);
break;
case 'maxheight':
$this->resizeWidth = $this->resizeWidthByHeight($height);
$this->resizeHeight = $height;
break;
default:
if($this->origWidth > $width || $this->origHeight > $height)
{
if ( $this->origWidth > $this->origHeight ) {
$this->resizeHeight = $this->resizeHeightByWidth($width);
$this->resizeWidth = $width;
} else if( $this->origWidth < $this->origHeight ) {
$this->resizeWidth = $this->resizeWidthByHeight($height);
$this->resizeHeight = $height;
}
} else {
$this->resizeWidth = $width;
$this->resizeHeight = $height;
}
break;
}
$this->newImage = imagecreatetruecolor($this->resizeWidth, $this->resizeHeight);
//Image is of a type that may have transparent background
if ($this->ext == 'image/png' || $this->ext == 'image/gif') {
// integer representation of the color black (rgb: 0,0,0)
$background = imagecolorallocate($this->newImage , 0, 0, 0);
// removing the black from the placeholder
imagecolortransparent($this->newImage, $background);
// turning off alpha blending (to ensure alpha channel information
// is preserved, rather than removed (blending with the rest of the
// image in the form of black))
imagealphablending($this->newImage, false);
// turning on alpha channel information saving (to ensure the full range
// of transparency is preserved)
imagesavealpha($this->newImage, true);
}
imagecopyresampled($this->newImage, $this->image, 0, 0, 0, 0, $this->resizeWidth, $this->resizeHeight, $this->origWidth, $this->origHeight);
}
/**
* Get the resized height from the width keeping the aspect ratio
*
* #param int $width - Max image width
*
* #return Height keeping aspect ratio
*/
private function resizeHeightByWidth($width)
{
return floor(($this->origHeight/$this->origWidth)*$width);
}
/**
* Get the resized width from the height keeping the aspect ratio
*
* #param int $height - Max image height
*
* #return Width keeping aspect ratio
*/
private function resizeWidthByHeight($height)
{
return floor(($this->origWidth/$this->origHeight)*$height);
}
}
?>
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
I need to get a preview of an image after upload.According to me , it will be a better solution to store the thumbnails on the server as a cache.However the function that i am using currently doesn't seems to support transparency.It just fill the background with black
Here is the function that i am using
<?php
/**
* Resize image class will allow you to resize an image
*
* Can resize to exact size
* Max width size while keep aspect ratio
* Max height size while keep aspect ratio
* Automatic while keep aspect ratio
*/
class ResizeImage
{
private $ext;
private $image;
private $newImage;
private $origWidth;
private $origHeight;
private $resizeWidth;
private $resizeHeight;
/**
* Class constructor requires to send through the image filename
*
* #param string $filename - Filename of the image you want to resize
*/
public function __construct( $filename )
{
if(file_exists($filename))
{
$this->setImage( $filename );
} else {
throw new Exception('Image ' . $filename . ' can not be found, try another image.');
}
}
/**
* Set the image variable by using image create
*
* #param string $filename - The image filename
*/
private function setImage( $filename )
{
$size = getimagesize($filename);
$this->ext = $size['mime'];
switch($this->ext)
{
// Image is a JPG
case 'image/jpg':
case 'image/jpeg':
// create a jpeg extension
$this->image = imagecreatefromjpeg($filename);
break;
// Image is a GIF
case 'image/gif':
$this->image = #imagecreatefromgif($filename);
break;
// Image is a PNG
case 'image/png':
$this->image = #imagecreatefrompng($filename);
break;
// Mime type not found
default:
throw new Exception("File is not an image, please use another file type.", 1);
}
$this->origWidth = imagesx($this->image);
$this->origHeight = imagesy($this->image);
}
/**
* Save the image as the image type the original image was
*
* #param String[type] $savePath - The path to store the new image
* #param string $imageQuality - The qulaity level of image to create
*
* #return Saves the image
*/
public function saveImage($savePath, $imageQuality="100", $download = false)
{
switch($this->ext)
{
case 'image/jpg':
case 'image/jpeg':
// Check PHP supports this file type
if (imagetypes() & IMG_JPG) {
imagejpeg($this->newImage, $savePath, $imageQuality);
}
break;
case 'image/gif':
// Check PHP supports this file type
if (imagetypes() & IMG_GIF) {
imagegif($this->newImage, $savePath);
}
break;
case 'image/png':
$invertScaleQuality = 9 - round(($imageQuality/100) * 9);
// Check PHP supports this file type
if (imagetypes() & IMG_PNG) {
imagepng($this->newImage, $savePath, $invertScaleQuality);
}
break;
}
if($download)
{
header('Content-Description: File Transfer');
header("Content-type: application/octet-stream");
header("Content-disposition: attachment; filename= ".$savePath."");
readfile($savePath);
}
imagedestroy($this->newImage);
}
/**
* Resize the image to these set dimensions
*
* #param int $width - Max width of the image
* #param int $height - Max height of the image
* #param string $resizeOption - Scale option for the image
*
* #return Save new image
*/
public function resizeTo( $width, $height, $resizeOption = 'default' )
{
switch(strtolower($resizeOption))
{
case 'exact':
$this->resizeWidth = $width;
$this->resizeHeight = $height;
break;
case 'maxwidth':
$this->resizeWidth = $width;
$this->resizeHeight = $this->resizeHeightByWidth($width);
break;
case 'maxheight':
$this->resizeWidth = $this->resizeWidthByHeight($height);
$this->resizeHeight = $height;
break;
default:
if($this->origWidth > $width || $this->origHeight > $height)
{
if ( $this->origWidth > $this->origHeight ) {
$this->resizeHeight = $this->resizeHeightByWidth($width);
$this->resizeWidth = $width;
} else if( $this->origWidth < $this->origHeight ) {
$this->resizeWidth = $this->resizeWidthByHeight($height);
$this->resizeHeight = $height;
}
} else {
$this->resizeWidth = $width;
$this->resizeHeight = $height;
}
break;
}
$this->newImage = imagecreatetruecolor($this->resizeWidth, $this->resizeHeight);
imagecopyresampled($this->newImage, $this->image, 0, 0, 0, 0, $this->resizeWidth, $this->resizeHeight, $this->origWidth, $this->origHeight);
}
/**
* Get the resized height from the width keeping the aspect ratio
*
* #param int $width - Max image width
*
* #return Height keeping aspect ratio
*/
private function resizeHeightByWidth($width)
{
return floor(($this->origHeight/$this->origWidth)*$width);
}
/**
* Get the resized width from the height keeping the aspect ratio
*
* #param int $height - Max image height
*
* #return Width keeping aspect ratio
*/
private function resizeWidthByHeight($height)
{
return floor(($this->origWidth/$this->origHeight)*$height);
}
}
?>
It would be awesome if anyone could modify it to make it handle images with transparent background.
In case you have a better function please share
Kind Regards
Your class handles jpeg and png files also so you will need to check the type and make the changes only if it is png:
relace this
$this->newImage = imagecreatetruecolor($this->resizeWidth, $this->resizeHeight);
with this
$this->newImage = imagecreatetruecolor($this->resizeWidth, $this->resizeHeight);
imagesavealpha($this->newImage, true);
$transparent_color = imagecolorallocatealpha($this->newImage, 0, 0, 0, 127);
imagefill($this->newImage, 0, 0, $transparent_color);
I am using timthumb.php for resizing images .
It works with local image but what if i have URL that will fetch image from MYSQL and then i want to resize that image on the fly before displaying?
I tried several ways.
my URL that will fetch image from MYSQL is
http://somedomain/final/getImage.php?id=1234
I want to do something like below which is not working
<img src="php_helpers/timthumb.php?src=http://somedomain/final/getImage.php?id=1234&w=260" alt="" />
Any help would be much appreciated .
Thanks
you should use image path in src tag instead of php path.like
<img src="timthumb.php?src=/images/filename.jpg&h=150&w=150&zc=1" alt="some text" />
if you want to fetch image path from database then you should write something like
<?php
$sql = "SELECT image FROM image_tbl WHERE ID ='$image_id'";
$result = mysql_query($sql);
$image = mysql_result($result, 0);
echo '<img src="' $image'"/>';
?>
Hi this is the image resize class. Please use this in your application. If need any changes depends upon your application path please do it in this.
<?php
/**
* Resize image class will allow you to resize an image
*
* Can resize to exact size
* Max width size while keep aspect ratio
* Max height size while keep aspect ratio
* Automatic while keep aspect ratio
*/
class ResizeImage
{
private $ext;
private $image;
private $newImage;
private $origWidth;
private $origHeight;
private $resizeWidth;
private $resizeHeight;
/**
* Class constructor requires to send through the image filename
*
* #param string $filename – Filename of the image you want to resize
*/
public function __construct( $filename )
{
if(file_exists($filename))
{
$this->setImage( $filename );
} else {
throw new Exception(‘Image ‘ . $filename . ‘ can not be found, try another image.’);
}
}
/**
* Set the image variable by using image create
*
* #param string $filename – The image filename
*/
private function setImage( $filename )
{
$size = getimagesize($filename);
$this->ext = $size['mime'];
switch($this->ext)
{
// Image is a JPG
case ‘image/jpg’:
case ‘image/jpeg’:
// create a jpeg extension
$this->image = imagecreatefromjpeg($filename);
break;
// Image is a GIF
case ‘image/gif’:
$this->image = #imagecreatefromgif($filename);
break;
// Image is a PNG
case ‘image/png’:
$this->image = #imagecreatefrompng($filename);
break;
// Mime type not found
default:
throw new Exception(“File is not an image, please use another file type.”, 1);
}
$this->origWidth = imagesx($this->image);
$this->origHeight = imagesy($this->image);
}
/**
* Save the image as the image type the original image was
*
* #param String[type] $savePath – The path to store the new image
* #param string $imageQuality – The qulaity level of image to create
*
* #return Saves the image
*/
public function saveImage($savePath, $imageQuality=”100″, $download = false)
{
switch($this->ext)
{
case ‘image/jpg’:
case ‘image/jpeg’:
// Check PHP supports this file type
if (imagetypes() & IMG_JPG) {
imagejpeg($this->newImage, $savePath, $imageQuality);
}
break;
case ‘image/gif’:
// Check PHP supports this file type
if (imagetypes() & IMG_GIF) {
imagegif($this->newImage, $savePath);
}
break;
case ‘image/png’:
$invertScaleQuality = 9 – round(($imageQuality/100) * 9);
// Check PHP supports this file type
if (imagetypes() & IMG_PNG) {
imagepng($this->newImage, $savePath, $invertScaleQuality);
}
break;
}
if($download)
{
header(‘Content-Description: File Transfer’);
header(“Content-type: application/octet-stream”);
header(“Content-disposition: attachment; filename= “.$savePath."");
readfile($savePath);
}
imagedestroy($this->newImage);
}
/**
* Resize the image to these set dimensions
*
* #param int $width - Max width of the image
* #param int $height - Max height of the image
* #param string $resizeOption – Scale option for the image
*
* #return Save new image
*/
public function resizeTo( $width, $height, $resizeOption = ‘default’ )
{
switch(strtolower($resizeOption))
{
case ‘exact’:
$this->resizeWidth = $width;
$this->resizeHeight = $height;
break;
case ‘maxwidth’:
$this->resizeWidth = $width;
$this->resizeHeight = $this->resizeHeightByWidth($width);
break;
case ‘maxheight’:
$this->resizeWidth = $this->resizeWidthByHeight($height);
$this->resizeHeight = $height;
break;
default:
if($this->origWidth > $width || $this->origHeight > $height)
{
if ( $this->origWidth > $this->origHeight ) {
$this->resizeHeight = $this->resizeHeightByWidth($width);
$this->resizeWidth = $width;
} else if( $this->origWidth < $this->origHeight ) {
$this->resizeWidth = $this->resizeWidthByHeight($height);
$this->resizeHeight = $height;
}
} else {
$this->resizeWidth = $width;
$this->resizeHeight = $height;
}
break;
}
$this->newImage = imagecreatetruecolor($this->resizeWidth, $this->resizeHeight);
imagecopyresampled($this->newImage, $this->image, 0, 0, 0, 0, $this->resizeWidth, $this->resizeHeight, $this->origWidth, $this->origHeight);
}
/**
* Get the resized height from the width keeping the aspect ratio
*
* #param int $width – Max image width
*
* #return Height keeping aspect ratio
*/
private function resizeHeightByWidth($width)
{
return floor(($this->origHeight/$this->origWidth)*$width);
}
/**
* Get the resized width from the height keeping the aspect ratio
*
* #param int $height – Max image height
*
* #return Width keeping aspect ratio
*/
private function resizeWidthByHeight($height)
{
return floor(($this->origWidth/$this->origHeight)*$height);
}
}
?>
<!– Below functions is to used for resizing and saving the image –>
<?php
$resize = new ResizeImage(‘images/1.jpg’);
$resize->resizeTo(500, 500, ‘exact’);
$resize->saveImage(‘images/5.jpg’);
$resize->resizeTo(500, 500, ‘maxWidth’);
$resize->saveImage(‘images/6.png’);
$resize->resizeTo(500, 500, ‘maxHeight’);
$resize->saveImage(‘images/7.png’);
$resize->resizeTo(500, 500);
$resize->saveImage(‘images/8.png’);
//$resize->resizeTo(500, 500, ‘exact’);
//$resize->saveImage(‘images/9.png’, “100″, true);
echo “<img src=’images/1.jpg’>”;
echo “<br>”;
echo “<img src=’images/6.png’>”;
echo “<br>”;
echo “<img src=’images/7.png’>”;
echo “<br>”;
echo “<img src=’images/8.png’>”;
echo “<br>”;
echo “<img src=’images/9.jpg’>”;
//echo “<img src=’images/5.jpg’ height=’600′ width=’1000′>”;
?>
If you have any trouble to use in this code kindly share with me. I will help you.
The following script are used to resize images. However, I want to be able to define the width and then the image should be resized proportionally and keep the aspect ratio.
Here's my code.
index.php
<?php
include( 'function.php');
// settings
$max_file_size = 1024*200; // 200kb
$valid_exts = array('jpeg', 'jpg', 'png', 'gif');
// thumbnail sizes
$sizes = array(100 => 100, 150 => 150, 250 => 250);
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 {
$msg = 'Unsupported file';
}
} else{
$msg = 'Please upload image smaller than 200KB';
}
}
?>
functions.php
/**
* Image resize
* #param int $width
* #param int $height
*/
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 = 'uploads/'.$width.'x'.$height.'_'.$_FILES['image']['name'];
/* 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, $path, 100);
break;
case 'image/png':
imagepng($tmp, $path, 0);
break;
case 'image/gif':
imagegif($tmp, $path);
break;
default:
exit;
break;
}
return $path;
/* cleanup memory */
imagedestroy($image);
imagedestroy($tmp);
}
How should i proceed? Don't have that much experience on this area, so a guide or examples would be great. Everything is appriciated! Thanks in advance.