Log in

View Full Version : Loading, resizing and renaming images



Jacquih
10-01-2006, 06:22 PM
Hi!
I was hoping that someone could give some advice on altering this code. As it stands, it uploads a picture file, gives it a random name, resizes it then creates a thumbnail.

I would like to alter this so that it can upload and resize image and thumbnail files separately. I would also like it to name the files using the $productId, such as $image = "i" . $productId . ".jpg".

(Handling the sql results is done with an abstraction layer.)

Here's what I got so far:


function addProduct()
{
$catId = $_POST['cboCategory'];
$name = $_POST['txtName'];
$description = $_POST['mtxDescription'];
$price = str_replace(',', '', (double)$_POST['txtPrice']);
$qty = (int)$_POST['txtQty'];
$sale = $_POST['cboSale'];
$notes = $_POST['mtxNotes'];

$images = uploadProductImage('fleImage', SRV_ROOT . 'images/');

$mainImage = $images['image'];
$thumbnail = $images['thumbnail'];

$sql = "INSERT INTO tbl_product (cat_id, pd_name, pd_description, pd_price, pd_qty, pd_image, pd_thumbnail, pd_date, pd_sale, pd_notes)
VALUES ('$catId', '$name', '$description', $price, $qty, '$mainImage', '$thumbnail', NOW(), '$sale', '$notes')";
$result = dbQuery($sql);

header("Location: index.php?catId=$catId");
}

//Upload an image and return the uploaded image name
function uploadProductImage($inputName, $uploadDir)
{
$image = $_FILES[$inputName];
$imagePath = '';
$thumbnailPath = '';

// if a file is given
if (trim($image['tmp_name']) != '') {
$ext = substr(strrchr($image['name'], "."), 1); //$extensions[$image['type']];

// generate a random new file name to avoid name conflict
$imagePath = md5(rand() * time()) . ".$ext";

list($width, $height, $type, $attr) = getimagesize($image['tmp_name']);

// make sure the image width does not exceed the maximum allowed width
if (LIMIT_PRODUCT_WIDTH && $width > MAX_PRODUCT_IMAGE_WIDTH) {
$result = createThumbnail($image['tmp_name'], $uploadDir . $imagePath, MAX_PRODUCT_IMAGE_WIDTH);
$imagePath = $result;
} else {
$result = move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath);
}

if ($result) {
// create thumbnail
$thumbnailPath = md5(rand() * time()) . ".$ext";
$result = createThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, THUMBNAIL_WIDTH);

// create thumbnail failed, delete the image
if (!$result) {
unlink($uploadDir . $imagePath);
$imagePath = $thumbnailPath = '';
} else {
$thumbnailPath = $result;
}
} else {
// the product cannot be upload / resized
$imagePath = $thumbnailPath = '';
}
}
return array('image' => $imagePath, 'thumbnail' => $thumbnailPath);
}

//Create a thumbnail of $srcFile and save it to $destFile; The thumbnail will be $width pixels
function createThumbnail($srcFile, $destFile, $width, $quality = 75)
{
$thumbnail = '';

if (file_exists($srcFile) && isset($destFile))
{
$size = getimagesize($srcFile);
$w = number_format($width, 0, ',', '');
$h = number_format(($size[1] / $size[0]) * $width, 0, ',', '');

$thumbnail = copyImage($srcFile, $destFile, $w, $h, $quality);
}

// return the thumbnail file name on sucess or blank on fail
return basename($thumbnail);
}

//copy an image to a destination file. The destination image size will be $w X $h pixels
function copyImage($srcFile, $destFile, $w, $h, $quality = 75)
{
$tmpSrc = pathinfo(strtolower($srcFile));
$tmpDest = pathinfo(strtolower($destFile));
$size = getimagesize($srcFile);

if ($tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg")
{
$destFile = substr_replace($destFile, 'jpg', -3);
$dest = imagecreatetruecolor($w, $h);
imageantialias($dest, TRUE);
} elseif ($tmpDest['extension'] == "png") {
$dest = imagecreatetruecolor($w, $h);
imageantialias($dest, TRUE);
} else {
return false;
}

switch($size[2])
{
case 1: //GIF
$src = imagecreatefromgif($srcFile);
break;
case 2: //JPEG
$src = imagecreatefromjpeg($srcFile);
break;
case 3: //PNG
$src = imagecreatefrompng($srcFile);
break;
default:
return false;
break;
}

imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);

switch($size[2])
{
case 1:
case 2:
imagejpeg($dest,$destFile, $quality);
break;
case 3:
imagepng($dest,$destFile);
}
return $destFile;

}



Thanks in advance for any advice!
Jacqui

lol33d
02-16-2008, 08:38 AM
Hi

how to resize height for images ?

rangana
02-16-2008, 08:48 AM
Hi lol33d,
You should not hijack someone's thread, anyway, you can resize the height, as well as the width using CSS.It could be something like:
<img src="image.jpg" style="height:300px;width:300px;">

See if it helps :D

lol33d
02-16-2008, 09:17 AM
WOW! THANKS;)


how to resize height for images ON [uploadProductImage] & [createThumbnail] FUNCTION PHP CODE

rangana
02-16-2008, 09:20 AM
...and those are things that I don't know :lol:
If I have to locate it in the PHP code above, I have this fear that I will lose a number of hair :D

jackbenimble4
02-16-2008, 01:26 PM
Here's a simple PHP 5 class that can resize and save .gif, .png and .jpg files.


<?php

class My_Image {

private $src, $im, $ext;

public function __construct($filename) {
$this->src = $filename;
$this->loadFile();
}

private function loadFile() {
$file = $this->src;

$system=explode('.',$file);
if (preg_match('/jpg|jpeg/',strtolower(end($system)))){
$this->ext = array('jpeg','.jpg');
$this->im = imagecreatefromjpeg($file);
}
elseif (preg_match('/png/',strtolower(end($system)))){
$this->im = imagecreatefrompng($file);
$this->ext = array('png','.png');
}
elseif (preg_match('/gif/',strtolower(end($system)))) {
$this->im = imagecreatefromgif($file);
$this->ext = array('gif','.gif');
}
else {
// unsupported format
$this->im = false;
return false;
}

return true;
}

public function resize($maxwidth, $maxheight) {


list($width, $height, $type, $attr) = getimagesize($this->src);


if($width > $maxwidth OR $height > $maxheight) {

// EXAMPLE SCENARIO
// Max-width: 700px, max-height: 400px
// width: 800px, max-height: 650px
// width ratio: .875 height ratio: .615

$widthRatio = $maxwidth/$width;
$heightRatio = $maxheight/$height;

if($widthRatio < $heightRatio) {
$new_width = $maxwidth;
$new_height = $height*$widthRatio;
}
elseif($heightRatio < $widthRatio) {
$new_height = $maxheight;
$new_width = $width*$heightRatio;
}
else {
$new_width = $width*$widthRatio;
$new_height = $height*$heightRatio;
}
}
else {
$new_width = $width;
$new_height = $height;
}

$newImage = imagecreatetruecolor($new_width, $new_height);
@imagecopyresampled($newImage,$this->im,0,0,0,0,$new_width,$new_height,$width,$height);

$this->im = $newImage;

return $this;

}

public static function load($file) {
return new self($file);
}

public function saveToFile($dest, $type = 'default') {
if($type == 'default') {
$ext = $this->ext;
call_user_func('image' . current($ext), &$this->im, $dest);

}

else {

call_user_func('image' . $type, &$this->im, $dest);

}

}

public function __clone() {

// reload from file so we don't have the same resources
$this->loadFile($this->src);

}

}


?>

Here's an example of how you'd use it:



$pathToImage = '/myimages/bigpic.jpg';
$pathToDestination = '/myimages/thumbnails/bigpic.jpg';

My_Image::load($pathToImage)->resize(300, 300)->saveToFile($pathToDestination);

// or

$image = new My_Image($pathToImage);
$secondImage = clone $image;
$image->saveToFile('/whatever/whatever.jpg', 'jpeg');
$secondImage->resize(300,300)->saveToFile('/whatever/thumbs/whatever.gif', 'gif');

lol33d
02-17-2008, 04:18 PM
how to resize height for Image & thumbnail on this sample :confused:


function addProduct()
{
$catId = $_POST['cboCategory'];
$name = $_POST['txtName'];
$description = $_POST['mtxDescription'];
$price = str_replace(',', '', (double)$_POST['txtPrice']);
$qty = (int)$_POST['txtQty'];
$sale = $_POST['cboSale'];
$notes = $_POST['mtxNotes'];

$images = uploadProductImage('fleImage', SRV_ROOT . 'images/');

$mainImage = $images['image'];
$thumbnail = $images['thumbnail'];

$sql = "INSERT INTO tbl_product (cat_id, pd_name, pd_description, pd_price, pd_qty, pd_image, pd_thumbnail, pd_date, pd_sale, pd_notes)
VALUES ('$catId', '$name', '$description', $price, $qty, '$mainImage', '$thumbnail', NOW(), '$sale', '$notes')";
$result = dbQuery($sql);

header("Location: index.php?catId=$catId");
}

//Upload an image and return the uploaded image name
function uploadProductImage($inputName, $uploadDir)
{
$image = $_FILES[$inputName];
$imagePath = '';
$thumbnailPath = '';

// if a file is given
if (trim($image['tmp_name']) != '') {
$ext = substr(strrchr($image['name'], "."), 1); //$extensions[$image['type']];

// generate a random new file name to avoid name conflict
$imagePath = md5(rand() * time()) . ".$ext";

list($width, $height, $type, $attr) = getimagesize($image['tmp_name']);

// make sure the image width does not exceed the maximum allowed width
if (LIMIT_PRODUCT_WIDTH && $width > MAX_PRODUCT_IMAGE_WIDTH) {
$result = createThumbnail($image['tmp_name'], $uploadDir . $imagePath, MAX_PRODUCT_IMAGE_WIDTH);
$imagePath = $result;
} else {
$result = move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath);
}

if ($result) {
// create thumbnail
$thumbnailPath = md5(rand() * time()) . ".$ext";
$result = createThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, THUMBNAIL_WIDTH);

// create thumbnail failed, delete the image
if (!$result) {
unlink($uploadDir . $imagePath);
$imagePath = $thumbnailPath = '';
} else {
$thumbnailPath = $result;
}
} else {
// the product cannot be upload / resized
$imagePath = $thumbnailPath = '';
}
}
return array('image' => $imagePath, 'thumbnail' => $thumbnailPath);
}

//Create a thumbnail of $srcFile and save it to $destFile; The thumbnail will be $width pixels
function createThumbnail($srcFile, $destFile, $width, $quality = 75)
{
$thumbnail = '';

if (file_exists($srcFile) && isset($destFile))
{
$size = getimagesize($srcFile);
$w = number_format($width, 0, ',', '');
$h = number_format(($size[1] / $size[0]) * $width, 0, ',', '');

$thumbnail = copyImage($srcFile, $destFile, $w, $h, $quality);
}

// return the thumbnail file name on sucess or blank on fail
return basename($thumbnail);
}

//copy an image to a destination file. The destination image size will be $w X $h pixels
function copyImage($srcFile, $destFile, $w, $h, $quality = 75)
{
$tmpSrc = pathinfo(strtolower($srcFile));
$tmpDest = pathinfo(strtolower($destFile));
$size = getimagesize($srcFile);

if ($tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg")
{
$destFile = substr_replace($destFile, 'jpg', -3);
$dest = imagecreatetruecolor($w, $h);
imageantialias($dest, TRUE);
} elseif ($tmpDest['extension'] == "png") {
$dest = imagecreatetruecolor($w, $h);
imageantialias($dest, TRUE);
} else {
return false;
}

switch($size[2])
{
case 1: //GIF
$src = imagecreatefromgif($srcFile);
break;
case 2: //JPEG
$src = imagecreatefromjpeg($srcFile);
break;
case 3: //PNG
$src = imagecreatefrompng($srcFile);
break;
default:
return false;
break;
}

imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);

switch($size[2])
{
case 1:
case 2:
imagejpeg($dest,$destFile, $quality);
break;
case 3:
imagepng($dest,$destFile);
}
return $destFile;

}