How to scale down an image on the server side with PHP? - php

I have some images that are pulled from a server and $imgUrl holds the path of the image.
Right now I use <img src="<?php echo $imgUrl ?>" width="100" height="200"/> or CSS to scale down the image, but I want to do it in PHP so that I will serve already scaled images to the DOM
Any ideas?
Thanks

This solution will cause the thumb to be created when it is requested for the first time. All future requests will fetch the already created thumb. It is using ImageMagick:
HTML:
<img src="script.php?img=example" />
PHP (script.php):
$width = 140;
$height = 80;
$image = $_GET['img'];
$ext = 'png';
// Check if file exists
if ( ! file_exists('/path/to/the/'.$image.'.'.$ext))
{
die('Unable to process the requested file.');
}
// Check if a thumb already exists, otherwise create a thumb
if (file_exists('/path/to/the/'.$image.'_thumb.'.$ext))
{
$img = new imagick('/path/to/the/'.$image.'_thumb.'.$ext);
}
else
{
$img = new imagick('/path/to/the/'.$image.'.'.$ext);
$img->setImageFormat($ext);
$img->scaleImage($width, 0);
$img->cropImage($width, $height, 0, 0);
$img->writeImage('/path/to/the/'.$image.'_thumb.'.$ext);
}
// Return as an image
header('Content-Type: image/'.$ext);
echo $img;

You should create a smaller version and save it to a folder. Then you don't need to rezise them on every request (it's memory intensive). Use Gd or ImageMagick for resize.
Example with GD

Be aware that doing this in PHP will mean a memory intensive process either every time the image is accessed (if done on the fly) or when the image is saved (which means you'll be using more storage to save the converted images). If you're still sure this is something you need/want then look into using GD. See this answer for an idea or how to do this: Image GD resize to 100px while keep the ratio

Here is what I am using atm. Feel free to extract you needs:
Usage:
<CLASS>::scale_image($dir.$name, 1024, 768, $dir.'thumb_'.$name);
/**
* Most simple way to get File Extension
* #param string $path Local path to File
* #return string Extension in lower case
*/
public static function extension($path){
return strtolower(pathinfo($path, PATHINFO_EXTENSION));
}
/**
* Rename Filename for more secure usage
* #param string $name filename
* #return string more secure filename
*/
public static function secure_name($name){
return urlencode(preg_replace('/[^a-z0-9 \-_\.]/i', '_', strtolower($name)));
}
/**
* Scale Image without ratio changes
* #param int $sw source width of orig image
* #param int $sh source height of orig image
* #param int $tw max target width
* #param int $th max target height
* #return array list($width, $height)
*/
public static function scale($sw, $sh, $tw, $th){
if ($sw > $tw && $sw/$tw > $sh/$th) {
$tw = $sw * ($tw / $sw);
$th = $sh * ($tw / $sw);
}else if ($sh > $th) {
$tw = $sw * ($th / $sh);
$th = $sh * ($th / $sh);
}else{
$th = $sh;
$tw = $sw;
}
return array(round($tw), round($th));
}
/**
* Scale Image
* #param string $sPath
* #param int $width max width
* #param int $height max height
* #param string $tPath Optional Path for Thumbnail
* #param int $thumbScale Scale ratio for optional Thumbnail (Width and Height / $thumbScale)
* #return void
*/
public static function scale_image($sPath, $width, $height, $tPath = NULL, $thumbScale = 10){
if(!function_exists('imagecreatetruecolor')){
return;
}
$ext = strtolower(self::extension($sPath));
if($ext == 'jpg' or $ext == 'jpeg'){
$src = imagecreatefromjpeg($sPath);
}elseif($ext == 'png'){
$src = imagecreatefrompng($sPath);
}elseif($ext == 'gif'){
$src = imagecreatefromgif($sPath);
}else{
return;
}
list($sw, $sh) = getimagesize($sPath);
list($tw, $th) = File::scale($sw, $sh, $width, $height);
$trg = imagecreatetruecolor($tw, $th);
imagecopyresampled($trg, $src, 0, 0, 0, 0, $tw, $th, $sw, $sh);
imagejpeg($trg, $sPath, 90);
if($tPath){
$tw = (int)$tw / $thumbScale;
$th = (int)$th / $thumbScale;
$trg = imagecreatetruecolor($tw, $th);
imagecopyresampled($trg, $src, 0, 0, 0, 0, $tw, $th, $sw, $sh);
imagejpeg($trg, $tPath, 90);
}
}

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

PHP resize image function creates beautiful jpg files but horrible png files

Following PHP function works great for jpg files. However it creates pixelated and too cropped png files.
How do I have to alter the function to create better quality png files?
/**
* Resize image (while keeping aspect ratio and cropping it off sexy)
*
*
* #param string $source_image The location to the original raw image.
* #param string $destination The location to save the new image.
* #param int $final_width The desired width of the new image
* #param int $final_height The desired height of the new image.
* #param int $quality The quality of the JPG to produce 1 - 100
*
*
* #return bool success state
*/
public static function resizeImage($source_image, $file_ext, $destination, $final_width = 470, $final_height = 470, $quality = 85)
{
$image = imagecreatefromstring(file_get_contents($source_image));
$width = imagesx($image);
$height = imagesy($image);
if (!$width || !$height) {
return false;
}
$original_aspect = $width / $height;
$final_aspect = $final_width / $final_height;
if ($original_aspect >= $final_aspect) {
// horizontal image
$new_height = $final_height;
$new_width = $width / ($height / $final_height);
} else {
// vertical image
$new_width = $final_width;
$new_height = $height / ($width / $final_width);
}
$thumb = imagecreatetruecolor($final_width, $final_height);
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $final_width) / 2, // Center the image horizontally
0 - ($new_height - $final_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
// if the file is a jpg file
if ($file_ext == 'jpg') {
// add '.jpg' to file path, save it as a .jpg file with our $destination_filename parameter
$destination .= '.jpg';
imagejpeg($thumb, $destination, $quality);
// if the file is a png file
} elseif ($file_ext == 'png') {
// add '.png' to file path, save it as a .jpg file with our $destination_filename parameter
$destination .= '.png';
imagepng($thumb, $destination);
}
if (file_exists($destination)) {
return true;
}
// default return
return false;
}
I have very limited knowledge about image files and therefore I do not understand why this function works fine for jpg- and not for png-files.
I would be very thankful for any kind of help!

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.

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