(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)
imagecopyresampled — 重采樣拷貝部分圖像并調整大小
$dst_image,$src_image,$dst_x,$dst_y,$src_x,$src_y,$dst_w,$dst_h,$src_w,$src_himagecopyresampled() 將一幅圖像中的一塊正方形區(qū)域拷貝到另一個圖像中,平滑地插入像素值,因此,尤其是,減小了圖像的大小而仍然保持了極大的清晰度。
In other words, imagecopyresampled() will take a
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).
如果源和目標的寬度和高度不同,則會進行相應的圖像收縮和拉伸。坐標指的是左上角。本函數(shù)可用來在同一幅圖內(nèi)部拷貝(如果
dst_image 和 src_image
相同的話)區(qū)域,但如果區(qū)域交迭的話則結果不可預知。
dst_image目標圖象資源。
src_image源圖象資源。
dst_x目標 X 坐標點。
dst_y目標 Y 坐標點。
src_x源的 X 坐標點。
src_y源的 Y 坐標點。
dst_w目標寬度。
dst_h目標高度。
src_w源圖象的寬度。
src_h源圖象的高度。
成功時返回 true, 或者在失敗時返回 false。
示例 #1 簡單的例子
這個例子會將圖像調整為原有尺寸的一半。
<?php
// 這個文件
$filename = 'test.jpg';
$percent = 0.5;
// 內(nèi)容類型
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;
// Content type
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 種顏色,計算新的被重采樣的像素及其顏色時采用了一種近似值。對調色板圖像嘗試分配一個新顏色時,如果失敗我們選擇了計算結果最接近(理論上)的顏色。這并不總是視覺上最接近的顏色。這可能會產(chǎn)生怪異的結果,例如空白(或者視覺上是空白)的圖像。要跳過這個問題,請使用真彩色圖像作為目標圖像,例如用 imagecreatetruecolor() 創(chuàng)建的。
imagecopyresized() - 拷貝部分圖像并調整大小