We often receive various data from users, including images that need to be stored on a server for future use. To ensure all uploaded images fit the site’s design or take up less disk space, resizing is necessary. While there are functions to check width and height, rejecting images based on size may not be user-friendly.
For this, I have a useful class called SimpleImage, which allows flexible image resizing.
<?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 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 getWidth() {
return imagesx($this->image);
}
function getHeight() {
return imagesy($this->image);
}
}
?>
Using SimpleImage
Save the class file on your server and use the following examples:
Resize image to fxed dimensions
<?php
include('classSimpleImage.php');
$image = new SimpleImage();
$image->load('image.jpg');
$image->resize(400, 200);
$image->save('image1.jpg');
?>
Resize while maintaining aspect ratio
<?php
include('classSimpleImage.php');
$image = new SimpleImage();
$image->load('image.jpg');
$image->resizeToWidth(250);
$image->save('image1.jpg');
?>
Scale image by percentage
<?php
include('classSimpleImage.php');
$image = new SimpleImage();
$image->load('image.jpg');
$image->scale(50);
$image->save('image1.jpg');
?>
Output image directly to browser
<?php
header('Content-Type: image/jpeg');
include('classSimpleImage.php');
$image = new SimpleImage();
$image->load('image.jpg');
$image->resizeToWidth(150);
$image->output();
?>
Upload and resize image via form
<?php
if (isset($_POST['submit'])) {
include('classSimpleImage.php');
$image = new SimpleImage();
$image->load($_FILES['uploaded_image']['tmp_name']);
$image->resizeToWidth(150);
$image->output();
}
else {
echo '<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_image" />
<input type="submit" name="submit" value="Upload" />
</form>';
}
?>
This small yet powerful SimpleImage class is a valuable tool for any developer handling image uploads and processing.