$newimg = imagecreatefromjpeg($tempname);现在,我需要按比例缩放这个图像,但事先不知道这两个维度。
$newimg = imagescale($newimg, 160, auto, IMG_BICUBIC); //doesn't work或
$newimg = imagescale($newimg, auto, 160, IMG_BICUBIC); // doesn't work是否有一种方法可以表示auto或某些东西自动计算宽度或高度。
如果没有,我怎么算?
接受的解决方案here不起作用。我没有保持高宽比。
发布于 2018-04-30 07:37:11
我做了一个能满足你需要的功能。我已经测试了这个功能与缩小图像,它的工作方式,如预期的。
此函数将调整图像大小,保持高宽比,使其完全适合您指定的维度。图像也将居中。
该功能还具有作物的能力。如果使用裁剪参数,它将对图像进行过大调整,以确保图像的最小部分填充所需的维度。然后,它将裁剪图像以适应维度,从而完全填充给定的维度。图像将居中。
以下是功能:
function scaleMyImage($filePath, $newPath, $newSize, $crop = NULL){
$img = imagecreatefromstring(file_get_contents($filePath));
$dst_x = 0;
$dst_y = 0;
$width = imagesx($img);
$height = imagesy($img);
$newWidth = $newSize;
$newHeight = $newSize;
if($width < $height){ //Portrait.
if($crop){
$newWidth = floor($width * ($newSize / $width));
$newHeight = floor($height * ($newSize / $width));
$dst_y = (floor(($newHeight - $newSize)/2)) * -1;
}else{
$newWidth = floor($width * ($newSize / $height));
$newHeight = $newSize;
$dst_x = floor(($newSize - $newWidth)/2);
}
} elseif($width > $height) { //Landscape
if($crop){
$newWidth = floor($width * ($newSize / $height));
$newHeight = floor($height * ($newSize / $height));
$dst_x = (floor(($newWidth - $newSize)/2)) * -1;
}else{
$newWidth = $newSize;
$newHeight = floor($height * ($newSize / $width));
$dst_y = floor(($newSize - $newHeight)/2);
}
}
$finalImage = imagecreatetruecolor($newSize, $newSize);
imagecopyresampled($finalImage, $img, $dst_x, $dst_y, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($finalImage, $newPath, 60); //Set your compression.
imagedestroy($img);
imagedestroy($finalImage);
}使用方法:
$newSize = 160;
$filePath = 'path/myImg.jpg';
$newPath = 'path/newImg.jpg';
$crop = 1; //Set to NULL if you don't want to crop.
scaleMyImage($filePath, $newPath, $newSize, 1);如果将裁剪参数设置为1,这将完全符合您的要求。
发布于 2018-04-30 07:11:56
首先,你必须提到至少一个维度(不管是高度还是宽度),然后使用原始图像的纵横比,你可以识别另一个维度。下面是我在本例中使用的示例代码:
$width = 160; // User-defined
$height = ''; // User-defined
$path = $uploadDir . '/' . $tempname;
$mime = getimagesize($path);
// Load original image
if($mime['mime']=='image/png') {
$orig_img = imagecreatefrompng($path);
}
if($mime['mime']=='image/jpg' || $mime['mime']=='image/jpeg' || $mime['mime']=='image/pjpeg') {
$orig_img = imagecreatefromjpeg($path);
}
// Get original image height and width
$width_orig = imagesx($orig_img);
$height_orig = imagesy($orig_img);
// Aspect ratio of original image
$aspectRatio = $width_orig / $height_orig;
// If any one dimension available then calculate other with the help of aspect-ratio of original image
if ($width == '' && $height != '') {
$newheight = $height;
$newwidth = round($height * $aspectRatio);
}
if ($width != '' && $height == '') {
$newheight = round($width / $aspectRatio);
$newwidth = $width;
}
$newimg = imagescale($orig_img, $newwidth, $newheight, IMG_BICUBIC);https://stackoverflow.com/questions/50095177
复制相似问题