Resize Images (supports transparency) - php

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);

Related

thumbFileFullUrlArrPHP image upload - copy file, make thumbnail and save both images

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);
}
}
?>

Fetch Image from mysql and resize using timthumb in php

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.

Resize images in PHP at a specific size

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);

Upload , Resize and Save using PHP (or generating thumbnails)

I am making a website for users to be able to track their favorite bands. One of the features of the website is allowing users to upload pictures of any gigs they have been to, they are then saved to a file and image location is stored in the database.
My problem is I need to be able to resize the images upon saving, as the page is taking to long to load when there are many pictures.
I know there are many questions on here like this but i'm just not to sure how to modify the code I have to do this.
Is this the best way to do it or should I use thumbnails? as the images are going to be displayed in a gallery, if there is many then the page is going to load slower
My knowledge of php is limited so any help is appreciated
This is the code I have at the moment:
<?php
///UPLOAD IMAGES
$sql = "SELECT * FROM photouploads WHERE BandID ='$bandid'";
$result = mysql_query($sql,$connect)or die ($error1);
$row = mysql_num_rows($result);
$userid=$_SESSION['userid'];
if (isset($_POST['submit']))
{
$name = $bandid."(".++$row.").jpg";
$tmp_name=$_FILES['photo']['tmp_name'];
if ($name)
{
//start upload
$location="Photouploads/".$name;
if (move_uploaded_file($tmp_name,$location))
{
mysql_query("INSERT INTO photouploads (BandID,UserID,ImageLocation)
VALUES ('$bandid', '$userid', '$location')") ;
}
}
else
;
}
And my form:
<input type='file' name='photo' id='photo'>
<input type='submit' class='submitLink' name='submit' id='submit'value='upload'>
</form>";
?>
Here is a very basic PHP image resizing class i've used in the past. You'll need the PHP GD2 module installed and enabled in order for it to work.
Usage:
$resized = ImageResizer::resizeExistingImage($_FILES['photo']['tmp_name'],
null,
500,
500,
100);
if (!$resized){
throw new Exception('Could not resize image');
}
echo '<pre>';
print_r($resized);
echo '</pre>';
The Class:
class ImageResizer
{
const RESULT_RESIZE_NOT_REQUIRED = 'resize_not_required';
const RESULT_RESIZE_SUCCESSFUL = 'resize_successful';
private static $_filePath = null;
private static $_newPath = null;
private static $_maxwidth = null;
private static $_maxheight = null;
private static $_quality = null;
private static $_newWidth = null;
private static $_newHeight = null;
private static $_actualWidth = null;
private static $_actualHeight = null;
/**
* Takes an image (from a file path) and resizes it. The newly resized image
* can then either be created in a different location, therefore maintainig
* the original file. Or can be created in the original location, therefore
* overwriting the original file.
*
*
* #static
* #access public
* #param string $filePath The file path of the image to resize
* #param string $newPath The file path where the resized image will
* be created. Null to overwrite original.
* #param integer $maxwidth The maximum height of the resized image
* #param integer $maxheight The maximum width of the resized image
* #param integer $quality The quality of the image
*/
public static function resizeExistingImage($filePath,
$newPath = null,
$maxwidth = 1000,
$maxheight = 1000,
$quality = 100)
{
if (is_null($newPath)) {
$newPath = $filePath;
}
$gdImage = getimagesize($filePath);
$actualWidth = $gdImage[0];
$actualHeight = $gdImage[1];
// Do we even need to resize the image!?
if ($actualWidth <= $maxwidth && $actualHeight <= $maxheight){
return array('result' => self::RESULT_RESIZE_NOT_REQUIRED,
'newHeight' => $actualHeight,
'newWidth' => $actualWidth);
}
$ratio = $actualWidth / $maxwidth;
// echo "ratio : ".$ratio."<br />";
// echo "Current dimensions: ".$actualWidth." : ".$actualHeight." : <br />";
// set the defaults:
$newWidth = intval($actualWidth);
$newHeight = intval($actualHeight);
if ($actualWidth > $maxwidth) {
$newWidth = intval($maxwidth);
$newHeight = intval($actualHeight / $ratio);
}
// echo "After width process, dimensions: ".$newWidth." : ".$newHeight." : <br />";
// once we've got the size width, is the height now small enough?
if ($newHeight > $maxheight) {
// set a new ratio
$ratio = $newHeight / $maxheight;
$newWidth = intval($newWidth / $ratio);
$newHeight = intval($maxheight);
}
// echo "New dimensions: ".$newWidth." : ".$newHeight." : <br />";
// Assign the class vars
self::$_filePath = $filePath;
self::$_newPath = $newPath;
self::$_maxwidth = $maxwidth;
self::$_maxheight = $maxheight;
self::$_quality = $quality;
self::$_newWidth = $newWidth;
self::$_newHeight = $newHeight;
self::$_actualWidth = $actualWidth;
self::$_actualHeight = $actualHeight;
switch (strtolower($gdImage['mime'])) {
case 'image/jpeg':
self::_createFromJpeg();
break;
case 'image/pjpeg':
self::_createFromPJpeg();
break;
case 'image/png':
self::_createFromPng();
break;
case 'image/gif':
self::_createFromGif();
break;
default:
throw new Exception('Mime Type \'' . $gdImage['mime'] . '\' not supported');
break;
}
return array('result' => self::RESULT_RESIZE_SUCCESSFUL,
'newHeight' => $newHeight,
'newWidth' => $newWidth);
}
/**
* Resizes images of type image/jpeg.
*
* #static
* #access private
* #return void
*/
private static function _createFromJpeg()
{
$img = imagecreatefromjpeg(self::$_filePath);
$new_img = imagecreatetruecolor(self::$_newWidth, self::$_newHeight);
imagecopyresampled($new_img,
$img,
0,
0,
0,
0,
self::$_newWidth,
self::$_newHeight,
self::$_actualWidth,
self::$_actualHeight);
imagejpeg($new_img, self::$_newPath, self::$_quality);
}
/**
* Resizes images of type image/jpeg.
*
* #static
* #access private
* #return void
*/
private static function _createFromPJpeg()
{
$img = imagecreatefromjpeg(self::$_filePath);
imageinterlace($img, 1);
$new_img = imagecreatetruecolor(self::$_newWidth, self::$_newHeight);
imagecopyresampled($new_img,
$img,
0,
0,
0,
0,
self::$_newWidth,
self::$_newHeight,
self::$_actualWidth,
self::$_actualHeight);
imagejpeg($new_img, self::$_newPath, self::$_quality);
}
/**
* Resizes images of type image/png.
*
* #static
* #access private
* #return void
*/
private static function _createFromPng()
{
$img = imagecreatefrompng(self::$_filePath);
$new_img = imagecreatetruecolor(self::$_newWidth, self::$_newHeight);
imagecopyresampled($new_img,
$img,
0,
0,
0,
0,
self::$_newWidth,
self::$_newHeight,
self::$_actualWidth,
self::$_actualHeight);
imagepng($new_img, self::$_newPath);
}
/**
* Resizes images of type image/gif.
*
* #static
* #access private
* #return void
*/
private static function _createFromGif()
{
$img = imagecreatefromgif(self::$_filePath);
$new_img = imagecreatetruecolor(self::$_newWidth, self::$_newHeight);
imagecopyresampled($new_img,
$img,
0,
0,
0,
0,
self::$_newWidth,
self::$_newHeight,
self::$_actualWidth,
self::$_actualHeight);
imagegif($new_img, self::$_newPath);
}
}
Hope that helps.
Retrieving all the data to find a name for the new image is very innefficient. A better solution would be insert a record without storing the filename and generate the filename from the auto_increment id (using a base path /some/where/Photouploads/$bandid/).
If this is not your biggest performance problem, it soon will be.
Reducing the size of the images is a good idea too - as is checking for duplicates.
if there is many then the page is going to load slower
Defer loading of images below the fold - there are lots of ready made scripts to do this (e.g.)

PHP's imagepng() method saves an invalid image

I am using the GD library to automatically generate a thumbnail version of an uploaded image. I call the appropriate image____() function to save in the same format as the original. My code works fine for JPEG and GIF, but if I upload a PNG file, the resulting thumbnail is invalid. It actually only contains 33 bytes (with any source PNG that I've tried so far). This image does not display in the browser, nor can it be opened by Preview (on MacOS).
I use imagecreatetruecolor() along with imagecopyresampled() to generate the thumbnail, like this:
function _resizeImageToFit($resource, $size)
{
$sourceWidth = imagesx($resource);
$sourceHeight = imagesy($resource);
if($sourceWidth >= $sourceHeight) {
// landscape or square
$newHeight = 1.0*$size/$sourceWidth*$sourceHeight;
$newWidth = $size;
}
else {
// portrait
$newWidth = 1.0*$size/$sourceHeight*$sourceWidth;
$newHeight = $size;
}
$thmb = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($thmb, $resource, 0, 0, 0, 0, $newWidth, $newHeight, $sourceWidth, $sourceHeight);
return $thmb;
}
Below is the version info of my setup (It's MAMP Version 1.9.4)
PHP Version 5.3.2
GD Version bundled (2.0.34 compatible)
Here is an example of an invalid generated thumbnail image (PNG):
âPNG
IHDRdaØMì∞
I found my error. imagepng() takes a quality value range of 0 to 9, while imagejpeg() takes a range of 0 to 100 and imagegif() doesn't take any such parameter. I was trying to save a PNG with a quality of 100.
So, this is a lovely case of RTM. Thanks for your responses.
http://ca3.php.net/manual/en/function.imagepng.php
http://ca3.php.net/manual/en/function.imagejpeg.php
http://ca3.php.net/manual/en/function.imagegif.php
Try this function.
/**
* Crop new images using the source image
*
* #param string $source - Image source
* #param string $destination - Image destination
* #param integer $thumbW - Width for the new image
* #param integer $thumbH - Height for the new image
* #param string $imageType - Type of the image
*
* #return bool
*/
function cropImage($source, $destination, $thumbW, $thumbH, $imageType)
{
list($width, $height, $type, $attr) = getimagesize($source);
$x = 0;
$y = 0;
if ($width*$thumbH>$height*$thumbW) {
$x = ceil(($width - $height*$thumbW/$thumbH)/2);
$width = $height*$thumbW/$thumbH;
} else {
$y = ceil(($height - $width*$thumbH/$thumbW)/2);
$height = $width*$thumbH/$thumbW;
}
$newImage = imagecreatetruecolor($thumbW, $thumbH) or die ('Can not use GD');
/*
if ($extension=='jpg' || $extension=='jpeg') {
$image = imagecreatefromjpeg($source);
} else if ($extension=='gif') {
$image = imagecreatefromgif($source);
} else if ($extension=='png') {
$image = imagecreatefrompng($source);
}
*/
switch($imageType) {
case "image/gif":
$image = imagecreatefromgif($source);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$image = imagecreatefromjpeg($source);
break;
case "image/png":
case "image/x-png":
$image = imagecreatefrompng($source);
break;
}
if (!#imagecopyresampled($newImage, $image, 0, 0, $x, $y, $thumbW, $thumbH, $width, $height)) {
return false;
} else {
imagejpeg($newImage, $destination,100);
imagedestroy($image);
return true;
}
}

Categories