我想能夠讓用戶上傳圖片。使用GD庫,我將爲圖庫創建/存儲三種不同尺寸的圖像並顯示產品。問題在於縮放上傳不同尺寸圖片的人的尺寸。例如,一張4000 x 3000的圖片可以縮放到我想要的240 x 180,但是我注意到一些用戶有不同尺寸的圖片,不會縮放到這個尺寸,例如3008 x 2000和3837 x 2551.處理上傳不同尺寸的圖片
有人可以請指導我以處理這些不同的圖像尺寸的最佳方式,以便他們可以縮放到一個普通的尺寸。
我想能夠讓用戶上傳圖片。使用GD庫,我將爲圖庫創建/存儲三種不同尺寸的圖像並顯示產品。問題在於縮放上傳不同尺寸圖片的人的尺寸。例如,一張4000 x 3000的圖片可以縮放到我想要的240 x 180,但是我注意到一些用戶有不同尺寸的圖片,不會縮放到這個尺寸,例如3008 x 2000和3837 x 2551.處理上傳不同尺寸的圖片
有人可以請指導我以處理這些不同的圖像尺寸的最佳方式,以便他們可以縮放到一個普通的尺寸。
你必須設置一個最終尺寸,e.g:通過較小的因素300x300的像素
然後,通過原始尺寸劃分兩個因素,e.g
factor1=300/4000 <- Width
factor2=300/3000 <- Heigth
現在你縮放圖像。 您現在應該有一個300像素高度或寬度的圖像。現在你把所有東西都切割得比最終的尺寸大。完了!
希望幫助
我認爲你正在尋找這樣的功能:
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight)
{
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
// Determine new width/height preserving aspect ratio
$srcRatio = $srcWidth/$srcHeight;
$targetRatio = $targetWidth/$targetHeight;
if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight))
{
$imgTargetWidth = $srcWidth;
$imgTargetHeight = $srcHeight;
}
else if ($targetRatio > $srcRatio)
{
$imgTargetWidth = (int) ($targetHeight * $srcRatio);
$imgTargetHeight = $targetHeight;
}
else
{
$imgTargetWidth = $targetWidth;
$imgTargetHeight = (int) ($targetWidth/$srcRatio);
}
// Creating new image with desired size
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
// Add transparency if your reduced image does not fit with the new size
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
// Copies image, centered to the new one (if it does not fit to it)
imagecopyresampled(
$targetImg, $img, ($targetWidth - $imgTargetWidth)/2, // centered
($targetHeight - $imgTargetHeight)/2, // centered
0, 0, $imgTargetWidth, $imgTargetHeight, $srcWidth, $srcHeight
);
return $targetImg;
}
用例:
$gd = imagecreatefromjpeg("images/image5.jpg");
$resized = resizePreservingAspectRatio($gd, 100, 100);
header("Content-type: image/png");
imagepng($resized);
這個轉換這樣一個形象:
那一個:
功能,你應該看看是:imagecreatetruecolor,imagecopyresampled和imagecopy的 – tobspr