在PHP中調整圖像大小我想編寫一些PHP代碼,自動調整通過表單上傳到147x147px的任何圖像的大小,但我不知道如何處理(我是一個相對的PHP新手)。到目前為止,我已經成功地上傳了圖片,文件類型被識別,名字被清理,但是我想在代碼中添加調整大小的功能。例如,我有一個測試映像,它是2.3MB,維度是1331x1331,我希望代碼能夠縮小它的大小,我猜這也會極大地壓縮圖像的文件大小。到目前為止,我得到了以下信息:if ($_FILES) {
//Put file properties into variables
$file_name = $_FILES['profile-image']['name'];
$file_size = $_FILES['profile-image']['size'];
$file_tmp_name = $_FILES['profile-image']['tmp_name'];
//Determine filetype
switch ($_FILES['profile-image']['type']) {
case 'image/jpeg': $ext = "jpg"; break;
case 'image/png': $ext = "png"; break;
default: $ext = ''; break;
}
if ($ext) {
//Check filesize
if ($file_size < 500000) {
//Process file - clean up filename and move to safe location
$n = "$file_name";
$n = ereg_replace("[^A-Za-z0-9.]", "", $n);
$n = strtolower($n);
$n = "avatars/$n";
move_uploaded_file($file_tmp_name, $n);
} else {
$bad_message = "Please ensure your chosen file is less than 5MB.";
}
} else {
$bad_message = "Please ensure your image is of filetype .jpg or.png.";
}
}$query = "INSERT INTO users (image) VALUES ('$n')";mysql_query($query) or die("Insert failed. " . mysql_error()
. "<br />" . $query);
3 回答

慕的地8271018
TA貢獻1796條經驗 獲得超4個贊
function resize_image($file, $w, $h, $crop=FALSE) { list($width, $height) = getimagesize($file); $r = $width / $height; if ($crop) { if ($width > $height) { $width = ceil($width-($width*abs($r-$w/$h))); } else { $height = ceil($height-($height*abs($r-$w/$h))); } $newwidth = $w; $newheight = $h; } else { if ($w/$h > $r) { $newwidth = $h*$r; $newheight = $h; } else { $newheight = $w/$r; $newwidth = $w; } } $src = imagecreatefromjpeg($file); $dst = imagecreatetruecolor($newwidth, $newheight); imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); return $dst;}
$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);

慕妹3146593
TA貢獻1820條經驗 獲得超9個贊
// for jpg function resize_imagejpg($file, $w, $h) { list($width, $height) = getimagesize($file); $src = imagecreatefromjpeg($file); $dst = imagecreatetruecolor($w, $h); imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height); return $dst;} // for pngfunction resize_imagepng($file, $w, $h) { list($width, $height) = getimagesize($file); $src = imagecreatefrompng($file); $dst = imagecreatetruecolor($w, $h); imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height); return $dst;}// for giffunction resize_imagegif($file, $w, $h) { list($width, $height) = getimagesize($file); $src = imagecreatefromgif($file); $dst = imagecreatetruecolor($w, $h); imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height); return $dst;}
// jpg change the dimension 750, 450 to your desired values $img = resize_imagejpg('path/image.jpg', 750, 450);
$img
// again for jpg imagejpeg($img, 'path/newimage.jpg');
- 3 回答
- 0 關注
- 696 瀏覽
添加回答
舉報
0/150
提交
取消