PHP работа с картинкой - изменение размеров PNG GIF JPG, подгонка по ширине, пропорциональное изменение - пример функций класса
Primary tabs
Друзья, скидываю вам такой вот 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 ) {
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) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
/*метод следует вызываеть,если требуется подогнать некоторую картинку
по стандартные рамки
*/
function toSize($width, $height)
{
if ($this->getWidth() >= $width) // если требуется уменьшаем длинну
$this->resizeToWidth($width);
if ($this->getHeight() >= $height) // если требуется уменьшаем высоту
$this->resizeToHeight($height);
// if ($width>=$height)
// $this->resizeToWidth($width);
// else
// $this->resizeToHeight($height);
}
}
- Log in to post comments
- 2800 reads