我一直在互联网上寻找解决方案。我正在使用这个SimpleImage.php类来调整我在这里找到的图像的大小(http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php)。到目前为止一切都很好。如果我尝试将图像重新调整到特定的高度或宽度,它就会完成它的工作。但是,这仅在我尝试一次调整一个图像时才有效。假设我的图像的原始大小是1400x1100,我想将其高度调整为800.这将给我一个某个数字x800 的结果。反之亦然。
我的目标是根据我传递的MAX-WIDTH和MAX-HEIGHT调整图像大小。
这样的事情:
$image = new SimpleImage();
$image->load($image_url);
$image->resizeToWidthHeight(MAX-WIDTH, MAX-HEIGHT);
$image->save('photo.png');
这是我的SimpleImage.php类
<?php
class SimpleImage {
var $image;
var $image_type;
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$this->image = imagecreatefromjpeg($filename);
} elseif( $this->image_type == IMAGETYPE_GIF ) {
$this->image = imagecreatefromgif($filename);
} elseif( $this->image_type == IMAGETYPE_PNG ) {
$this->image = imagecreatefrompng($filename);
}
}
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image,$filename,$compression);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image,$filename);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image,$filename);
}
if( $permissions != null) {
chmod($filename,$permissions);
}
}
function output($image_type=IMAGETYPE_JPEG) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image);
} elseif( $image_type == IMAGETYPE_PNG ) {
imageAlphaBlending($this->image, true);
imageSaveAlpha($this->image, true);
imagepng($this->image);
}
}
function getWidth() {
return imagesx($this->image);
}
function getHeight() {
return imagesy($this->image);
}
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
function resize($width,$height) {
// ADDED CODE IS HERE - NOT SURE WHY IT DOESN'T WORK FOR PNG
// Setup new image
$new_image = imagecreatetruecolor($width, $height);
// These parameters are required for handling PNG files.
imagealphablending($new_image, false);
imagesavealpha($new_image,true);
$transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
imagefilledrectangle($new_image, 0, 0, $width, $height, $transparent);
// Resize image
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
}
?>
答案 0 :(得分:0)
如果您的图片尺寸发生变化:您从3:4变为16:9,则需要在某处进行一些裁剪。
根据比例确定哪个维度最小,调整该属性的大小,然后裁剪另一个维度。
根据我的经验,规模始终是错误的。我建议你把它从图书馆中删除。调整大小+裁剪是可行的方法。
您可以编写类似cropTo($newX, $newY)