2012-07-04 39 views
2

我有一些與imagecopyresampled問題,主要是圖像不能正確縮放,並且圖像的位置是錯誤的,並有邊緣周圍的黑色邊框。php imagecopyresampled問題

我有以下瓦爾設立

$tW = $width; // Original width of image 
    $tH = $height; // Orignal height of image 

    $w = postvar; // New width 
    $h = postvar; // New height 
    $x = postvar; // New X pos 
    $y = postvar; // New Y pos 

然後運行以下

$tn = imagecreatetruecolor($w, $h); 
    $image = imagecreatefromjpeg('filepathhere.jpeg'); 
    imagecopyresampled($tn, $image, 0, 0, $x, $y, $w, $h, $tW, $tH); 

如果任何人有任何線索,那將是很大的幫助!謝謝

+0

你究竟想要做什麼,預期的結果是什麼? – jeroen

+1

對不起,根據提供的信息無法判斷。 原始尺寸是什麼? $ tW和$ tH的值是多少?你是否可能重新取樣原始圖像以外的區域? –

+0

這些值會改變裁剪工具提交的內容。因此,每次有人運行該工具時,它們都會有所不同。 $ width和$ height值來自一個列表($ width,$ height)= getimagesize('filepath.jpg'); – user1293351

回答

3

這裏有幾個問題。首先,您不應該使用指定的新高度和寬度創建新圖像,而應根據原始圖像的比例計算它們應該是什麼,否則縮放的圖像將會失真。例如,下面的代碼將創建一個適合的$w x $h指定的矩形適當調整後的圖像:如果你要複製的原始圖像的僅某些部分現在

$tW = $width; //original width 
$tH = $height; //original height 

$w = postvar; 
$h = postvar; 

if($w == 0 || $h == 0) { 
    //error... 
    exit; 
} 

if($tW/$tH > $w/$h) { 
    // specified height is too big for the specified width 
    $h = $w * $tH/$tW; 
} 
elseif($tW/$tH < $w/$h) { 
    // specified width is too big for the specified height 
    $w = $h * $tW/$tH; 
} 

$tn = imagecreatetruecolor($w, $h); //this will create it with black background 
imagefill($tn, 0, 0, imagecolorallocate($tn, 255, 255, 255)); //fill it with white; 

//now you can copy the original image: 
$image = imagecreatefromjpeg('filepathhere.jpeg'); 
//next line will just create a scaled-down image 
imagecopyresampled($tn, $image, 0, 0, 0, 0, $w, $h, $tW, $tH); 

,從座標($x, $y)說右邊的角落,那麼你需要包含到您的計算:

$tW = $width - $x; //original width 
$tH = $height - $y; //original height 

$w = postvar; 
$h = postvar; 

if($w == 0 || $h == 0) { 
    //error... 
    exit; 
} 

if($tW/$tH > $w/$h) { 
    // specified height is too big for the specified width 
    $h = $w * $tH/$tW; 
} 
elseif($tW/$tH < $w/h) { 
    // specified width is too big for the specified height 
    $w = $h * $tW/$tH; 
} 

$tn = imagecreatetruecolor($w, $h); //this will create it with black background 
imagefill($tn, 0, 0, imagecolorallocate($tn, 255, 255, 255)); //fill it with white; 

//now you can copy the original image: 
$image = imagecreatefromjpeg('filepathhere.jpeg'); 
//next line will create a scaled-down portion of the original image from coordinates ($x, $y) to the lower-right corner 
imagecopyresampled($tn, $image, 0, 0, $x, $y, $w, $h, $tW, $tH); 

如果你提供有關你要達到什麼樣的更多的細節,我或許可以進一步幫助。