imagecopyresampled

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagecopyresampled重采樣拷貝部分圖像并調(diào)整大小

說明

imagecopyresampled(
    resource $dst_image,
    resource $src_image,
    int $dst_x,
    int $dst_y,
    int $src_x,
    int $src_y,
    int $dst_w,
    int $dst_h,
    int $src_w,
    int $src_h
): bool

imagecopyresampled() 將一幅圖像中的一塊正方形區(qū)域拷貝到另一個(gè)圖像中,平滑地插入像素值,因此,尤其是,減小了圖像的大小而仍然保持了極大的清晰度。

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).

如果源和目標(biāo)的寬度和高度不同,則會(huì)進(jìn)行相應(yīng)的圖像收縮和拉伸。坐標(biāo)指的是左上角。本函數(shù)可用來在同一幅圖內(nèi)部拷貝(如果 dst_imagesrc_image 相同的話)區(qū)域,但如果區(qū)域交迭的話則結(jié)果不可預(yù)知。

參數(shù)

dst_image

目標(biāo)圖象資源。

src_image

源圖象資源。

dst_x

目標(biāo) X 坐標(biāo)點(diǎn)。

dst_y

目標(biāo) Y 坐標(biāo)點(diǎn)。

src_x

源的 X 坐標(biāo)點(diǎn)。

src_y

源的 Y 坐標(biāo)點(diǎn)。

dst_w

目標(biāo)寬度。

dst_h

目標(biāo)高度。

src_w

源圖象的寬度。

src_h

源圖象的高度。

返回值

成功時(shí)返回 true, 或者在失敗時(shí)返回 false

范例

示例 #1 簡單的例子

這個(gè)例子會(huì)將圖像調(diào)整為原有尺寸的一半。

<?php
// 這個(gè)文件
$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$image0000$new_width$new_height$width$height);

// 輸出
imagejpeg($image_pnull100);
?>

以上例程的輸出類似于:

輸出的例子:簡單的例子

示例 #2 按比例對(duì)圖像重新采樣

這個(gè)例子會(huì)以最大寬度高度為 200 像素顯示一個(gè)圖像。

<?php
// 源文件
$filename 'test.jpg';

// 設(shè)置最大寬高
$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$image0000$width$height$width_orig$height_orig);

// 輸出
imagejpeg($image_pnull100);
?>

以上例程的輸出類似于:

輸出例子:按比例對(duì)圖像重新采樣

注釋

注意:

因?yàn)檎{(diào)色板圖像限制(255+1 種顏色)有個(gè)問題。重采樣或過濾圖像通常需要多于 255 種顏色,計(jì)算新的被重采樣的像素及其顏色時(shí)采用了一種近似值。對(duì)調(diào)色板圖像嘗試分配一個(gè)新顏色時(shí),如果失敗我們選擇了計(jì)算結(jié)果最接近(理論上)的顏色。這并不總是視覺上最接近的顏色。這可能會(huì)產(chǎn)生怪異的結(jié)果,例如空白(或者視覺上是空白)的圖像。要跳過這個(gè)問題,請使用真彩色圖像作為目標(biāo)圖像,例如用 imagecreatetruecolor() 創(chuàng)建的。

參見

imagecopyresized() - 拷貝部分圖像并調(diào)整大小