PHP 日本研討會 2024

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 是目標影像,src_image 是來源影像識別碼。

換句話說,imagecopyresized() 會從 src_image 中取出寬度為 src_width 和高度為 src_height 的矩形區域,位置在 (src_x,src_y),並將其放置到 dst_image 中寬度為 dst_width 和高度為 dst_height 的矩形區域,位置在 (dst_x,dst_y)。

如果來源和目標的座標以及寬度和高度不同,則會對影像片段進行適當的拉伸或縮放。座標指的是左上角。此函式可用於複製同一影像內的區域(如果 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);
?>

上面的範例會輸出類似以下的內容

Output of example : Resizing an image

影像將以一半大小輸出,但使用 imagecopyresampled() 可以獲得更好的品質。

注意事項

注意:

由於調色盤影像的限制(255+1 種顏色),存在一個問題。重新取樣或過濾影像通常需要超過 255 種顏色,因此會使用一種近似值來計算新的重新取樣像素及其顏色。使用調色盤影像時,我們會嘗試配置新的顏色,如果失敗,則選擇最接近(理論上)計算出的顏色。這不一定是視覺上最接近的顏色。這可能會產生奇怪的結果,例如空白(或視覺上空白)的影像。要跳過這個問題,請使用真彩色影像作為目標影像,例如使用 imagecreatetruecolor() 建立的影像。

另請參閱

新增註解

使用者貢獻的註解 33 則註解

19
robby at planetargon dot com
19 年前
以下大多數範例都沒有正確保持比例。他們不斷對高度/寬度使用 if/else...並且忘記了您可能會有最大高度和最大寬度,而不是兩者之一。

/**
* 調整影像大小並保持比例
* @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;

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

# 較寬
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;
}
4
jesse at method studios
19 年前
imagecopyresized() 不會進行任何重新取樣。這使其速度非常快。如果對品質有要求,請使用 imagecopyresampled()。
4
email at vladislav dot net
13 年前
我之前在這裡沒有找到任何可以正確處理 GIF 和 PNG 透明影像的腳本,因此我提供我的。
這是 'image.php' 腳本的程式碼,用於產生任何類型(JPEG、GIF、PNG)的調整大小或原始大小的影像,並考慮到 GIF 和 PNG 可能的透明度。
以下腳本可用於 HTML 標籤 IMG(顯示資料庫中標記 ID 等於 1 且調整大小至最大 100px 的影像),如下所示
<img src="image.php?id=1&size=100" />。

<?php
/* *************************
* 腳本作者:A. Vladislav I.
* ************************* */
$id = $_GET['id'];
$size = $_GET['size'];
if(!empty(
$id))
{
/* 在這裡,您可以從任何您想要的地方獲取原始影像路徑:目前目錄、資料庫等。
我使用 $_GET['id'] 來為腳本提供資料庫中影像的 ID,其中儲存了它的真實名稱。
我稍後會將 $f 變數視為負責儲存檔案名稱,而 $type 變數負責儲存影像的 MIME 類型。您可以使用 GetImageSize() 函數來找出 MIME 類型。
因此,不要忘記設定 */
$f = /*...*/ ;
/* 和 */
$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 - 找不到影像");
break;
}
header("Content-Type: ".$type);
if(!empty(
$size))
{

list(
$w,$h) = GetImageSize($f);
if(
$w==0 or $h==0 ) die("ERROR - 影像大小為零");
$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);
?>

附註:
此腳本可以寫得更好(最佳化等等),但我希望您可以自行完成。
3
development at lab-9 dot com
19 年前
如果您從資料庫 Blob 讀取影像資料,並使用上述函數將影像調整為縮圖以大幅改善流量,則必須建立檔案的臨時副本,以便函數可以存取它們

以下範例:

// 依照影像類型切換
$extension = "jpg";
if(mysql_result($query, 0, 'type') == "image/pjpeg")
{ $extension = "jpg"; } // 覆寫
else if(mysql_result($query, 0, 'type') == "image/gif")
{ $extension = "gif"; } // 覆寫

// 取得臨時檔案名稱
// 使用 microtime() 取得唯一的檔案名稱
// 如果您要求多個檔案,例如透過建立大量縮圖,伺服器可能不夠快來儲存所有這些不同的檔案,而且您會得到重複的副本,而 resizepics() 將經常調整大小並輸出相同的內容

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

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

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

// 關閉
fclose($tempfile);

// 調整大小並輸出內容
echo resizepics($filename, '100', '70');

// 刪除臨時檔案
unlink($filename);

注意:此腳本必須放入一個將正確標頭資訊傳送到瀏覽器的檔案中,否則您將看不到比一個大的紅色叉號更多的東西 :-)
2
hodgman at ali dot com dot au
18 年前
此函數的使用者應該注意到,此函數在某些情況下可能會傳回 false!我假設這表示失敗。

這些註解中顯示的任何範例程式碼都沒有考慮到這一點,因此如果使用不慎,所有這些範例都包含可能會使程式崩潰的弱點。

然而,它沒有記錄哪些情況會導致失敗,以及如果操作失敗時會發生哪些副作用(如果它不是原子性的),因此我們必須等待文件更新後才能在堅固(防崩潰)的程式碼中使用此函數。

[[我稍早發佈了此資訊,但我將其表達為一個問題,因此被編輯者刪除了]]
1
skurrilo at skurrilo dot de
24 年前
如果您對調整大小後的圖片品質不滿意,不妨試試 ImageMagick。(https://imagemagick.dev.org.tw)這是一個用於轉換和檢視圖片的命令列工具。
4
smelban at smwebdesigns dot com
19 年前
依比例調整圖片大小,您可以設定最大寬度或最大高度

<?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);
}
?>
1
mecdesign at hotmail dot com
19 年前
如果您的圖片需要放入一個非 1:1 比例(我的圖片是 4:3)的最大高度/寬度目標圖片中(不拉伸),此程式碼將調整您的圖片大小。

<?
// 比例
$image_ratio = $width / $height; // 實際圖片的比例
$destination_ratio = $max_width / $max_height; // 目標佔位符的比例

// 較高
if($image_ratio < $destination_ratio)
{
// 太高
if($height > $max_height)
{
$height = $max_height;
$width = ceil($height / $image_ratio);
}
}
// 較寬/平衡 & 太寬
else if ($width > $max_width)
{
$width = $max_width;
$height = ceil($width / $image_ratio);
}
?>
1
no at name dot com
19 年前
我正在尋找一個腳本,它不會即時調整大小,而是將調整大小後的文件複製到其他地方,經過長時間的搜尋,我完成了這個函式。我希望它對某些人有用
(這不是原始程式碼,我從某處取得並稍微編輯了一下 :))
<?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);
}
}
?>
使用以下方式呼叫此函式
<?
resize("./input folder", "picture_file_name", "width", "./output folder");
?>
2
FearINC at gmail dot com
19 年前
我不久前寫了一個函式,可以從大圖片建立縮圖。與此頁面上的其他筆記不同,該程式碼是一個函式,因此可以在同一個腳本上多次使用。此函式允許程式設計師設定最大高度和寬度,並按比例調整圖片大小。
<?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);
}
}
?>

這個函數目前僅接受 jpg、gif 和 png 檔案,但可以輕鬆更改。
這是一個易於使用、易於理解的函數,我希望它對某些人有所幫助。
1
Halit Yesil mail at halityesil dot com
17 年前
這個類別用於圖片調整大小或裁切,
將您的版權文字寫在圖片上,並將您的標誌合併到圖片上。

完整類別程式碼 => http://www.phpbuilder.com/snippet/download.php?type=snippet&id=2188
/**
* 作者:Halit YESIL
* 網址:www.halityesil.com, www.prografik.net, www.trteknik.net
* 電子郵件:mail@halityesil.com, halit.yesil@prografik.net, halit.yesil@trteknik.net
* 行動電話:+90.535 648 3504
* 建立日期:2007 年 3 月 21 日
*
*
* 腳本:圖片調整大小和裁切類別。
* 您可以使用此類別在圖片上寫入版權文字並附加您的標誌
*
*
* $obj = new pg_image($arg);
*
*
* 變數資訊
* [0] type => (POST | FILE) => 來源檔案傳送類型 _FILES 或 Dir
* [1] file => ({如果 POST 陣列 file = $_FILES['yourfile']}|{如果 FILE 為 false}) => 來源檔案檔案來源
* [2] path => ({如果 FILE 為字串 [ 路徑名稱/檔名.副檔名 ]}) => 來源檔案根路徑
* [3] target => ({如果 FILE 為字串 [ 路徑名稱/檔名.副檔名 ]}) => 目標檔案根路徑
* [4] width => (整數) => 目標檔案寬度
* [5] height => (整數) => 目標檔案高度
* [6] quality => (整數 1 - 100) => 目標檔案品質 0-100 %
* [7] action => (crop | resize) => 目標動作「resize」或「crop」
* [8] bordersize => (整數 0-5) => 目標邊框大小
* [9] bordercolor => (顏色十六進位) => 目標邊框顏色
* [10] bgcolor => (顏色十六進位) => 目標背景顏色
* [11] copytext => (字串) => 版權內容文字
* [12] copycolor => (顏色十六進位) => 版權文字顏色
* [13] copyshadow => (顏色十六進位) => 版權文字陰影顏色
* [14] copybgcolor => (顏色十六進位) => 版權背景顏色
* [15] copybgshadow => (顏色十六進位) => 版權背景陰影顏色
* [16] copybordersize => (整數 0-5) => 版權邊框大小 1-3
* [17] copybordercolor => (顏色十六進位) => 版權邊框顏色
* [18] copyposition => (top | topright | topleft | center | left | right | bottom | bottomright | bottomleft) => 版權位置
* [19] logoposition => (top | topright | topleft | center | left | right | bottom | bottomright | bottomleft) => 標誌圖片位置
* [20] logoimage => (字串 [ 路徑名稱/檔名.副檔名] 允許的副檔名 (PNG | GIF | JPG)) => 標誌圖片根路徑「PNG」或「GIF」或「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);

?>
1
finnsi at centrum dot is
19 年前
如果您需要在檔案系統中刪除或調整圖片大小(而非在資料庫中),而不會遺失圖片品質...
我盡可能地註解了程式碼,以便新手(像我自己)能夠理解。 ;)

<?php

/*

作者:
Finnur Eiriksson, (http://www.centrum.is/finnsi)
基於 www.PHP.net 上發布的程式碼片段。
如果您有任何問題,請寄電子郵件給我。

注意:
此程式碼旨在刪除或調整檔案系統中的圖片大小,因此如果您將圖片儲存在資料庫中,
您必須進行一些更改。此外,如果您使用 .gif 或 .jpg 以外的其他圖片格式,
您也必須新增一些程式碼(請閱讀註解以了解在哪裡進行此操作)。

重要:
$_GET['resizepic'] 變數僅包含要刪除/調整大小的檔案名稱。

網際網路訪客帳戶 (在 WINDOWS 上為 IUSR_SERVERNAME) 必須在您的圖片目錄(例如 $dir_name = "FooBar")中擁有讀取和寫入權限 (不需要執行權限)。
最好為使用者上傳和操作內容的圖片使用單獨的目錄。理想情況下,您應該為網站使用的圖片設置一個目錄,
並為上傳的圖片設置另一個目錄。

*/

$dir_name = "FooBar"; // 輸入包含圖片的目錄名稱
$olddir = getcwd(); // 取得目前的 Windows 目錄,以便在腳本結尾時切換回來
$dir = opendir($dir_name); //建立目錄控制代碼
//刪除圖片
if(isset($_GET['delpic'])){
chdir('images');
$delpic = $_GET['delpic'];
@
unlink($delpic);
chdir($olddir);
}
//調整圖片大小
if(isset($_GET['resize'])){
//$_GET['resize'] 包含調整大小的百分比(例如,80 和 40 分別表示 80% 和 40%。要將圖像大小加倍,使用者輸入 200 等)。
// 檔案和新大小
$percent = ($_GET['resize']/100);
chdir('images');// 將 Windows 目錄變更為圖片目錄
$filename = $_GET['resizepic'];

// 決定內容類型,注意:此程式碼僅針對 .gif 和 .jpg 執行。
// 如果您想要 .gif 和 .jpg 以外的其他格式,請在此處以相同的方式新增您的程式碼:
$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!=''){ //這是實際調整大小過程開始的地方...
// 取得新大小
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// 載入圖片
switch($format){
case
'image/jpeg':
$source = imagecreatefromjpeg($filename);
break;
case
'image/gif';
$source = imagecreatefromgif($filename);
break;
}
//取得圖片
$thumb = imagecreatetruecolor($newwidth,$newheight);
//必須將此設定為 false,才能使用透明像素覆寫背景中的黑色像素。否則,新像素只會應用在黑色背景之上。
imagealphablending($thumb, false);
//建立臨時檔案控制代碼
$source = @imagecreatefromjpeg($filename);
// 調整大小
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//將圖像寫入目標檔案
@imagejpeg($thumb, $filename);
//切換回舊目錄...我不確定這是否必要
chdir($olddir);
//指定使用者在操作後要前往的位置:
header('Location: foobar.php');
}
}


?>
1
來自 quidware 的 david
15 年前
如果腳本應該調整大小並儲存縮圖,我會使用這個簡單的程式碼,我從上一個程式碼中做了一些更正,並加入了調整為最大高度的可能性

<?php
/**
* 從 JPEG、PNG、GIF 來源檔案產生縮圖
*
* $tmpname = $_FILES['source']['tmp_name'];
* $size - 最大寬度尺寸
* $save_dir - 目的地資料夾
* $save_name - 縮圖新名稱
* $maxisheight - 是否最大寬度 (若否則為最大高度)
*
* 作者:David Taubmann http://www.quidware.com (從 LEDok 修改 - http://www.citadelavto.ru/)
*/

/*/ // 現在是如何快速使用此函數的方法:
if ($_POST[pic])
{
$tmpname = $_FILES['pic']['tmp_name'];
@img_resize( $tmpname , 600 , "../album" , "album_".$id.".jpg");
@img_resize( $tmpname , 120 , "../album" , "album_".$id."_small.jpg");
@img_resize( $tmpname , 60 , "../album" , "album_".$id."_maxheight.jpg", 1);
}
else
echo "No Images uploaded via POST";
/**/

function img_resize( $tmpname, $size, $save_dir, $save_name, $maxisheight = 0 )
{
$save_dir .= ( substr($save_dir,-1) != "/") ? "/" : "";
$gis = getimagesize($tmpname);
$type = $gis[2];
switch(
$type)
{
case
"1": $imorig = imagecreatefromgif($tmpname); break;
case
"2": $imorig = imagecreatefromjpeg($tmpname);break;
case
"3": $imorig = imagecreatefrompng($tmpname); break;
default:
$imorig = imagecreatefromjpeg($tmpname);
}

$x = imagesx($imorig);
$y = imagesy($imorig);

$woh = (!$maxisheight)? $gis[0] : $gis[1] ;

if(
$woh <= $size)
{
$aw = $x;
$ah = $y;
}
else
{
if(!
$maxisheight){
$aw = $size;
$ah = $size * $y / $x;
} else {
$aw = $size * $x / $y;
$ah = $size;
}
}
$im = imagecreatetruecolor($aw,$ah);
if (
imagecopyresampled($im,$imorig , 0,0,0,0,$aw,$ah,$x,$y))
if (
imagejpeg($im, $save_dir.$save_name))
return
true;
else
return
false;
}
?>
1
haker4o at haker4o dot org
19 年前
<?php
// 調整圖片大小。
// 作者:Smelban & Haker4o
// 電子郵件 smelban@smwebdesigns.com & Haker4o@Haker4o.org
// 此程式碼僅適用於 jpg、gif、png 格式的圖片
// $picname = resizepics('pics', 'new widthmax', 'new heightmax');
// 範例 $picname = resizepics('stihche.jpg', '180', '140');
$picname = resizepics('圖片名稱.格式', '180', '140');
echo
$pickname;
//錯誤
die( "<font color=\"#FF0066\"><center><b>檔案不存在 :(<b></center></FONT>");
// resizepics 函式
function resizepics($pics, $newwidth, $newheight){
if(
preg_match("/.jpg/i", "$pics")){
header('Content-type: image/jpeg');
}
if (
preg_match("/.gif/i", "$pics")){
header('Content-type: image/gif');
}
list(
$width, $height) = getimagesize($pics);
if(
$width > $height && $newheight < $height){
$newheight = $height / ($width / $newwidth);
} else if (
$width < $height && $newwidth < $width) {
$newwidth = $width / ($height / $newheight);
} else {
$newwidth = $width;
$newheight = $height;
}
if(
preg_match("/.jpg/i", "$pics")){
$source = imagecreatefromjpeg($pics);
}
if(
preg_match("/.jpeg/i", "$pics")){
$source = imagecreatefromjpeg($pics);
}
if(
preg_match("/.jpeg/i", "$pics")){
$source = Imagecreatefromjpeg($pics);
}
if(
preg_match("/.png/i", "$pics")){
$source = imagecreatefrompng($pics);
}
if(
preg_match("/.gif/i", "$pics")){
$source = imagecreatefromgif($pics);
}
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return
imagejpeg($thumb);
if(
preg_match("/.jpg/i", "$pics")){
return
imagejpeg($thumb);
}
if(
preg_match("/.jpeg/i", "$pics")){
return
imagejpeg($thumb);
}
if(
preg_match("/.jpeg/i", "$pics")){
return
imagejpeg($thumb);
}
if(
preg_match("/.png/i", "$pics")){
return
imagepng($thumb);
}
if(
preg_match("/.gif/i", "$pics")){
return
imagegif($thumb);
}
}
?>
1
del at kartoon dot net
19 年前
這段程式碼可以讓你從大型圖片的中心抓取縮圖。這被用於客戶的美術藝廊,以提供即將出現的圖片的預覽(僅一小部分)。你可以動態地調整這個值。我也加入了一個縮放因子,如果你想在裁剪之前先縮小圖片的話。

<?php
// 檔案
$filename = 'moon.jpg';
$percent = 1.0; // 如果你想先縮小圖片
$imagethumbsize = 200; // 縮圖大小(圖片中心裁剪的區域)
// 內容類型
header('Content-type: image/jpeg');

// 取得新的尺寸
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// 重新取樣
$image_p = imagecreatetruecolor($imagethumbsize , $imagethumbsize); // 真彩色,以獲得最佳品質
$image = imagecreatefromjpeg($filename);

// 基本上將此行放入你的版本中,使用 -($new_width/2) + ($imagethumbsize/2) 和 -($new_height/2) + ($imagethumbsize/2) 作為
// imagecopyresampled 的第三和第四個位置
// -($new_width/2) + ($imagethumbsize/2)
// 和
// -($new_height/2) + ($imagethumbsize/2)
// 是關鍵
imagecopyresampled($image_p, $image, -($new_width/2) + ($imagethumbsize/2), -($new_height/2) + ($imagethumbsize/2), 0, 0, $new_width , $new_width , $width, $height);

// 輸出

imagejpeg($image_p, null, 100);
?>
1
eslindsey at gmail dot com
7 年前
我不確定為什麼 nworld3d at yahoo dot com 的 https://php.dev.org.tw/manual/en/function.imagecopyresized.php#69123 被投了反對票--它正是我要用於合成數個 alpha 通道圖片的東西,就像 Photoshop 一樣。我需要從透明度開始,然後將幾個 alpha 圖片一個接一個地疊加在它上面。在擺弄了內建的 PHP 函式之後,我擔心我需要作弊,移除所有 alpha 通道,然後最後使用透明顏色,但這樣做會因為我將它放在哪個背景之上而看起來不同。nworld3d at yahoo dot 的評論讓我免於走那條路,我給他 +1。
0
kvslaap
15 年前
這是一個腳本,它會遍歷目前設定為 "files" 的目錄,並在尊重圖片比例的情況下調整所有圖片的大小。

<?php
//如果因為使用過多記憶體而出現錯誤訊息,請使用此行 (移除 '//')
//ini_set ( "memory_limit", "48M");

$target_width = 800;
$target_height = 600;

if (
ob_get_level() == 0) ob_start();
if (
$handle = opendir('files/')) {
while (
false !== ($file = readdir($handle))) {
if (
$file != "." && $file != "..") {
$destination_path = './files/';
$target_path = $destination_path . basename($file);

$extension = pathinfo($target_path);
$allowed_ext = "jpg, gif, png, bmp, jpeg, JPG";
$extension = $extension[extension];
$allowed_paths = explode(", ", $allowed_ext);
$ok = 0;
for(
$i = 0; $i < count($allowed_paths); $i++) {
if (
$allowed_paths[$i] == "$extension") {
$ok = "1";
}
}

if (
$ok == "1") {

if(
$extension == "jpg" || $extension == "jpeg" || $extension == "JPG"){
$tmp_image=imagecreatefromjpeg($target_path);
}

if(
$extension == "png") {
$tmp_image=imagecreatefrompng($target_path);
}

if(
$extension == "gif") {
$tmp_image=imagecreatefromgif($target_path);
}

$width = imagesx($tmp_image);
$height = imagesy($tmp_image);

//計算圖片長寬比
$imgratio = ($width / $height);

if (
$imgratio>1) {
$new_width = $target_width;
$new_height = ($target_width / $imgratio);
} else {
$new_height = $target_height;
$new_width = ($target_height * $imgratio);
}

$new_image = imagecreatetruecolor($new_width,$new_height);
ImageCopyResized($new_image, $tmp_image,0,0,0,0, $new_width, $new_height, $width, $height);
//取得新的圖片
imagejpeg($new_image, $target_path);
$image_buffer = ob_get_contents();
ImageDestroy($new_image);
ImageDestroy($tmp_image);
echo
" $file 調整大小為 $new_width x $new_height <br> \n";
echo
str_pad('',4096)."\n";
ob_flush();
flush();
}
}
}
closedir($handle);
echo
"完成。";
ob_end_flush();
}
?>
0
it at chmzap dot ru
16 年前
如果腳本需要調整圖片大小並儲存縮圖,我會使用這個簡單的程式碼。

<?php
/**
* 從 JPEG、PNG、GIF 來源檔案製作縮圖
*
* $tmpname = $_FILES['source']['tmp_name'];
* $size - 最大寬度尺寸
* $save_dir - 目的地資料夾
* $save_name - 縮圖新名稱
*
* 作者:LEDok - http://www.citadelavto.ru/
*/

function img_resize( $tmpname, $size, $save_dir, $save_name )
{
$save_dir .= ( substr($save_dir,-1) != "/") ? "/" : "";
$gis = GetImageSize($tmpname);
$type = $gis[2];
switch(
$type)
{
case
"1": $imorig = imagecreatefromgif($tmpname); break;
case
"2": $imorig = imagecreatefromjpeg($tmpname);break;
case
"3": $imorig = imagecreatefrompng($tmpname); break;
default:
$imorig = imagecreatefromjpeg($tmpname);
}

$x = imageSX($imorig);
$y = imageSY($imorig);
if(
$gis[0] <= $size)
{
$av = $x;
$ah = $y;
}
else
{
$yc = $y*1.3333333;
$d = $x>$yc?$x:$yc;
$c = $d>$size ? $size/$d : $size;
$av = $x*$c; //原始圖片高度
$ah = $y*$c; //原始圖片長度
}
$im = imagecreate($av, $ah);
$im = imagecreatetruecolor($av,$ah);
if (
imagecopyresampled($im,$imorig , 0,0,0,0,$av,$ah,$x,$y))
if (
imagejpeg($im, $save_dir.$save_name))
return
true;
else
return
false;
}

?>

現在如何快速使用此函式

<?php
if ($_POST[pic])
{
$tmpname = $_FILES['pic']['tmp_name'];
@
img_resize( $tmpname , 600 , "../album" , "album_".$id.".jpg");
@
img_resize( $tmpname , 120 , "../album" , "album_".$id."_small.jpg");
@
img_resize( $tmpname , 60 , "../album" , "album_".$id."verysmall.jpg");
}
else
echo
"沒有透過 POST 上傳圖片";
?>
0
andrvm at andrvm dot ru
17 年前
另一個設定圖片記憶體的版本 (請見下方)

<?php

function setMemoryForImage($filename)
{
$imageInfo = getimagesize($filename);
$memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);

$memoryLimit = (int) ini_get('memory_limit')*1048576;

if ((
memory_get_usage() + $memoryNeeded) > $memoryLimit)
{
ini_set('memory_limit', ceil((memory_get_usage() + $memoryNeeded + $memoryLimit)/1048576).'M');
return (
true);
}
else return(
false);
}

?>
//它能運作。沒有問題!
0
feip at feip dot net
18 年前
這段程式碼將圖片轉換為縮圖。
它的運作方式 -
檢查來源圖片 - 寬度和高度,
從原始圖片裁切最大範圍,
將裁切後的圖片調整為使用者定義的大小

// makeIcons_MergeCenter($src, $dst, $dstx, $dsty);

<?php

function makeIcons_MergeCenter($src, $dst, $dstx, $dsty){

//$src = 原始圖片路徑
//$dst = 目的圖片路徑
//$dstx = 使用者定義的圖片寬度
//$dsty = 使用者定義的圖片高度

$allowedExtensions = 'jpg jpeg gif png';

$name = explode(".", $src);
$currentExtensions = $name[count($name)-1];
$extensions = explode(" ", $allowedExtensions);

for(
$i=0; count($extensions)>$i; $i=$i+1){
if(
$extensions[$i]==$currentExtensions)
{
$extensionOK=1;
$fileExtension=$extensions[$i];
break; }
}

if(
$extensionOK){

$size = getImageSize($src);
$width = $size[0];
$height = $size[1];

if(
$width >= $dstx AND $height >= $dsty){

$proportion_X = $width / $dstx;
$proportion_Y = $height / $dsty;

if(
$proportion_X > $proportion_Y ){
$proportion = $proportion_Y;
}else{
$proportion = $proportion_X ;
}
$target['width'] = $dstx * $proportion;
$target['height'] = $dsty * $proportion;

$original['diagonal_center'] =
round(sqrt(($width*$width)+($height*$height))/2);
$target['diagonal_center'] =
round(sqrt(($target['width']*$target['width'])+
(
$target['height']*$target['height']))/2);

$crop = round($original['diagonal_center'] - $target['diagonal_center']);

if(
$proportion_X < $proportion_Y ){
$target['x'] = 0;
$target['y'] = round((($height/2)*$crop)/$target['diagonal_center']);
}else{
$target['x'] = round((($width/2)*$crop)/$target['diagonal_center']);
$target['y'] = 0;
}

if(
$fileExtension == "jpg" OR $fileExtension=='jpeg'){
$from = ImageCreateFromJpeg($src);
}elseif (
$fileExtension == "gif"){
$from = ImageCreateFromGIF($src);
}elseif (
$fileExtension == 'png'){
$from = imageCreateFromPNG($src);
}

$new = ImageCreateTrueColor ($dstx,$dsty);

imagecopyresampled ($new, $from, 0, 0, $target['x'],
$target['y'], $dstx, $dsty, $target['width'], $target['height']);

if(
$fileExtension == "jpg" OR $fileExtension == 'jpeg'){
imagejpeg($new, $dst, 70);
}elseif (
$fileExtension == "gif"){
imagegif($new, $dst);
}elseif (
$fileExtension == 'png'){
imagepng($new, $dst);
}
}
}
}

?>
0
kyle dot florence at gmail dot com
18 年前
以下函式會根據最大寬度和高度調整圖片大小,然後從調整大小後的圖片中心建立指定寬度和高度的縮圖。此函式不會將圖片調整為最大寬度像素乘以最大高度像素,這些只是圖片可接受的最大寬度和高度,它會將圖片調整為小於最大寬度和最大高度的第一個 1:1 比例。

例如,如果您有一張 800x600 的圖片,並且您指定新圖片為 400x200,它會根據最小的數字(在此範例中為 200)調整大小,並保持圖片的 1:1 比例。因此,您的最終圖片將會變成類似 262x200 的大小。

更新:我已更新此函式,我加入了 'newdir' 選項,以防您希望圖片儲存在與腳本不同的目錄中。我也修正了縮圖切片的錯誤,使其現在完全位於中心,並修正了 'ob at babcom dot biz' 提到的錯誤,因此您現在可以安全地根據寬度或高度調整大小。

<?
/**********************************************************
* function resizejpeg
*
* = 建立基於最大寬度的調整大小圖片
* 指定,並從
* 從圖片中間切割的矩形產生縮圖。
*
* @dir = 圖片儲存的目錄
* @newdir = 新圖片將儲存的目錄
* @img = 圖片名稱
* @max_w = 調整大小後圖片的最大寬度
* @max_h = 調整大小後圖片的最大高度
* @th_w = 縮圖的寬度
* @th_h = 縮圖的高度
*
**********************************************************/

function resizejpeg($dir, $newdir, $img, $max_w, $max_h, $th_w, $th_h)
{
// 設定目標目錄
if (!$newdir) $newdir = $dir;

// 取得原始圖片的寬度和高度
list($or_w, $or_h, $or_t) = getimagesize($dir.$img);

// 確保圖片是 jpeg 格式
if ($or_t == 2) {

// 取得圖片的比例
$ratio = ($or_h / $or_w);

// 原始圖片
$or_image = imagecreatefromjpeg($dir.$img);

// 調整圖片大小?
if ($or_w > $max_w || $or_h > $max_h) {

// 先依高度調整大小,然後依寬度調整大小(高度優先)
if ($max_h < $max_w) {
$rs_h = $max_h;
$rs_w = $rs_h / $ratio;
}
// 先依寬度調整大小,然後依高度調整大小(寬度優先)
else {
$rs_w = $max_w;
$rs_h = $ratio * $rs_w;
}

// 將舊圖片複製到新圖片
$rs_image = imagecreatetruecolor($rs_w, $rs_h);
imagecopyresampled($rs_image, $or_image, 0, 0, 0, 0, $rs_w, $rs_h, $or_w, $or_h);
}
// 圖片不需要調整大小
else {
$rs_w = $or_w;
$rs_h = $or_h;

$rs_image = $or_image;
}

// 產生調整大小後的圖片
imagejpeg($rs_image, $newdir.$img, 100);

$th_image = imagecreatetruecolor($th_w, $th_h);

// 從調整大小後的圖片中裁切一個矩形並儲存為縮圖
$new_w = (($rs_w / 2) - ($th_w / 2));
$new_h = (($rs_h / 2) - ($th_h / 2));

imagecopyresized($th_image, $rs_image, 0, 0, $new_w, $new_h, $rs_w, $rs_h, $rs_w, $rs_h);

// 產生縮圖
imagejpeg($th_image, $newdir.'thumb_'.$img, 100);

return true;
}

// 圖片類型不是 jpeg!
else {
return false;
}
}
?>

範例

<?php
$dir
= './';
$img = 'test.jpg';

resizejpeg($dir, '', $img, 600, 400, 300, 150);
?>

此範例會將圖片 'test.jpg' 調整大小為 600x400 或更小 (保持圖片的 1:1 比例),並建立一個 300x150 的檔案 'thumb_test.jpg'。
0
kyle(dot)florence(_[at]_)gmail(dot)com
18 年前
以下函式會根據最大寬度和高度調整圖片大小,然後從調整大小後的圖片中心建立指定寬度和高度的縮圖。

<?php
/**********************************************************
* function resizejpeg:
*
* = 根據指定的最大寬度建立調整大小後的圖片,
* 以及從圖片中間裁切一個矩形來產生縮圖。
*
* @dir = 圖片儲存的目錄
* @img = 圖片名稱
* @max_w = 調整大小後圖片的最大寬度
* @max_h = 調整大小後圖片的最大高度
* @th_w = 縮圖的寬度
* @th_h = 縮圖的高度
*
**********************************************************/

function resizejpeg($dir, $img, $max_w, $max_h, $th_w, $th_h)
{
// 取得原始圖片的寬度和高度
list($or_w, $or_h, $or_t) = getimagesize($dir.$img);

// 確保圖片是 jpeg 格式
if ($or_t == 2) {

// 取得圖片的比例
$ratio = ($or_h / $or_w);

// 原始圖片
$or_image = imagecreatefromjpeg($dir.$img);

// 調整圖片大小
if ($or_w > $max_w || $or_h > $max_h) {

// 先依寬度調整大小 (小於 $max_w)
if ($or_w > $max_w) {
$rs_w = $max_w;
$rs_h = $ratio * $max_h;
} else {
$rs_w = $or_w;
$rs_h = $or_h;
}

// 再依高度調整大小 (小於 $max_h)
if ($rs_h > $max_h) {
$rs_w = $max_w / $ratio;
$rs_h = $max_h;
}

// 將舊圖片複製到新圖片
$rs_image = imagecreatetruecolor($rs_w, $rs_h);
imagecopyresampled($rs_image, $or_image, 0, 0, 0, 0, $rs_w, $rs_h, $or_w, $or_h);
} else {
$rs_w = $or_w;
$rs_h = $or_h;

$rs_image = $or_image;
}

// 產生調整大小後的圖片
imagejpeg($rs_image, $dir.$img, 100);

$th_image = imagecreatetruecolor($th_w, $th_h);

// 從調整大小後的圖片中裁切一個矩形並儲存為縮圖
$new_w = (($rs_w / 4));
$new_h = (($rs_h / 4));

imagecopyresized($th_image, $rs_image, 0, 0, $new_w, $new_h, $rs_w, $rs_h, $rs_w, $rs_h);

// 產生縮圖
imagejpeg($th_image, $dir.'thumb_'.$img, 100);

return
true;
}

// 圖片類型不是 jpeg!
else {
return
false;
}
}
?>

範例

<?php
$dir
= './';
$img = 'test.jpg';

resizejpeg($dir, $img, 600, 600, 300, 150);
?>

此範例會將圖片 'test.jpg' 調整大小為 600x600 或更小 (1:1 比例),並建立一個 300x150 的檔案 'thumb_test.jpg'。
0
06madsenl at westseneca dot wnyric dot org
18 年前
我這幾天一直試著弄清楚如何在我的網站上調整原始圖片的大小,但是這個網站

http://www.sitepoint.com/article/image-resizing-php

有一個很棒的教學,教你如何使用 PHP 調整圖片大小而不產生縮圖。這正是我想要做的。
0
konteineris at yahoo dot com
18 年前
函式會從來源圖片建立縮圖,調整大小使其符合所需的縮圖寬度和高度,或者填滿它並抓取最大圖片部分並調整大小,最後將其寫入目的地

<?

function thumb($filename, $destination, $th_width, $th_height, $forcefill)
{
list($width, $height) = getimagesize($filename);

$source = imagecreatefromjpeg($filename);

if($width > $th_width || $height > $th_height){
$a = $th_width/$th_height;
$b = $width/$height;

if(($a > $b)^$forcefill)
{
$src_rect_width = $a * $height;
$src_rect_height = $height;
if(!$forcefill)
{
$src_rect_width = $width;
$th_width = $th_height/$height*$width;
}
}
else
{
$src_rect_height = $width/$a;
$src_rect_width = $width;
if(!$forcefill)
{
$src_rect_height = $height;
$th_height = $th_width/$width*$height;
}
}

$src_rect_xoffset = ($width - $src_rect_width)/2*intval($forcefill);
$src_rect_yoffset = ($height - $src_rect_height)/2*intval($forcefill);

$thumb = imagecreatetruecolor($th_width, $th_height);
imagecopyresized($thumb, $source, 0, 0, $src_rect_xoffset, $src_rect_yoffset, $th_width, $th_height, $src_rect_width, $src_rect_height);

imagejpeg($thumb,$destination);
}
}

?>
0
backglancer at hotmail
19 年前
很棒的腳本,可以建立一個不超過 150 (或使用者指定) 高度和寬度的縮圖。

<?PHP
$picture
="" # 圖片檔案名稱,這裡不是路徑
$max=150; # 圖片單邊最大尺寸
/*
這裡您可以插入任何特定的 "if-else" 或 "switch" 類型的偵測器,來判斷圖片的類型。
在這個範例中,我將使用標準的 JPG 格式。
*/

$src_img=ImagecreateFromJpeg($picture);

$oh = imagesy($src_img); # 原始高度
$ow = imagesx($src_img); # 原始寬度

$new_h = $oh;
$new_w = $ow;

if(
$oh > $max || $ow > $max){
$r = $oh/$ow;
$new_h = ($oh > $ow) ? $max : $max*$r;
$new_w = $new_h/$r;
}
// 注意 TrueColor 使用 256 色,而不是 8 色
$dst_img = ImageCreateTrueColor($new_w,$new_h);

ImageCopyResized($dst_img, $src_img, 0,0,0,0, $new_w, $new_h, ImageSX($src_img), ImageSY($src_img));

ImageJpeg($dst_img, "th_$picture");

?>
-1
jack at computerrageprevention dot ca
11 年前
這裡有很多使用者筆記在處理縮圖的建立,但我寫了一個函式,可以在圖片上傳時建立縮圖。它只是檔案上傳器和縮圖產生器的組合,但現在使用起來非常簡單。

以下是一個 index.php 檔案,其中包含上傳表單、函式以及如何使用該函式的範例。'thumb' 函式中的最後兩個值是結果縮圖的寬度和高度限制。無論原始圖片的大小如何,縮圖始終會符合指定的尺寸。

<?php

if ($_POST[formname] =="upload")
{
if (
$_FILES)
{
foreach (
$_FILES as $key => $value)
{
$m = thumb($value, realpath(dirname(__FILE__)) . "/" . "image_1", realpath(dirname(__FILE__)) . "/" . "thumb_1", 150, 150);

// 顯示任何訊息,無論成功或失敗
if ($m) { foreach($m as $text) { print "$text<br>"; } }
}
}
}

function
thumb($file, $bigname, $thumbname, $maxwidth, $maxheight)
{
if (
is_uploaded_file($file[tmp_name]))
{
// 判斷圖片類型
if ($file[type] == "image/jpeg") { $ext = ".jpg"; }
if (
$file[type] == "image/png") { $ext = ".png"; }
if (
$file[type] == "image/gif") { $ext = ".gif"; }

$newfile = $bigname . $ext;

if (
move_uploaded_file($file[tmp_name], $newfile))
{
$message[] = "上傳完成";

// 取得舊圖片大小並轉換為最大寬度/高度組合
$size = getimagesize($newfile);

// 只有在寬度大於零時才進行轉換,否則可能會出現除以零的錯誤
if ($size[1] != 0)
{

// 根據允許的最大尺寸和原始尺寸計算縮圖的寬度和高度
if ($size[0]/$size[1] > $maxwidth/$maxheight)
{
$newwidth = $maxwidth; $newheight = floor(($size[1] * $maxwidth) / $size[0]); }
else
{
$newheight = $maxheight; $newwidth = ceil(($size[0] * $maxheight) / $size[1]); }

// 建立縮圖
$i = imagecreate($newwidth, $newheight);

if (
$ext == ".jpg") { $j = imagecreatefromjpeg($newfile); }
if (
$ext == ".png") { $j = imagecreatefrompng($newfile); }
if (
$ext == ".gif") { $j = imagecreatefromgif($newfile); }

if (
$j)
{
// 複製原始圖片並貼到調整大小的新圖片中
if (imagecopyresized($i, $j, 0, 0, 0, 0, $newwidth, $newheight, $size[0], $size[1]))
{
if (
imagejpeg($i, $thumbname . $ext, 100))
{
$message[] = "圖片縮圖建立成功";
} else {
$message[] = "圖片縮圖無法匯出";
}
} else {
$message[] = "圖片調整大小失敗";
}
} else {
$message[] = "圖片類型無法辨識";
}
} else {
// size[1] != 0
$message[] = "圖片大小無效";
}
}
// move_uploaded_file
} // is_uploaded_file

return $message;
}

print
"
<html>
<head>
<title>圖片上傳和建立縮圖</title>
</head>

<body>

<form action='index.php' method='POST' enctype='multipart/form-data'>
<input type='hidden' name='formname' value='upload'>
<input type='file' name='fileupload'>
<input type='submit' value='上傳'>
</form>

</body>
</html>
"
;

?>

注意:這不處理調整調色盤或透明顏色,但如果您需要,可以添加這些功能。
-1
nworld3d at yahoo dot com
18 年前
以下程式碼片段可讓您調整透明 PNG 的大小,並將其合成到另一個圖片中。該程式碼經過測試,可在 PHP5.1.2、GD2 上運作,但我認為它也可以與其他版本的 PHP 和 GD 搭配使用。

這段程式碼已加上註解,方便您閱讀。調整透明 PNG 圖片大小的概念是建立一個完全透明的新目標圖片,然後關閉此新圖片的影像 Alpha 混合,以便在複製 PNG 來源檔案時,其 Alpha 通道仍然保留。

<?php
/**
* 將 PNG 檔案合成到來源檔案上。
* 如果定義了新的寬度/高度,則調整 PNG 大小 (並保留所有透明度資訊)
* 作者:Alex Le - http://www.alexle.net
*/
function imageComposeAlpha( &$src, &$ovr, $ovr_x, $ovr_y, $ovr_w = false, $ovr_h = false)
{
if(
$ovr_w && $ovr_h )
$ovr = imageResizeAlpha( $ovr, $ovr_w, $ovr_h );

/* 現在合成這兩張圖片 */
imagecopy($src, $ovr, $ovr_x, $ovr_y, 0, 0, imagesx($ovr), imagesy($ovr) );
}

/**
* 調整具有透明度的 PNG 檔案大小為給定的尺寸
* 並仍然保留 Alpha 通道資訊
* 作者:Alex Le - http://www.alexle.net
*/
function imageResizeAlpha(&$src, $w, $h)
{
/* 建立一個具有新寬度和高度的新圖片 */
$temp = imagecreatetruecolor($w, $h);

/* 使新圖片透明 */
$background = imagecolorallocate($temp, 0, 0, 0);
ImageColorTransparent($temp, $background); // 使新的臨時圖片完全透明
imagealphablending($temp, false); // 關閉 Alpha 混合以保留 Alpha 通道

/* 調整 PNG 檔案大小 */
/* 使用 imagecopyresized 以獲得一些效能,但會損失一些品質 */
imagecopyresized($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
/* 如果您更關心品質,請使用 imagecopyresampled */
//imagecopyresampled($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
return $temp;
}
?>
使用範例

<?php
header
('Content-type: image/png');

/* 開啟照片和覆蓋圖片 */
$photoImage = ImageCreateFromJPEG('images/MiuMiu.jpg');
$overlay = ImageCreateFromPNG('images/hair-trans.png');

$percent = 0.8;
$newW = ceil(imagesx($overlay) * $percent);
$newH = ceil(imagesy($overlay) * $percent);

/* 將覆蓋照片合成到目標圖片上 */
imageComposeAlpha( $photoImage, $overlay, 86, 15, $newW, $newH );

/* 開啟另一個 PNG 檔案,然後調整大小並合成它 */
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 10, 20, imagesx($watermark)/2, imagesy($watermark)/2 );

/**
* 開啟相同的 PNG 檔案,然後在不調整大小的情況下合成
* 由於原始的 $watermark 是以參考傳遞,它已經被調整大小了。
* 所以我們必須重新開啟它。
*/
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 80, 350);
Imagepng($photoImage); // 輸出到瀏覽器

ImageDestroy($photoImage);
ImageDestroy($overlay);
ImageDestroy($watermark);
?>
-1
licson0729 at gmail dot com
13 年前
我找不到任何可以調整圖片大小並為其加上邊框的腳本。所以我自己做了一個。希望對您有所幫助。

<?php
function imagecopyresizedwithborder(&$src,$width,$height,$borderthickess,$bordercolor=NULL)
{
list(
$width_orig, $height_orig) = array(imagesx($src),imagesy($src));

if (
$width && ($width_orig < $height_orig))
{
$width = ($height / $height_orig) * $width_orig;
}
else
{
$height = ($width / $width_orig) * $height_orig;
}

$dst = imagecreatetruecolor($width+2*$borderthickess,$height+2*$borderthickess);
imagecolortransparent($dst,imagecolorallocate($dst,0,0,0));
imagealphablending($dst,false);
imagesavealpha($dst,true);
imagefill($dst,0,0,(isset($bordercolor) ? $bordercolor : imagecolorallocate($dst,255,255,255)));
imagecopyresampled($dst,$src,$borderthickess,$borderthickess,0,0,$width,$height,imagesx($src),imagesy($src));
return
$dst;
}

?>
-1
ob at babcom dot biz
18 年前
關於 2006 年 8 月 3 日 kyle.florence 的註解和函數

我嘗試使用他的 resizejpeg() 函數來調整我的圖庫中的圖片大小。據我所知,它包含一個小錯誤。

只要我指定相同的最大寬度和最大高度,調整大小就可以正常運作。想要所有縮圖都具有相同的高度 - 這樣我的圖片在我的網站上無論是直向或橫向格式都會呈現一直線 - 我很快就遇到了問題,使用不同的最大寬度和最大高度值調整大小將無法正常運作。

如果您正在使用該腳本,請變更計算調整大小的寬度和調整大小的高度的以下 2 行

<?php
$rs_h
= $ratio * $max_h;
?>
應該是
<?php
$rs_h
= $ratio * $rs_w;
?>


<?php
$rs_w
= $max_w / $ratio;
?>
應該是
<?php
$rs_w
= $rs_h / $ratio;
?>

以下函式基於 Kyle Florence 的函式修改。我省略了縮圖部分,而是增加了為圖像定義新目錄和新檔名的可能性。如果您需要調整大小然後建立縮圖,只需執行兩次此函式即可。這裡,縮圖將包含完整圖片,而不是原始圖像的剪裁。

此函式支援 JPG、GIF 和 PNG 的調整大小。JPG 的品質作為最後一個參數 $Quality 傳遞給函式。

變數名稱應該能表達它們的用途。

<?php
function Resize($Dir,$Image,$NewDir,$NewImage,$MaxWidth,$MaxHeight,$Quality) {
list(
$ImageWidth,$ImageHeight,$TypeCode)=getimagesize($Dir.$Image);
$ImageType=($TypeCode==1?"gif":($TypeCode==2?"jpeg":
(
$TypeCode==3?"png":FALSE)));
$CreateFunction="imagecreatefrom".$ImageType;
$OutputFunction="image".$ImageType;
if (
$ImageType) {
$Ratio=($ImageHeight/$ImageWidth);
$ImageSource=$CreateFunction($Dir.$Image);
if (
$ImageWidth > $MaxWidth || $ImageHeight > $MaxHeight) {
if (
$ImageWidth > $MaxWidth) {
$ResizedWidth=$MaxWidth;
$ResizedHeight=$ResizedWidth*$Ratio;
}
else {
$ResizedWidth=$ImageWidth;
$ResizedHeight=$ImageHeight;
}
if (
$ResizedHeight > $MaxHeight) {
$ResizedHeight=$MaxHeight;
$ResizedWidth=$ResizedHeight/$Ratio;
}
$ResizedImage=imagecreatetruecolor($ResizedWidth,$ResizedHeight);
imagecopyresampled($ResizedImage,$ImageSource,0,0,0,0,$ResizedWidth,
$ResizedHeight,$ImageWidth,$ImageHeight);
}
else {
$ResizedWidth=$ImageWidth;
$ResizedHeight=$ImageHeight;
$ResizedImage=$ImageSource;
}
$OutputFunction($ResizedImage,$NewDir.$NewImage,$Quality);
return
true;
}
else
return
false;
}
?>

在呼叫函式之前,應該檢查是否支援 JPG、PNG 或 GIF。
-1
marcy DOT xxx (AT) gmail.com
19 年前
此範例允許使用任何類型的圖片,並使用 ImageCopyResized() 調整圖片大小,同時保持比例。

<?php
// 切換以找到正確的函式類型

$imgfile = 'namefile.jpg';
Header("Content-type: image/".$_GET["type"]);

switch(
$_GET["type"]){
default:
$function_image_create = "ImageCreateFromJpeg";
$function_image_new = "ImageJpeg";
break;
case
"jpg":
$function_image_create = "ImageCreateFromJpeg";
$function_image_new = "ImageJpeg";
case
"jpeg":
$function_image_create = "ImageCreateFromJpeg";
$function_image_new = "ImageJpeg";
break;
case
"png":
$function_image_create = "ImageCreateFromPng";
$function_image_new = "ImagePNG";
break;
case
"gif":
$function_image_create = "ImageCreateFromGif";
$function_image_new = "ImagePNG";
break;
}

list(
$width, $height) = getimagesize($imgfile);

// 縮圖的新寬度

$newheight = 80;

// 保持比例

$newwidth = (int) (($width*80)/$height);

$thumb = ImageCreateTrueColor($newwidth,$newheight);
$source = @function_image_create($imgfile);

ImageCopyResized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

@
$function_image_new($thumb);
?>
-2
nils dot clark-bernhard at human-aspects dot de
17 年前
關於 ob at babcom dot biz 的函式 Resize($Dir,$Image,$NewDir,$NewImage,$MaxWidth,$MaxHeight,$Quality)

請確保不要在調整 PNG 大小時使用 9 或更高的品質。

PHP 會輸出類似以下的錯誤:
fatal libpng error: zlib failed to initialize compressor
或者
gd-png error: setjmp returns error condition
-1
MaLaZ
19 年前
用於建立縮圖的簡單腳本,包含處理資訊並將原始比例縮圖儲存到新目的地...適合與上傳或已上傳的圖像一起使用

<?php

//上傳------------------------------------
if(isset( $submit ))
{
if (
$_FILES['imagefile']['type'] == "image/jpeg"){
copy ($_FILES['imagefile']['tmp_name'], "../images/".$_FILES['imagefile']['name'])
or die (
"無法複製");
echo
"";
echo
"圖片名稱: ".$_FILES['imagefile']['name']."";
echo
"<br>圖片大小: ".$_FILES['imagefile']['size']."";
echo
"<br>圖片類型: ".$_FILES['imagefile']['type']."";
echo
"<br>圖片複製完成....<br>";
}
else {
echo
"<br><br>";
echo
"錯誤的檔案類型 (".$_FILES['imagefile']['name'].")<br>";exit;
}
//-----上傳結束

//------開始縮圖產生器

$thumbsize=120;
echo
"縮圖資訊: <br>
1.縮圖定義尺寸: - OK:
$thumbsize<br>";
$imgfile = "../images/$imagefile_name";//處理過的圖片
echo "
2.圖片目標位置: - OK:
$imgfile<br>";
header('Content-type: image/jpeg');
list(
$width, $height) = getimagesize($imgfile);
echo
"3.圖片尺寸 - OK: 寬=$width x 高=$height<br>";
$imgratio=$width/$height;
echo
"3.圖片比例 - OK: $imgratio<br>";
if (
$imgratio>1){
$newwidth = $thumbsize;
$newheight = $thumbsize/$imgratio;}
else{
$newheight = $thumbsize;
$newwidth = $thumbsize*$imgratio;}
echo
"4.縮圖新尺寸 -OK: 寬=$newwidth x 高=$newheight<br>";
$thumb = ImageCreateTrueColor($newwidth,$newheight);
echo
"5.TrueColor - OK<br>";
$source = imagecreatefromjpeg($imgfile);
echo
"6.From JPG - OK<br>";
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb,"../images/thumbs/thumb_$imagefile_name",100);echo "7.完成... - OK<br>";
//-----------結束--------------
?>

或者在沒有任何資訊的情況下,僅調整大小

<?php
//------開始縮圖產生器
$thumbsize=120;
$imgfile = "../images/$imagefile_name";
header('Content-type: image/jpeg');
list(
$width, $height) = getimagesize($imgfile);
$imgratio=$width/$height;
if (
$imgratio>1){
$newwidth = $thumbsize;
$newheight = $thumbsize/$imgratio;}
else{
$newheight = $thumbsize;
$newwidth = $thumbsize*$imgratio;}
$thumb = ImageCreateTrueColor($newwidth,$newheight);
$source = imagecreatefromjpeg($imgfile);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb,"../images/thumbs/thumb_$imagefile_name",100);
//-----------結束--------------
?>

希望這對您有所幫助。
-2
brian <dot> tyler <at> gmail <dot> com
19 年前
我昨晚一直嘗試這個函式,都得到不成功的結果,直到我在 imagecopyresampled 頁面上找到 fluffle <<at>> gmail 的這則註解,我做了一些小修改,所以您可以直接複製貼上。

為了澄清,src_w 和 src_h 不一定需要是來源圖片的寬度和高度,因為它們指定從來源圖片裁剪的矩形大小,其左上角位於 (src_x, src_y)。

例如,下面的程式碼將 JPEG 圖片裁剪成正方形,正方形位於原始圖片的中心,然後將其大小調整為 100x100 的縮圖。

function ($image_filename, $thumb_location, $image_thumb_size){
//@$image_filename - 您要取得縮圖的圖片檔名(相對於此函式的位置)
//取得縮圖(相對於此函式的位置)
//函式)。
//@$thumb_location - 儲存縮圖的網址(相對於此
//函式的位置)。
//@$image_thumb_size - 您的縮圖的 x-y 維度
//以像素為單位。

list($ow, $oh) = getimagesize($image_filename);
$image_original = imagecreatefromjpeg($image_filename);
$image_thumb = imagecreatetruecolor($image_thumb_size,$image_thumb_size);
if ($ow > $oh) {
$off_w = ($ow-$oh)/2;
$off_h = 0;
$ow = $oh;
} elseif ($oh > $ow) {
$off_w = 0;
$off_h = ($oh-$ow)/2;
$oh = $ow;
} else {
$off_w = 0;
$off_h = 0;
}
imagecopyresampled($image_thumb, $image_original, 0, 0, $off_w, $off_h, 100, 100, $ow, $oh);

imagejpeg($image_thumb, $thumb_location);
}//結束函式
To Top