imagecopyresampled
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)
imagecopyresampled — 再サンプリングを行いイメージの一部をコピー、伸縮する
説明
GdImage
$dst_image
,GdImage
$src_image
,int
$dst_x
,int
$dst_y
,int
$src_x
,int
$src_y
,int
$dst_width
,int
$dst_height
,int
$src_width
,int
$src_height
): bool
imagecopyresampled() は、イメージの矩形の部分 を別のイメージにコピーします。同時にピクセル値を滑らかに補間を行い、 このため、特にサイズを小さくした場合には鮮明さが維持されます。
言い換えると、imagecopyresampled() は
src_image
の座標 (src_x
,src_y
) にある
幅 src_width
、高さ src_height
の矩形領域を受け取って、それを dst_image
の座標 (dst_x
,dst_y
)
にある幅 dst_width
、
高さ dst_height
の矩形領域に配置します。
コピー元とコピー先の座標、幅、高さが異なる場合には、
適当なイメージ伸縮が行われます。座標は、左上を基準とします。
この関数は、同じイメージ内の領域にコピーする場合にも使用可能です
(dst_image
が src_image
と同じ場合) が、領域が重なる場合の結果は予測できません。
パラメータ
dst_image
-
コピー先の画像リソース。
src_image
-
コピー元の画像リソース。
dst_x
-
コピー先の x 座標。
dst_y
-
コピー先の y 座標。
src_x
-
コピー元の x 座標。
src_y
-
コピー元の y 座標。
dst_width
-
コピー先の幅。
dst_height
-
コピー先の高さ。
src_width
-
コピー元の幅。
src_height
-
コピー元の高さ。
変更履歴
バージョン | 説明 |
---|---|
8.0.0 |
dst_image と
src_image は、
GdImage
クラスのインスタンスを期待するようになりました。
これより前のバージョンでは、
resource を期待していました。
|
例
例1 単純な例
この例は、イメージをオリジナルの半分のサイズに再サンプルします。
<?php
// ファイル
$filename = 'test.jpg';
$percent = 0.5;
// コンテントタイプ
header('Content-Type: image/jpeg');
// 新規サイズを取得します
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// 再サンプル
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// 出力
imagejpeg($image_p, null, 100);
?>
上の例の出力は、 たとえば以下のようになります。
例2 イメージを均等に再サンプルする
この例は最大の幅もしくは高さが 200 ピクセルのイメージを表示します。
<?php
// ファイル
$filename = 'test.jpg';
// 最大の高さ・幅を設定します
$width = 200;
$height = 200;
// コンテントタイプ
header('Content-Type: image/jpeg');
// 新規サイズを取得します
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;
}
// 再サンプル
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// 出力
imagejpeg($image_p, null, 100);
?>
上の例の出力は、 たとえば以下のようになります。
注意
注意:
パレットイメージの制限(255+1色)による問題があります。 カラーの再サンプリングやフィルタリングには通常は255色以上の色が 必要となります。再サンプルするピクセルとその色を計算するために ある種の近似計算が使用されます。パレットに新しい色を割り当てよう として失敗すると、(理論的に)最も近い色が選択されます。 それは必ずしも常に可視色とは限りません。そのため、 空白(あるいは不可視な)といった不可思議な結果がもたらされます。 この問題を回避するには、imagecreatetruecolor()で 生成されるようなTrueカラーイメージを目的のイメージとして 使用してください。
参考
- imagecopyresized() - 画像の一部をコピーしサイズを変更する
- imagescale() - 幅と高さを指定して、画像の縮尺を変更する
- imagecrop() - 指定した矩形に画像をクロップする
User Contributed Notes 37 notes
FOUR RECTANGLES
$src_image $dst_image
+------------+---------------------------------+ +------------+--------------------+
| | | | | |
| | | | $dst_y |
| | | | | |
| $src_y | +-- $dst_x --+----$dst_width----+ |
| | | | | | |
| | | | | Resampled | |
| | | | | | |
+-- $src_x --+------ $src_width ------+ | | $dst_height | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | +------------------+ |
| | Sample | | | |
| | | | | |
| | | | | |
| $src_height | | | |
| | | | +---------------------------------+
| | | |
| | | |
| +------------------------+ |
| |
| |
+----------------------------------------------+
Here is my ultimate image resizer that preserves transparency for gif's and png's and has an option to crop images to fixed dimensions (preserves image proportions by default)
<?php
function image_resize($src, $dst, $width, $height, $crop=0){
if(!list($w, $h) = getimagesize($src)) return "Unsupported picture type!";
$type = strtolower(substr(strrchr($src,"."),1));
if($type == 'jpeg') $type = 'jpg';
switch($type){
case 'bmp': $img = imagecreatefromwbmp($src); break;
case 'gif': $img = imagecreatefromgif($src); break;
case 'jpg': $img = imagecreatefromjpeg($src); break;
case 'png': $img = imagecreatefrompng($src); break;
default : return "Unsupported picture type!";
}
// resize
if($crop){
if($w < $width or $h < $height) return "Picture is too small!";
$ratio = max($width/$w, $height/$h);
$h = $height / $ratio;
$x = ($w - $width / $ratio) / 2;
$w = $width / $ratio;
}
else{
if($w < $width and $h < $height) return "Picture is too small!";
$ratio = min($width/$w, $height/$h);
$width = $w * $ratio;
$height = $h * $ratio;
$x = 0;
}
$new = imagecreatetruecolor($width, $height);
// preserve transparency
if($type == "gif" or $type == "png"){
imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
imagealphablending($new, false);
imagesavealpha($new, true);
}
imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);
switch($type){
case 'bmp': imagewbmp($new, $dst); break;
case 'gif': imagegif($new, $dst); break;
case 'jpg': imagejpeg($new, $dst); break;
case 'png': imagepng($new, $dst); break;
}
return true;
}
?>
Example that I use when uploading new images to the server.
This saves the original picture in the form:
original.type
and creates a new thumbnail:
100x100.type
<?php
$pic_type = strtolower(strrchr($picture['name'],"."));
$pic_name = "original$pic_type";
move_uploaded_file($picture['tmp_name'], $pic_name);
if (true !== ($pic_error = @image_resize($pic_name, "100x100$pic_type", 100, 100, 1))) {
echo $pic_error;
unlink($pic_name);
}
else echo "OK!";
?>
Cheers!
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();
?>
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;
}
?>
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;
}
}
?>
This function is taken from lots of web sources so thanks to all for posting. It creates square or landscape thumbnails from .jpgs from either portait or landscape original images. I decide in advance which way I want the thumbs to display for consistency. I usually sharpen the images as well post-upload, to save on server resources. I can post this code if anyone wants it. I hope this helps someone...
# create thumbnails from jpgs
# usage:
# create_jpgthumb(uploaded file, final file (with path), thumb height, thumb width, jpg quality, scale thumb (true) or fixed size (false);
function create_jpgthumb($original, $thumbnail, $max_width, $max_height, $quality, $scale = true) {
list ($src_width, $src_height, $type, $w) = getimagesize($original);
if (!$srcImage = @imagecreatefromjpeg($original)) {
return false;
}
# image resizes to natural height and width
if ($scale == true) {
if ($src_width > $src_height ) {
$thumb_width = $max_width;
$thumb_height = floor($src_height * ($max_width / $src_width));
} else if ($src_width < $src_height ) {
$thumb_height = $max_height;
$thumb_width = floor($src_width * ($max_height / $src_height));
} else {
$thumb_width = $max_height;
$thumb_height = $max_height;
}
if (!@$destImage = imagecreatetruecolor($thumb_width, $thumb_height)) {
return false;
}
if (!@imagecopyresampled($destImage, $srcImage, 0, 0, 0, 0, $thumb_width, $thumb_height, $src_width, $src_height)) {
return false;
}
# image is fixed to supplied width and height and cropped
} else if ($scale == false) {
$ratio = $max_width / $max_height;
# thumbnail is landscape
if ($ratio > 1) {
# uploaded pic is landscape
if ($src_width > $src_height) {
$thumb_width = $max_width;
$thumb_height = ceil($max_width * ($src_height / $src_width));
if ($thumb_height > $max_width) {
$thumb_height = $max_width;
$thumb_width = ceil($max_width * ($src_width / $src_height));
}
# uploaded pic is portrait
} else {
$thumb_height = $max_width;
$thumb_width = ceil($max_width * ($src_height / $src_width));
if ($thumb_width > $max_width) {
$thumb_width = $max_width;
$thumb_height = ceil($max_width * ($src_height / $src_width));
}
$off_h = ($src_height - $src_width) / 2;
}
if (!@$destImage = imagecreatetruecolor($max_width, $max_height)) {
return false;
}
if (!@imagecopyresampled($destImage, $srcImage, 0, 0, 0, $off_h, $thumb_width, $thumb_height, $src_width, $src_height)) {
return false;
}
# thumbnail is square
} else {
if ($src_width > $src_height) {
$off_w = ($src_width - $src_height) / 2;
$off_h = 0;
$src_width = $src_height;
} else if ($src_height > $src_width) {
$off_w = 0;
$off_h = ($src_height - $src_width) / 2;
$src_height = $src_width;
} else {
$off_w = 0;
$off_h = 0;
}
if (!@$destImage = imagecreatetruecolor($max_width, $max_height)) {
return false;
}
if (!@imagecopyresampled($destImage, $srcImage, 0, 0, $off_w, $off_h, $max_width, $max_height, $src_width, $src_height)) {
return false;
}
}
}
@imagedestroy($srcImage);
if (!@imageantialias($destImage, true)) {
return false;
}
if (!@imagejpeg($destImage, $thumbnail, $quality)) {
return false;
}
@imagedestroy($destImage);
return true;
}
<?php
$new_file = img_resize("./img/", "test.jpg","copy_test.jpg",300);
echo "<IMG src = '$new_file'>";
function img_resize($path,$tmp_name,$new_name,$new_width){
if (!file_exists($path.$filename)){
echo "file not found!";
exit;
}
if (!is_writable($path)){
echo "error:permission denied!";
exit;
}
list($width, $height) = getimagesize($path . $tmp_name);
$new_height = abs($new_width * $height / $width);
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($path . $tmp_name);
imagecopyresampled($image_p, $image, 0, 0, 0, 0,
$new_width, $new_height, $width, $height);
imagejpeg($image_p, $path . $new_name);
return $path.$new_name;
}
?>
It should be noted that the imagecopyresampled() function is much more blurry than Photoshop CS's default bicubic funtion. And looks similar to a blury version of Photoshop's bilinear function. The documentation fails to note which algorithm is used in resampling.
I was looking around and couldn't find a function that resizes images to any ratio without leaving a blank area, so i wrote this one. It's able to resize images to any size ratio, when the ratio is no match with the original it will crop proportional area on the original and resize it.
<?php
function _ckdir($fn) {
if (strpos($fn,"/") !== false) {
$p=substr($fn,0,strrpos($fn,"/"));
if (!is_dir($p)) {
_o("Mkdir: ".$p);
mkdir($p,777,true);
}
}
}
function img_resizer($src,$quality,$w,$h,$saveas) {
/* v2.5 with auto crop */
$r=1;
$e=strtolower(substr($src,strrpos($src,".")+1,3));
if (($e == "jpg") || ($e == "peg")) {
$OldImage=ImageCreateFromJpeg($src) or $r=0;
} elseif ($e == "gif") {
$OldImage=ImageCreateFromGif($src) or $r=0;
} elseif ($e == "bmp") {
$OldImage=ImageCreateFromwbmp($src) or $r=0;
} elseif ($e == "png") {
$OldImage=ImageCreateFromPng($src) or $r=0;
} else {
_o("Not a Valid Image! (".$e.") -- ".$src);$r=0;
}
if ($r) {
list($width,$height)=getimagesize($src);
// check if ratios match
$_ratio=array($width/$height,$w/$h);
if ($_ratio[0] != $_ratio[1]) { // crop image
// find the right scale to use
$_scale=min((float)($width/$w),(float)($height/$h));
// coords to crop
$cropX=(float)($width-($_scale*$w));
$cropY=(float)($height-($_scale*$h));
// cropped image size
$cropW=(float)($width-$cropX);
$cropH=(float)($height-$cropY);
$crop=ImageCreateTrueColor($cropW,$cropH);
// crop the middle part of the image to fit proportions
ImageCopy(
$crop,
$OldImage,
0,
0,
(int)($cropX/2),
(int)($cropY/2),
$cropW,
$cropH
);
}
// do the thumbnail
$NewThumb=ImageCreateTrueColor($w,$h);
if (isset($crop)) { // been cropped
ImageCopyResampled(
$NewThumb,
$crop,
0,
0,
0,
0,
$w,
$h,
$cropW,
$cropH
);
ImageDestroy($crop);
} else { // ratio match, regular resize
ImageCopyResampled(
$NewThumb,
$OldImage,
0,
0,
0,
0,
$w,
$h,
$width,
$height
);
}
_ckdir($saveas);
ImageJpeg($NewThumb,$saveas,$quality);
ImageDestroy($NewThumb);
ImageDestroy($OldImage);
}
return $r;
}
?>
Another add-on to previous php5 class for thumbnail (with a merge of Matt and Zorro's proposals).
This is dedicated to generate thumbnail on the fly for a webpage using the subclass thumbnail.
It saves the generated thumb as myimage_tn, in the same directory.
I'm quite new with php5, so I think this could be optimized, but it seems to work fine.
<?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($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; }
}
// 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);
}
}
class thumbnail extends imaging {
private $image;
private $width;
private $height;
function __construct($image,$width,$height) {
parent::set_img($image);
parent::set_quality(80);
parent::set_size($width,$height);
$this->thumbnail= pathinfo($image, PATHINFO_DIRNAME).pathinfo($image, PATHINFO_FILENAME).'_tn.'.pathinfo($image, PATHINFO_EXTENSION);
parent::save_img($this->thumbnail);
parent::clear_cache();
}
function __toString() {
return $this->thumbnail;
}
}
********
* DEMO *
********
$thumb = new thumbnail('./image_dir/sub_dir/myimage.jpg',100,100);
echo '<img src=\''.$thumb.'\' alt=\'myimage\' title=\'myimage\'/>';
?>
Windows does not accept floating width and height...
So, in "Example #2 Resampling an image proportionally", prefer :
<?php
if ($width/$height > $ratio_orig) {
$width = round( $height*$ratio_orig );
} else {
$height = round( $width/$ratio_orig );
}
?>
(used "round")
otherwise your image wont be resized.