Another addition to zorroswordsman at gmail dot com's resize class.
The function takes $_FILES['sent_image'] as 1st parameter. The 2nd is complete destination path.
It only moves images.
It returns destination path if succeeded, and false if any error occurred.
<?php
public function move_image($tmp_img, $dest_img)
{
//verifies if the uploaded file is an image
if (strpos($tmp_img['type'], 'image') !== false)
{
//moves the uploaded file into the destination place
if (move_uploaded_file($tmp_img['tmp_name'], $dest_img)) {
return $dest_img;
}
}
return false;
}
?>
imagecopyresampled
(PHP 4 >= 4.0.6, PHP 5)
imagecopyresampled — Copy and resize part of an image with resampling
Description
imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.
In other words, imagecopyresampled() will take an rectangular area from src_image of width src_w and height src_h at position (src_x ,src_y ) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x ,dst_y ).
If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_image is the same as src_image ) but if the regions overlap the results will be unpredictable.
Parameters
- dst_im
-
Destination image link resource.
- src_im
-
Source image link resource.
- dst_x
-
x-coordinate of destination point.
- dst_y
-
y-coordinate of destination point.
- src_x
-
x-coordinate of source point.
- src_y
-
y-coordinate of source point.
- dst_w
-
Destination width.
- dst_h
-
Destination height.
- src_w
-
Source width.
- src_h
-
Source height.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Simple example
This example will resample an image to half its original size.
<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-type: image/jpeg');
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Output
imagejpeg($image_p, null, 100);
?>
The above example will output something similar to:
Example #2 Resampling an image proportionally
This example will display an image with the maximum width, or height, of 200 pixels.
<?php
// The file
$filename = 'test.jpg';
// Set a maximum height and width
$width = 200;
$height = 200;
// Content type
header('Content-type: image/jpeg');
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagejpeg($image_p, null, 100);
?>
The above example will output something similar to:
Notes
Note: There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().
See Also
imagecopyresampled
28-Dec-2008 06:53
27-Dec-2008 11:39
Another tiny ammendment to zorroswordsman at gmail dot com's resize class AND matt at rees-jenkins dot co dot uk addition. The class may resize to different width and height not only same ones:
<?php
// Set maximum image size (pixels)
public function set_size($max_x = 100,$max_y = 100)
{
// Resize
if($this->x_input > $max_x || $this->y_input > $max_y)
{
$a= $max_x / $max_y;
$b= $this->x_input / $this->y_input;
if ($a<$b)
{
$this->x_output = $max_x;
$this->y_output = ($max_x / $this->x_input) * $this->y_input;
}
else
{
$this->y_output = $max_y;
$this->x_output = ($max_y / $this->y_input) * $this->x_input;
}
// Ready
$this->resize = TRUE;
}
// Don't resize
else { $this->resize = FALSE; }
}
?>
And the use of the class is now:
<?php
##### DEMO #####
// Image
$src = "myimage.jpg";
// Begin
$img = new imaging;
$img->set_img($src);
$img->set_quality(80);
// Small thumbnail
$img->set_size(250,150);
$img->save_img("small_250x150_" . $src);
// Baby thumbnail
$img->set_size(50,250);
$img->save_img("baby_50x250_" . $src);
// Finalize
$img->clear_cache();
?>
14-Oct-2008 10:32
A tiny ammendment to zorroswordsman at gmail dot com's resize class. It was only resizing if both the width AND height where greater than the desired size. This should fix it:
<?php
// Set maximum image size (pixels)
function set_size($size = 100)
{
// Resize
if($this->x_input > $size || $this->y_input > $size)
{
// Wide
if($this->x_input >= $this->y_input)
{
$this->x_output = $size;
$this->y_output = ($this->x_output / $this->x_input) * $this->y_input;
}
// Tall
else
{
$this->y_output = $size;
$this->x_output = ($this->y_output / $this->y_input) * $this->x_input;
}
// Ready
$this->resize = TRUE;
}
// Don't resize
else { $this->resize = FALSE; }
}
?>
25-Sep-2008 02:46
I've created a PHP5 image resize class, using ImageCopyResampled, that someone might find useful, with support for JPEG, PNG, and GIF formats. It retains the original image's aspect ratio when resizing, and doesn't resize or resample if the original width and height is smaller then the desired resize.
<?php
// Imaging
class imaging
{
// Variables
private $img_input;
private $img_output;
private $img_src;
private $format;
private $quality = 80;
private $x_input;
private $y_input;
private $x_output;
private $y_output;
private $resize;
// Set image
public function set_img($img)
{
// Find format
$ext = strtoupper(pathinfo($img, PATHINFO_EXTENSION));
// JPEG image
if(is_file($img) && ($ext == "JPG" OR $ext == "JPEG"))
{
$this->format = $ext;
$this->img_input = ImageCreateFromJPEG($img);
$this->img_src = $img;
}
// PNG image
elseif(is_file($img) && $ext == "PNG")
{
$this->format = $ext;
$this->img_input = ImageCreateFromPNG($img);
$this->img_src = $img;
}
// GIF image
elseif(is_file($img) && $ext == "GIF")
{
$this->format = $ext;
$this->img_input = ImageCreateFromGIF($img);
$this->img_src = $img;
}
// Get dimensions
$this->x_input = imagesx($this->img_input);
$this->y_input = imagesy($this->img_input);
}
// Set maximum image size (pixels)
public function set_size($size = 100)
{
// Resize
if($this->x_input > $size && $this->y_input > $size)
{
// Wide
if($this->x_input >= $this->y_input)
{
$this->x_output = $size;
$this->y_output = ($this->x_output / $this->x_input) * $this->y_input;
}
// Tall
else
{
$this->y_output = $size;
$this->x_output = ($this->y_output / $this->y_input) * $this->x_input;
}
// Ready
$this->resize = TRUE;
}
// Don't resize
else { $this->resize = FALSE; }
}
// Set image quality (JPEG only)
public function set_quality($quality)
{
if(is_int($quality))
{
$this->quality = $quality;
}
}
// Save image
public function save_img($path)
{
// Resize
if($this->resize)
{
$this->img_output = ImageCreateTrueColor($this->x_output, $this->y_output);
ImageCopyResampled($this->img_output, $this->img_input, 0, 0, 0, 0, $this->x_output, $this->y_output, $this->x_input, $this->y_input);
}
// Save JPEG
if($this->format == "JPG" OR $this->format == "JPEG")
{
if($this->resize) { imageJPEG($this->img_output, $path, $this->quality); }
else { copy($this->img_src, $path); }
}
// Save PNG
elseif($this->format == "PNG")
{
if($this->resize) { imagePNG($this->img_output, $path); }
else { copy($this->img_src, $path); }
}
// Save GIF
elseif($this->format == "GIF")
{
if($this->resize) { imageGIF($this->img_output, $path); }
else { copy($this->img_src, $path); }
}
}
// Get width
public function get_width()
{
return $this->x_input;
}
// Get height
public function get_height()
{
return $this->y_input;
}
// Clear image cache
public function clear_cache()
{
@ImageDestroy($this->img_input);
@ImageDestroy($this->img_output);
}
}
##### DEMO #####
// Image
$src = "myimage.jpg";
// Begin
$img = new imaging;
$img->set_img($src);
$img->set_quality(80);
// Small thumbnail
$img->set_size(200);
$img->save_img("small_" . $src);
// Baby thumbnail
$img->set_size(50);
$img->save_img("baby_" . $src);
// Finalize
$img->clear_cache();
?>
12-Aug-2008 01:49
The suggestion of converting a gif to a png to retain transparency was useful. However the steps used to maintain the transparency work for a gif as well, so the conversion step is not necessary. Just do everything the same, and save as a gif anyway. i.e.
<?php
$g_iw is new image width
$g_ih is new image height
$img_src=imagecreatefromgif($g_srcfile);
$img_dst=imagecreatetruecolor($g_iw,$g_ih);
//preserve alpha
imagecolortransparent($img_dst, imagecolorallocate($img_dst, 0, 0, 0));
imagealphablending($img_dst, false);
imagesavealpha($img_dst, true);
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);
imagegif($img_dst, $g_dstfile);
imagedestroy($img_dst);
?>
17-Jul-2008 09:20
Wrote a function for sanitising user uploaded images. It saves the native image in size roughly 800x600 so it still fits on most screens when opened, makes a desired size thumbnail and turns all images into high quality jpegs for smaller bandwidth use.
Thumbnails are made in a similar way a designer would make them in photoshop, first resize the most troublesome dimension to desired size, then crop the rest out so the image retains proportions and most of it ends up in the thumbnail.
<?php
// $image is $_FILES[ <image name> ]
// $imageId is the id used in a database or wherever for this image
// $thumbWidth and $thumbHeight are desired dimensions for the thumbnail
function processImage( $image, $imageId, $thumbWidth, $thumbHeight )
{
$type = $image[ 'type' ];
$galleryPath = 'images/collection/';
if ( strpos( $type, 'image/' ) === FALSE )
{ // not an image
return FALSE;
}
$type = str_replace( 'image/', '', $type );
$createFunc = 'imagecreatefrom' . $type;
$im = $createFunc( $image[ 'tmp_name' ] );
$size = getimagesize( $image[ 'tmp_name' ] );
$w = $size[ 0 ];
$h = $size[ 1 ];
if ( $w > 800 || $h > 600 )
{ // we make sure the image isn't too huge
if ( $w > 800 )
{
$nw = 800;
$nh = ceil( $nw*($h/$w) );
}elseif( $h > 600 )
{
$nh = 600;
$nw = ceil( $nh*($w/$h) );
}
$im2 = imagecreatetruecolor( $nw, $nh );
imagecopyresampled( $im2, $im, 0, 0, 0, 0, $nw, $nh, $w, $h );
imagedestroy( $im );
$im = $im2;
$w = $nw;
$h = $nh;
}
// create thumbnail
$tw = $thumbWidth;
$th = $thumbHeight;
$imT = imagecreatetruecolor( $tw, $th );
if ( $tw/$th > $th/$tw )
{ // wider
$tmph = $h*($tw/$w);
$temp = imagecreatetruecolor( $tw, $tmph );
imagecopyresampled( $temp, $im, 0, 0, 0, 0, $tw, $tmph, $w, $h ); // resize to width
imagecopyresampled( $imT, $temp, 0, 0, 0, $tmph/2-$th/2, $tw, $th, $tw, $th ); // crop
imagedestroy( $temp );
}else
{ // taller
$tmpw = $w*($th/$h );
$imT = imagecreatetruecolor( $tmpw, $th );
imagecopyresampled( $imT, $im, 0, 0, 0, 0, $tmpw, $h, $w, $h ); // resize to height
imagecopyresampled( $imT, $temp, 0, 0, $tmpw/2-$tw/2, 0, $tw, $th, $tw, $th ); // crop
imagedestroy( $temp );
}
// save the image
imagejpeg( $im, $galleryPath . $imgid . '.jpg', 100 );
imagejpeg( $imT, $galleryPath . $imgid . '_thumb.jpg', 100 );
}
?>
19-May-2008 05:53
Here's a little function I wrote to resize images to a maximum dimension - based on what facebook does in the galleries. You put in a source, destination and a maximum dimension in pixels (eg 300), and for example if the image is long and thin, the longest edge will be 300px, yet the image retains proportions. A square image will become 300x300, a 6x4 (landscape) will become 300x200, a 4x6 (portrait) - 200x300 etc.
It works on jpg images, but other formats can easily be added.
<?php
function createThumb($spath, $dpath, $maxd) {
$src=@imagecreatefromjpeg($spath);
if (!$src) {return false;} else {
$srcw=imagesx($src);
$srch=imagesy($src);
if ($srcw<$srch) {$height=$maxd;$width=floor($srcw*$height/$srch);}
else {$width=$maxd;$height=floor($srch*$width/$srcw);}
if ($width>$srcw && $height>$srch) {$width=$srcw;$height=$srch;} //if image is actually smaller than you want, leave small (remove this line to resize anyway)
$thumb=imagecreatetruecolor($width, $height);
if ($height<100) {imagecopyresized($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));}
else {imagecopyresampled($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));}
imagejpeg($thumb, $dpath);
return true;
}
}
?>
18-Mar-2008 07:41
I hated that enlarging an image resulted in giant pixels rather than a smoother look, so I wrote this function. It takes longer, but gives a much nicer look.
<?php
function imagecopyresampledSMOOTH(&$dst_img, &$src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $mult=1.25){
// don't use a $mult that's too close to an int or this function won't make much of a difference
$tgt_w = round($src_w * $mult);
$tgt_h = round($src_h * $mult);
// using $mult <= 1 will make the current step w/h smaller (or the same), don't allow this, always resize by at least 1 pixel larger
if($tgt_w <= $src_w){ $tgt_w += 1; }
if($tgt_h <= $src_h){ $tgt_h += 1; }
// if the current step w/h is larger than the final height, adjust it back to the final size
// this check also makes it so that if we are doing a resize to smaller image, it happens in one step (since that's already smooth)
if($tgt_w > $dst_w){ $tgt_w = $dst_w; }
if($tgt_h > $dst_h){ $tgt_h = $dst_h; }
$tmpImg = imagecreatetruecolor($tgt_w, $tgt_h);
imagecopyresampled($tmpImg, $src_img, 0, 0, $src_x, $src_y, $tgt_w, $tgt_h, $src_w, $src_h);
imagecopy($dst_img, $tmpImg, $dst_x, $dst_y, 0, 0, $tgt_w, $tgt_h);
imagedestroy($tmpImg);
// as long as the final w/h has not been reached, reep on resizing
if($tgt_w < $dst_w OR $tgt_h < $dst_h){
imagecopyresampledSMOOTH($dst_img, $dst_img, $dst_x, $dst_y, $dst_x, $dst_y, $dst_w, $dst_h, $tgt_w, $tgt_h, $mult);
}
}
?>
16-Mar-2008 06:58
A small thumb script. Lets you specify max height and width. The thumb will always be of a rectangular shape while the image itself retains it's proportions. Very clean.
<?php
// The file
$filename = 'a.jpg';
// Set a maximum height and width
$width = 80;
$height = 80;
$thumbsize = 80;
// Content type
header('Content-type: image/jpeg');
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($thumbsize, $thumbsize);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, -($width/2) + ($thumbsize/2), -($height/2) + ($thumbsize/2), 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagejpeg($image_p, null, 100);
?>
07-Mar-2008 10:45
Here's a simple function to resample one JPEG imagefile to another while keeping aspect ratio of the source within the destination's dimensions. You can also tune the allowable distortion if you end up making too many thumbnails with thin blank areas around them. Should work when enlarging images too. Function returns true if it worked, false if not.
function resample_picfile($src, $dst, $w, $h)
{
// If distortion stretching is within the range below,
// then let image be distorted.
$lowend = 0.8;
$highend = 1.25;
$src_img = imagecreatefromjpeg($src);
if($src_img)
{
$dst_img = ImageCreateTrueColor($w, $h);
/* if you don't want aspect-preserved images
to have a black bkgnd, fill $dst_img with the color of your choice here.
*/
if($dst_img)
{
$src_w = imageSX($src_img);
$src_h = imageSY($src_img);
$scaleX = (float)$w / $src_w;
$scaleY = (float)$h / $src_h;
$scale = min($scaleX, $scaleY);
$dstW = $w;
$dstH = $h;
$dstX = $dstY = 0;
$scaleR = $scaleX / $scaleY;
if($scaleR < $lowend || $scaleR > $highend)
{
$dstW = (int)($scale * $src_w + 0.5);
$dstH = (int)($scale * $src_h + 0.5);
// Keep pic centered in frame.
$dstX = (int)(0.5 * ($w - $dstW));
$dstY = (int)(0.5 * ($h - $dstH));
}
imagecopyresampled(
$dst_img, $src_img, $dstX, $dstY, 0, 0,
$dstW, $dstH, $src_w, $src_h);
imagejpeg($dst_img, $dst);
imagedestroy($dst_img);
}
imagedestroy($src_img);
return file_exists($dst);
}
return false;
}
02-Mar-2008 03:51
If anyone felt like implementing Bicubic Sharper and/or Bicubic Smoother, that would seriously rock.
20-Feb-2008 09:16
This is a fixed version of ImageCopyResampledBicubic posted by liviu.malaescu
The original version wasn't respecting src_x & src_y args
<?php
function ImageCopyResampledBicubic(&$dst_image, &$src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) {
// we should first cut the piece we are interested in from the source
$src_img = ImageCreateTrueColor($src_w, $src_h);
imagecopy($src_img, $src_image, 0, 0, $src_x, $src_y, $src_w, $src_h);
// this one is used as temporary image
$dst_img = ImageCreateTrueColor($dst_w, $dst_h);
ImagePaletteCopy($dst_img, $src_img);
$rX = $src_w / $dst_w;
$rY = $src_h / $dst_h;
$w = 0;
for ($y = 0; $y < $dst_h; $y++) {
$ow = $w; $w = round(($y + 1) * $rY);
$t = 0;
for ($x = 0; $x < $dst_w; $x++) {
$r = $g = $b = 0; $a = 0;
$ot = $t; $t = round(($x + 1) * $rX);
for ($u = 0; $u < ($w - $ow); $u++) {
for ($p = 0; $p < ($t - $ot); $p++) {
$c = ImageColorsForIndex($src_img, ImageColorAt($src_img, $ot + $p, $ow + $u));
$r += $c['red'];
$g += $c['green'];
$b += $c['blue'];
$a++;
}
}
ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img, $r / $a, $g / $a, $b / $a));
}
}
// apply the temp image over the returned image and use the destination x,y coordinates
imagecopy($dst_image, $dst_img, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h);
// we should return true since ImageCopyResampled/ImageCopyResized do it
return true;
}
?>
15-Jan-2008 06:09
Here is a function I thought I would share that will resample and copy an image with rounded corners.
<?php
/** ------------------------------------------------------------
* Copy and resample an image with rounded corners.
* ----------------------------------------------------------- */
function imageRoundedCopyResampled(&$dstimg, &$srcimg, $dstx, $dsty, $srcx,
$srcy, $dstw, $dsth, $srcw, $srch, $radius) {
# Resize the Source Image
$srcResized = imagecreatetruecolor($dstw, $dsth);
imagecopyresampled($srcResized, $srcimg, 0, 0, $srcx, $srcy,
$dstw, $dsth, $srcw, $srch);
# Copy the Body without corners
imagecopy($dstimg, $srcResized, $dstx+$radius, $dsty,
$radius, 0, $dstw-($radius*2), $dsth);
imagecopy($dstimg, $srcResized, $dstx, $dsty+$radius,
0, $radius, $dstw, $dsth-($radius*2));
# Create a list of iterations; array(array(X1, X2, CenterX, CenterY), ...)
# Iterations in order are: Top-Left, Top-Right, Bottom-Left, Bottom-Right
$iterations = array(
array(0, 0, $radius, $radius),
array($dstw-$radius, 0, $dstw-$radius, $radius),
array(0, $dsth-$radius, $radius, $dsth-$radius),
array($dstw-$radius, $dsth-$radius, $dstw-$radius, $dsth-$radius)
);
# Loop through each corner 'iteration'
foreach($iterations as $iteration) {
list($x1,$y1,$cx,$cy) = $iteration;
for ($y=$y1; $y<=$y1+$radius; $y++) {
for ($x=$x1; $x<=$x1+$radius; $x++) {
# If length (X,Y)->(CX,CY) is less then radius draw the point
$length = sqrt(pow(($cx - $x), 2) + pow(($cy - $y), 2));
if ($length < $radius) {
imagecopy($dstimg, $srcResized, $x+$dstx, $y+$dsty,
$x, $y, 1, 1);
}
}
}
}
}
?>
20-Nov-2007 03:15
None of the stuff I've seen for resizing transparent GIFs works consistently and yields a good image. The hack I thought of is silly, but it works okay -- convert GIF to PNG. This worked for me.
$g_iw is new image width
$g_ih is new image height
$img_src=imagecreatefromgif($g_srcfile);
$img_dst=imagecreatetruecolor($g_iw,$g_ih);
//preserve alpha
imagecolortransparent($img_dst, imagecolorallocate($img_dst, 0, 0, 0));
imagealphablending($img_dst, false);
imagesavealpha($img_dst, true);
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);
imagepng($img_dst, $g_dstfile);
im