PHPのお勉強!

PHP TOP

imagecopyresized

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecopyresized画像の一部をコピーしサイズを変更する

説明

imagecopyresized(
    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

imagecopyresized() は指定した画像の矩形部分を 別の画像へコピーします。dst_image はコピー先の イメージ ID、src_image はコピー元のイメージ ID です。

言い換えると、imagecopyresized()src_image の座標 (src_x,src_y) にある 幅 src_width、 高さ src_height の矩形領域を受け取って、それを dst_image の座標 (dst_x,dst_y) にある幅 dst_width、 高さ dst_height の矩形領域に配置します。

コピー先とコピー元の座標、幅、高さが異なった場合、画像の一部が 適当に伸縮されます。座標の原点は左上です。(仮に、 dst_imagesrc_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

コピー元の高さ。

戻り値

成功した場合に true を、失敗した場合に false を返します。

変更履歴

バージョン 説明
8.0.0 dst_imagesrc_image は、 GdImage クラスのインスタンスを期待するようになりました。 これより前のバージョンでは、 resource を期待していました。

例1 イメージをリサイズする

この例はイメージを半分のサイズで表示します。

<?php
// ファイルと新規サイズ
$filename = 'test.jpg';
$percent = 0.5;

// コンテントタイプ
header('Content-Type: image/jpeg');

// 新規サイズを取得します
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// 読み込み
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// リサイズ
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// 出力
imagejpeg($thumb);
?>

上の例の出力は、 たとえば以下のようになります。

出力例 : イメージをリサイズする

イメージは半分サイズで出力されますが、 imagecopyresampled() を使用するとより良い品質になります。

注意

注意:

パレットイメージの制限(255+1 色)による問題があります。 カラーの再サンプリングやフィルタリングには通常は 255 色以上の色が 必要となります。再サンプルするピクセルとその色を計算するために ある種の近似計算が使用されます。パレットに新しい色を割り当てよう として失敗すると、(理論的に)最も近い色が選択されます。 それは必ずしも常に可視色とは限りません。そのため、 空白(あるいは不可視な)といった不可思議な結果がもたらされます。 この問題を回避するには、imagecreatetruecolor() で 生成されるような True カラーイメージを目的のイメージとして 使用してください。

参考

  • imagecopyresampled() - 再サンプリングを行いイメージの一部をコピー、伸縮する
  • imagescale() - 幅と高さを指定して、画像の縮尺を変更する
  • imagecrop() - 指定した矩形に画像をクロップする
add a note

User Contributed Notes 33 notes

up
19
robby at planetargon dot com
19 years ago
Most of the examples below don't keep the proportions properly. They keep using if/else for the height/width..and forgetting that you might have a max height AND a max width, not one or the other.

/**
* Resize an image and keep the proportions
* @author Allison Beckwith <allison@planetargon.com>
* @param string $filename
* @param integer $max_width
* @param integer $max_height
* @return image
*/
function resizeImage($filename, $max_width, $max_height)
{
list($orig_width, $orig_height) = getimagesize($filename);

$width = $orig_width;
$height = $orig_height;

# taller
if ($height > $max_height) {
$width = ($max_height / $height) * $width;
$height = $max_height;
}

# wider
if ($width > $max_width) {
$height = ($max_width / $width) * $height;
$width = $max_width;
}

$image_p = imagecreatetruecolor($width, $height);

$image = imagecreatefromjpeg($filename);

imagecopyresampled($image_p, $image, 0, 0, 0, 0,
$width, $height, $orig_width, $orig_height);

return $image_p;
}
up
4
jesse at method studios
19 years ago
imagecopyresized() does not do any resampling. This makes it extremely quick. If quality is an issue, use imagecopyresampled().
up
4
email at vladislav dot net
13 years ago
I didn't find here before any script giving both GIF and PNG transparent images correct, so I offer you mine.
Here is the code for 'image.php' script to generate a resized or original sized images of any type (JPEG, GIF, PNG) with respect to possible transparency of GIF and PNG.
The following script can be used in HTML tag IMG (to display an image marked in database with ID equal to 1 and resized to max 100px) like this:
<img src="image.php?id=1&size=100" />.

<?php
/* *************************
* Script by A. Vladislav I.
* ************************* */
$id = $_GET['id'];
$size = $_GET['size'];
if(!empty(
$id))
{
/* Here you may take the source image path from where you want: current direcory, databse etc.
I used the $_GET['id'] for giving the script an ID of the image in database, where its real name is stored.
I consider later the $f variable responsible to store file name and $type variable responsible to store mime type of the image. You may use function GetImageSize() to discover the mime type.
So don't forget to set the */
$f = /*...*/ ;
/* and */
$type = /*...*/ ;
/* ... */
}
$imgFunc = '';
switch(
$type)
{
case
'image/gif':
$img = ImageCreateFromGIF($f);
$imgFunc = 'ImageGIF';
$transparent_index = ImageColorTransparent($img);
if(
$transparent_index!=(-1)) $transparent_color = ImageColorsForIndex($img,$transparent_index);
break;
case
'image/jpeg':
$img = ImageCreateFromJPEG($f);
$imgFunc = 'ImageJPEG';
break;
case
'image/png':
$img = ImageCreateFromPNG($f);
ImageAlphaBlending($img,true);
ImageSaveAlpha($img,true);
$imgFunc = 'ImagePNG';
break;
default:
die(
"ERROR - no image found");
break;
}
header("Content-Type: ".$type);
if(!empty(
$size))
{

list(
$w,$h) = GetImageSize($f);
if(
$w==0 or $h==0 ) die("ERROR - zero image size");
$percent = $size / (($w>$h)?$w:$h);
if(
$percent>0 and $percent<1)
{
$nw = intval($w*$percent);
$nh = intval($h*$percent);
$img_resized = ImageCreateTrueColor($nw,$nh);
if(
$type=='image/png')
{
ImageAlphaBlending($img_resized,false);
ImageSaveAlpha($img_resized,true);
}
if(!empty(
$transparent_color))
{
$transparent_new = ImageColorAllocate($img_resized,$transparent_color['red'],$transparent_color['green'],$transparent_color['blue']);
$transparent_new_index = ImageColorTransparent($img_resized,$transparent_new);
ImageFill($img_resized, 0,0, $transparent_new_index);
}
if(
ImageCopyResized($img_resized,$img, 0,0,0,0, $nw,$nh, $w,$h ))
{
ImageDestroy($img);
$img = $img_resized;

}
}
}
$imgFunc($img);
ImageDestroy($img);
?>

P.S.
The script can be written better (optimized etc.), but I hope you can do it by yourself.
up
3
development at lab-9 dot com
19 years ago
If you read your Imagedata from a Database Blob and use the functions from above to resize the image to a thumbnail improving a lot of traffic, you will have to make temporary copies of the files in order that the functions can access them

Here a example:

// switch through imagetypes
$extension = "jpg";
if(mysql_result($query, 0, 'type') == "image/pjpeg")
{ $extension = "jpg"; } // overwrite
else if(mysql_result($query, 0, 'type') == "image/gif")
{ $extension = "gif"; } // overwrite

// get a temporary filename
// use microtime() to get a unique filename
// if you request more than one file f.e. by creating large numbers of thumbnails, the server could be not fast enough to save all these different files and you get duplicated copies and resizepics() will resize and output often the same content

$filename = microtime()."_temp.".$extension;

// open
$tempfile = fopen($filename, "w+");

// write
fwrite($tempfile, mysql_result($query, 0, 'image'));

// close
fclose($tempfile);

// resize and output the content
echo resizepics($filename, '100', '70');

// delete temporary file
unlink($filename);

NOTE: this script has to be put into a file which sends correct header informations to the browser, otherwise you won't get more to see than a big red cross :-)
up
2
hodgman at ali dot com dot au
18 years ago
Users of this function should be aware that this function can return false in certain circumstances! I am assuming this is an indicator of failure.

None of the example code displayed in these notes takes this into account, so all of these examples contain weaknesses that could crash a program if not used with care.

However, it is not documented what kinds situations will cause it to fail, and what side effects (if it is not atomic) occur if the operation fails, so we will have to wait for the documentation to be updated before this function can be used in rock-solid (crash-proof) code.

[[I posted this information earlier, but I phrased it as a question so it was removed by the editors]]
up
1
skurrilo at skurrilo dot de
24 years ago
If you aren't happy with the quality of the resized images, just give ImageMagick a try. (http://www.imagemagick.org) This is a commandline tool for converting and viewing images.
up
4
smelban at smwebdesigns dot com
19 years ago
Resize image proportionaly where you give a max width or max height

<?php
header
('Content-type: image/jpeg');
//$myimage = resizeImage('filename', 'newwidthmax', 'newheightmax');
$myimage = resizeImage('test.jpg', '150', '120');
print
$myimage;

function
resizeImage($filename, $newwidth, $newheight){
list(
$width, $height) = getimagesize($filename);
if(
$width > $height && $newheight < $height){
$newheight = $height / ($width / $newwidth);
} else if (
$width < $height && $newwidth < $width) {
$newwidth = $width / ($height / $newheight);
} else {
$newwidth = $width;
$newheight = $height;
}
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return
imagejpeg($thumb);
}
?>
up
1
mecdesign at hotmail dot com
19 years ago
This code will resize your images if your image needs to fit (without stretching) into a max height / width destination image that is not a 1:1 ratio (mine was 4:3).

<?
// Ratios
$image_ratio = $width / $height; // Actual image's ratio
$destination_ratio = $max_width / $max_height; // Ratio of dest. placeholder

// Taller
if($image_ratio < $destination_ratio)
{
//Too tall:
if($height > $max_height)
{
$height = $max_height;
$width = ceil($height / $image_ratio);
}
}
// Wider / balanced & too wide:
else if ($width > $max_width)
{
$width = $max_width;
$height = ceil($width / $image_ratio);
}
?>
up
1
no at name dot com
19 years ago
I was searching for script, that do not resize on the fly, but copy resized file to other place, so after long searches, i've done this function. I hope it will be usefull for someone:
(This is not original code, i'v taked it from somwhere and edited a ltl :)
<?php
function resize($cur_dir, $cur_file, $newwidth, $output_dir)
{
$dir_name = $cur_dir;
$olddir = getcwd();
$dir = opendir($dir_name);
$filename = $cur_file;
$format='';
if(
preg_match("/.jpg/i", "$filename"))
{
$format = 'image/jpeg';
}
if (
preg_match("/.gif/i", "$filename"))
{
$format = 'image/gif';
}
if(
preg_match("/.png/i", "$filename"))
{
$format = 'image/png';
}
if(
$format!='')
{
list(
$width, $height) = getimagesize($filename);
$newheight=$height*$newwidth/$width;
switch(
$format)
{
case
'image/jpeg':
$source = imagecreatefromjpeg($filename);
break;
case
'image/gif';
$source = imagecreatefromgif($filename);
break;
case
'image/png':
$source = imagecreatefrompng($filename);
break;
}
$thumb = imagecreatetruecolor($newwidth,$newheight);
imagealphablending($thumb, false);
$source = @imagecreatefromjpeg("$filename");
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$filename="$output_dir/$filename";
@
imagejpeg($thumb, $filename);
}
}
?>
call this function using
<?
resize("./input folder", "picture_file_name", "width", "./output folder");
?>
up
2
FearINC at gmail dot com
19 years ago
I wrote a function not long ago that creates a thumbnail out of a large picture. Unlike other notes on this page, the code is a function so it can be used many times on the same script. The function allows the programer to set max height and width and resizes the picture proportionally.
<?php
function saveThumbnail($saveToDir, $imagePath, $imageName, $max_x, $max_y) {
preg_match("'^(.*)\.(gif|jpe?g|png)$'i", $imageName, $ext);
switch (
strtolower($ext[2])) {
case
'jpg' :
case
'jpeg': $im = imagecreatefromjpeg ($imagePath);
break;
case
'gif' : $im = imagecreatefromgif ($imagePath);
break;
case
'png' : $im = imagecreatefrompng ($imagePath);
break;
default :
$stop = true;
break;
}

if (!isset(
$stop)) {
$x = imagesx($im);
$y = imagesy($im);

if ((
$max_x/$max_y) < ($x/$y)) {
$save = imagecreatetruecolor($x/($x/$max_x), $y/($x/$max_x));
}
else {
$save = imagecreatetruecolor($x/($y/$max_y), $y/($y/$max_y));
}
imagecopyresized($save, $im, 0, 0, 0, 0, imagesx($save), imagesy($save), $x, $y);

imagegif($save, "{$saveToDir}{$ext[1]}.gif");
imagedestroy($im);
imagedestroy($save);
}
}
?>

the function for now takes only jpg,gif and png files, but that can easily be changed.
It's an easy to use easy to understand function and I hope it will come useful to someone.
up
1
Halit Yesil mail at halityesil dot com
17 years ago
This Class image resize or crop,
your copyright text write on the image and your logo marge on the image.

Full Class code => http://www.phpbuilder.com/snippet/download.php?type=snippet&id=2188
/**
* Author : Halit YESIL
* www : www.halityesil.com, www.prografik.net, www.trteknik.net
* email : mail@halityesil.com, halit.yesil@prografik.net, halit.yesil@trteknik.net
* GSM : +90.535 648 3504
* Create Date : 21 / 03 / 2007
*
*
* Script : Image resize and croping class.
* You can Write copyright text and attach your logo write on image with this class
*
*
* $obj = new pg_image($arg);
*
*
* Varibles Information
* [0] type => (POST | FILE) => Source File Send Type _FILES OR Dir
* [1] file => ({if POST Array file = $_FILES['yourfile']}|{if FILE false}) => Source File filesource
* [2] path => ({if FILE String [ dirname/filename.extension ]}) => Source File Root Path
* [3] target => ({if FILE String [ dirname/filename.extension ]}) => Target File Root Path
* [4] width => (integer) => Target File Width
* [5] height => (integer) => Target File Height
* [6] quality => (integer 1 - 100) => Target File Quality 0-100 %
* [7] action => (crop | resize) => Target Action "resize" OR "crop"
* [8] bordersize => (integer 0-5) => Target Border Size
* [9] bordercolor => (color hex) => Target Border Color
* [10] bgcolor => (color hex) => Target Background Color
* [11] copytext => (String) => Copyright Content Text
* [12] copycolor => (color hex) => Copyright Text Color
* [13] copyshadow => (color hex) => Copyright Text Shadow color
* [14] copybgcolor => (color hex) => Copyright Background Color
* [15] copybgshadow => (color hex) => Copyright Background Shadow Color
* [16] copybordersize => (integer 0-5) => Copyright Border Size 1-3
* [17] copybordercolor => (color hex) => Copyright Border Color
* [18] copyposition => (top | topright | topleft | center | left | right | bottom | bottomright | bottomleft) => Copyright Position
* [19] logoposition => (top | topright | topleft | center | left | right | bottom | bottomright | bottomleft) => Logo Image Position
* [20] logoimage => (String [ dirname/filename.extension] Allow Extension (PNG | GIF | JPG)) => Logo Image Root Path "PNG" OR "GIF" OR "JPG"
*
*
*
*
*/

<?php

$source
= ($_REQUEST['img'] != '')?$_REQUEST['img']:'braille3.jpg';
$arg =array( type =>'FILE',
file =>false,
path =>$source,
target =>'',
width =>150,
height =>50,
quality =>80,
action =>'resize',
bordersize =>1,
bordercolor =>'#00CCFF',
bgcolor =>'#000000',
copytext =>'Bodrum 1998',
copycolor =>'#FFFFFF',
//copyshadow =>'#000000',
//copybgcolor =>'#D0FFCC',
//copybgshadow =>'#656565',
copybordersize =>0,
copybordercolor =>'#FFFFFF',
copyposition =>'bottom',
logoposition =>'topleft',
logoimage =>'logo.png');

//$arg = "$source,,400,300,80,resize";
new pg_image($arg);

?>
up
1
finnsi at centrum dot is
19 years ago
If you need to delete or resize images in the filesystem (not in DB) without loosing the image quality...
I commented the code as much as possible so that newbies (like myself) will understand it. ;)

<?php

/*

WRITTEN BY:
Finnur Eiriksson, (http://www.centrum.is/finnsi)
Based on snippets that have been posted on www.PHP.net
Drop me an e-mail if you have any questions.

NOTE:
This code is written to either delete or resize pictures in the file system, so if you have your pictures in a database
you will have to make some changes. Also, if you are using other picture formats than .gif's or .jpg's you
will have to add som code as well (Read the comments to find out where to do this).

IMPORTANT:
The $_GET['resizepic'] variable only contains the NAME of the file that is going to be deleted/resized.

The internet guest account (IUSR_SERVERNAME on WINDOWS) must have read and write permissions (execution permission not needed)
in your image directory (i.e. $dir_name = "FooBar"). It is a good idea to have a separate directory for images that users
can upload to and manipulate the contents. Ideally, you should have one directory for the pictures that are used for the website,
and another upload directory

*/

$dir_name = "FooBar"; // Enter the name of the directory that contains the images
$olddir = getcwd(); // Get the Current Windows Directory to be able to switch back in the end of the script
$dir = opendir($dir_name); //make a directory handle
//To delete a picture
if(isset($_GET['delpic'])){
chdir('images');
$delpic = $_GET['delpic'];
@
unlink($delpic);
chdir($olddir);
}
//To resize a picture
if(isset($_GET['resize'])){
//$_GET['resize'] contains the resize-percentage (for example 80 and 40, for 80% and 40% respectively. To double the image in size the user enters 200 etc.)
// File and new size
$percent = ($_GET['resize']/100);
chdir('images');// change the windows directory to the image directory
$filename = $_GET['resizepic'];

// Decide the content type, NB:This code is written to only execute on .gif's and .jpg's
// If you want other formats than .gif's and .jpg's add your code here, in the same manner:
$format='';
if(
preg_match("/.jpg/i", "$filename")){
$format = 'image/jpeg';
header('Content-type: image/jpeg');
}
if (
preg_match("/.gif/i", "$filename")){
$format = 'image/gif';
header('Content-type: image/gif');
}
if(
$format!=''){ //This is where the actual resize process begins...
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load the image
switch($format){
case
'image/jpeg':
$source = imagecreatefromjpeg($filename);
break;
case
'image/gif';
$source = imagecreatefromgif($filename);
break;
}
//Get the Image
$thumb = imagecreatetruecolor($newwidth,$newheight);
//This must be set to false in order to be able to overwrite the black
//pixels in the background with transparent pixels. Otherwise the new
//pixels would just be applied on top of the black background.
imagealphablending($thumb, false);
//Make a temporary file handle
$source = @imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//Write the image to the destination file
@imagejpeg($thumb, $filename);
//Change back to the old directory... I'm not sure that this is neccessary
chdir($olddir);
//Specify where you want the user to go after the operation:
header('Location: foobar.php');
}
}


?>