使用PHP扭曲的图像调整大小 [英] Distorted image resize with PHP
本文介绍了使用PHP扭曲的图像调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个上传表单,您可以在其中选择照片.上传后,如有必要,我会调整图像的大小.
I have an upload form where you select photos. Upon upload I resize the image if necessary.
似乎我上传的任何照片都是HEIGHT > WIDTH
拉伸图像的地方.如果我在WIDTH > HEIGHT
的位置上传图片,效果很好.我一直在绞尽脑汁想办法解决这个问题.我很确定自己知道问题所在,并已在评论中指出了这一点.
It seems any photo that I upload where the HEIGHT > WIDTH
stretches the image. If I upload an image where WIDTH > HEIGHT
it works fine. I've been racking my brain trying to figure this out. I'm pretty sure I know which line is the issue and I've pointed it out in a comment.
有人可以看到我的数学有什么问题吗?谢谢!
Can anyone see what is wrong with my math? Thanks!
<?php
$maxWidth = 900;
$maxHeight = 675;
$count = 0;
foreach ($_FILES['photos']['name'] as $filename)
{
$uniqueId = uniqid();
$target = "../resources/images/projects/" . strtolower($uniqueId . "_" . $filename);
$file = $_FILES['photos']['tmp_name'][$count];
list($originalWidth, $originalHeight) = getimagesize($file);
// if the image is larger than maxWidth or maxHeight
if ($originalWidth > $maxWidth || $originalHeight > $maxHeight)
{
$ratio = $originalWidth / $originalHeight;
// I think this is the problem line
(($maxWidth / $maxHeight) > $ratio) ? $maxWidth = $maxWidth * $ratio : $maxHeight = $maxWidth / $ratio;
// resample and save
$image_p = imagecreatetruecolor($maxWidth, $maxHeight);
$image = imagecreatefromjpeg($file);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $maxWidth, $maxHeight, $originalWidth, $originalHeight);
$image = imagejpeg($image_p, $target, 75);
}
else
{
// just save the image
move_uploaded_file($file,$target);
}
$count += 1;
}
?>
推荐答案
缩放时,您需要同时修改目标的宽度和高度.
When scaling, you need to modify both the width and the height of the target.
尝试:
if ($originalWidth > $maxWidth || $originalHeight > $maxHeight)
{
if ($originalWidth / $maxWidth > $originalHeight / $maxHeight) {
// width is the limiting factor
$width = $maxWidth;
$height = floor($width * $originalHeight / $originalWidth);
} else { // height is the limiting factor
$height = $maxHeight;
$width = floor($height * $originalWidth / $originalHeight);
}
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($file);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight);
$image = imagejpeg($image_p, $target, 75);
}
这篇关于使用PHP扭曲的图像调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文