Reduce quality in imagepng without save the file - php

I use this code in images.php to show the images :
imagepng($out);
and if i want to reduce the images quality for thumbnails i tried this code :
imagepng($out,$filename,$quality);
i want to know how to reduce image quality without saving.

function resize_image($file, $w, $h, $crop=false) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
//Get file extension
$exploding = explode(".",$file);
$ext = end($exploding);
switch($ext){
case "png":
$src = imagecreatefrompng($file);
break;
case "jpeg":
case "jpg":
$src = imagecreatefromjpeg($file);
break;
case "gif":
$src = imagecreatefromgif($file);
break;
default:
$src = imagecreatefromjpeg($file);
break;
}
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
$filename = "/var/www/images/mynormalimage.png";
$resizedFilename = "/var/www/images/myresizedimage.png";
// resize the image with 300x300
$imgData = resize_image($filename, 300, 300);
// save the image on the given filename
imagepng($imgData, $resizedFilename);
// or according to the original format, use another method
// imagejpeg($imgData, $resizedFilename);
// imagegif($imgData, $resizedFilename);
https://ourcodeworld.com/articles/read/197/how-to-resize-an-image-and-reduce-quality-in-php-without-imagickenter code here

Related

How to resize image in PHP with new dimensions? [duplicate]

I want to write some PHP code that automatically resizes any image uploaded via a form to 147x147px, but I have no idea how to go about it (I'm a relative PHP novice).
So far, I've got images uploading successfully, filetypes being recognized and names cleaned up, but I'd like to add the resize functionality into the code. For example, I've got a test image that is 2.3MB, and 1331x1331 in dimension, and I'd like the code to size it down, which I'm guessing will dramatically compress the file size of the image, too.
So far, I've got the following:
if ($_FILES) {
//Put file properties into variables
$file_name = $_FILES['profile-image']['name'];
$file_size = $_FILES['profile-image']['size'];
$file_tmp_name = $_FILES['profile-image']['tmp_name'];
//Determine filetype
switch ($_FILES['profile-image']['type']) {
case 'image/jpeg': $ext = "jpg"; break;
case 'image/png': $ext = "png"; break;
default: $ext = ''; break;
}
if ($ext) {
//Check filesize
if ($file_size < 500000) {
//Process file - clean up filename and move to safe location
$n = "$file_name";
$n = ereg_replace("[^A-Za-z0-9.]", "", $n);
$n = strtolower($n);
$n = "avatars/$n";
move_uploaded_file($file_tmp_name, $n);
} else {
$bad_message = "Please ensure your chosen file is less than 5MB.";
}
} else {
$bad_message = "Please ensure your image is of filetype .jpg or.png.";
}
}
$query = "INSERT INTO users (image) VALUES ('$n')";
mysql_query($query) or die("Insert failed. " . mysql_error() . "<br />" . $query);
You need to use either PHP's ImageMagick or GD functions to work with images.
With GD, for example, it's as simple as...
function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
And you could call this function, like so...
$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);
From personal experience, GD's image resampling does dramatically reduce file size too, especially when resampling raw digital camera images.
Simply use PHP's GD functions (like imagescale):
Syntax:
imagescale ( $image , $new_width , $new_height )
Example:
Step: 1 Read the file
$image_name = 'path_of_Image/Name_of_Image.jpg|png|gif';
Step: 2: Load the Image File
$image = imagecreatefromjpeg($image_name); // For JPEG
//or
$image = imagecreatefrompng($image_name); // For PNG
//or
$image = imagecreatefromgif($image_name); // For GIF
Step: 3: Our Life-saver comes in '_' | Scale the image
$imgResized = imagescale($image , 500, 400); // width=500 and height = 400
// $imgResized is our final product
Note: imagescale will work for (PHP 5 >= 5.5.0, PHP 7)
Step: 4: Save the Resized image to your desired directory.
imagejpeg($imgResized, 'path_of_Image/Name_of_Image_resized.jpg'); //for jpeg
imagepng($imgResized, 'path_of_Image/Name_of_Image_resized.png'); //for png
Source : Click to Read more
This resource(broken link) is also worth considering - some very tidy code that uses GD. However, I modified their final code snippet to create this function which meets the OPs requirements...
function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) {
$target_dir = "your-uploaded-images-folder/";
$target_file = $target_dir . basename($_FILES[$html_element_name]["name"]);
$image = new SimpleImage();
$image->load($_FILES[$html_element_name]['tmp_name']);
$image->resize($new_img_width, $new_img_height);
$image->save($target_file);
return $target_file; //return name of saved file in case you want to store it in you database or show confirmation message to user
}
You will also need to include this PHP file...
<?php
/*
* File: SimpleImage.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 08/11/06
* Link: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/
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;
}
}
?>
If you dont care about the aspect ration (i.e you want to force the image to a particular dimension), here is a simplified answer
// for jpg
function resize_imagejpg($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
// for png
function resize_imagepng($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefrompng($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
// for gif
function resize_imagegif($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefromgif($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
Now let's handle the upload part.
First step, upload the file to your desired directory. Then called one of the above functions based on file type (jpg, png or gif) and pass the absolute path of your uploaded file as below:
// jpg change the dimension 750, 450 to your desired values
$img = resize_imagejpg('path/image.jpg', 750, 450);
The return value $img is a resource object. We can save to a new location or override the original as below:
// again for jpg
imagejpeg($img, 'path/newimage.jpg');
Hope this helps someone. Check these links for more on resizing Imagick::resizeImage and
imagejpeg()
I hope is will work for you.
/**
* Image re-size
* #param int $width
* #param int $height
*/
function ImageResize($width, $height, $img_name)
{
/* Get original file size */
list($w, $h) = getimagesize($_FILES['logo_image']['tmp_name']);
/*$ratio = $w / $h;
$size = $width;
$width = $height = min($size, max($w, $h));
if ($ratio < 1) {
$width = $height * $ratio;
} else {
$height = $width / $ratio;
}*/
/* Calculate new image size */
$ratio = max($width/$w, $height/$h);
$h = ceil($height / $ratio);
$x = ($w - $width / $ratio) / 2;
$w = ceil($width / $ratio);
/* set new file name */
$path = $img_name;
/* Save image */
if($_FILES['logo_image']['type']=='image/jpeg')
{
/* Get binary data from image */
$imgString = file_get_contents($_FILES['logo_image']['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
imagejpeg($tmp, $path, 100);
}
else if($_FILES['logo_image']['type']=='image/png')
{
$image = imagecreatefrompng($_FILES['logo_image']['tmp_name']);
$tmp = imagecreatetruecolor($width,$height);
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
imagecopyresampled($tmp, $image,0,0,$x,0,$width,$height,$w, $h);
imagepng($tmp, $path, 0);
}
else if($_FILES['logo_image']['type']=='image/gif')
{
$image = imagecreatefromgif($_FILES['logo_image']['tmp_name']);
$tmp = imagecreatetruecolor($width,$height);
$transparent = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
imagefill($tmp, 0, 0, $transparent);
imagealphablending($tmp, true);
imagecopyresampled($tmp, $image,0,0,0,0,$width,$height,$w, $h);
imagegif($tmp, $path);
}
else
{
return false;
}
return true;
imagedestroy($image);
imagedestroy($tmp);
}
(IMPORTANT: In the case of animation (animated webp or gif) resizing, the result will be a not animated, but resized image from the first frame! (The original animation remains intact...)
I created this to my php 7.2 project (example imagebmp sure (PHP 7 >= 7.2.0) :php/manual/function.imagebmp) about techfry.com/php-tutorial, with GD2, (so nothing 3rd party library) and very similar to the answer of Nico Bistolfi, but works with the all five basic image mimetype (png, jpeg, webp, bmp and gif), creating a new resized file, without modifying the original one, and the all stuff in one function and ready to use (copy and paste to your project). (You can set the extension of the new file with the fifth parameter, or just leave it, if you want keep the orignal):
function createResizedImage(
string $imagePath = '',
string $newPath = '',
int $newWidth = 0,
int $newHeight = 0,
string $outExt = 'DEFAULT'
) : ?string
{
if (!$newPath or !file_exists ($imagePath)) {
return null;
}
$types = [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_BMP, IMAGETYPE_WEBP];
$type = exif_imagetype ($imagePath);
if (!in_array ($type, $types)) {
return null;
}
list ($width, $height) = getimagesize ($imagePath);
$outBool = in_array ($outExt, ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']);
switch ($type) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg ($imagePath);
if (!$outBool) $outExt = 'jpg';
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng ($imagePath);
if (!$outBool) $outExt = 'png';
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif ($imagePath);
if (!$outBool) $outExt = 'gif';
break;
case IMAGETYPE_BMP:
$image = imagecreatefrombmp ($imagePath);
if (!$outBool) $outExt = 'bmp';
break;
case IMAGETYPE_WEBP:
$image = imagecreatefromwebp ($imagePath);
if (!$outBool) $outExt = 'webp';
}
$newImage = imagecreatetruecolor ($newWidth, $newHeight);
//TRANSPARENT BACKGROUND
$color = imagecolorallocatealpha ($newImage, 0, 0, 0, 127); //fill transparent back
imagefill ($newImage, 0, 0, $color);
imagesavealpha ($newImage, true);
//ROUTINE
imagecopyresampled ($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// Rotate image on iOS
if(function_exists('exif_read_data') && $exif = exif_read_data($imagePath, 'IFD0'))
{
if(isset($exif['Orientation']) && isset($exif['Make']) && !empty($exif['Orientation']) && preg_match('/(apple|ios|iphone)/i', $exif['Make'])) {
switch($exif['Orientation']) {
case 8:
if ($width > $height) $newImage = imagerotate($newImage,90,0);
break;
case 3:
$newImage = imagerotate($newImage,180,0);
break;
case 6:
$newImage = imagerotate($newImage,-90,0);
break;
}
}
}
switch (true) {
case in_array ($outExt, ['jpg', 'jpeg']): $success = imagejpeg ($newImage, $newPath);
break;
case $outExt === 'png': $success = imagepng ($newImage, $newPath);
break;
case $outExt === 'gif': $success = imagegif ($newImage, $newPath);
break;
case $outExt === 'bmp': $success = imagebmp ($newImage, $newPath);
break;
case $outExt === 'webp': $success = imagewebp ($newImage, $newPath);
}
if (!$success) {
return null;
}
return $newPath;
}
I created an easy-to-use library for image resizing. It can be found here on Github.
An example of how to use the library:
// Include PHP Image Magician library
require_once('php_image_magician.php');
// Open JPG image
$magicianObj = new imageLib('racecar.jpg');
// Resize to best fit then crop (check out the other options)
$magicianObj -> resizeImage(100, 200, 'crop');
// Save resized image as a PNG (or jpg, bmp, etc)
$magicianObj -> saveImage('racecar_small.png');
Other features, should you need them, are:
Quick and easy resize - Resize to landscape, portrait, or auto
Easy crop
Add text
Quality adjustment
Watermarking
Shadows and reflections
Transparency support
Read EXIF metadata
Borders, Rounded corners, Rotation
Filters and effects
Image sharpening
Image type conversion
BMP support
I found a mathematical way to get this job done
Github repo - https://github.com/gayanSandamal/easy-php-image-resizer
Live example - https://plugins.nayague.com/easy-php-image-resizer/
<?php
//path for the image
$source_url = '2018-04-01-1522613288.PNG';
//separate the file name and the extention
$source_url_parts = pathinfo($source_url);
$filename = $source_url_parts['filename'];
$extension = $source_url_parts['extension'];
//define the quality from 1 to 100
$quality = 10;
//detect the width and the height of original image
list($width, $height) = getimagesize($source_url);
$width;
$height;
//define any width that you want as the output. mine is 200px.
$after_width = 200;
//resize only when the original image is larger than expected with.
//this helps you to avoid from unwanted resizing.
if ($width > $after_width) {
//get the reduced width
$reduced_width = ($width - $after_width);
//now convert the reduced width to a percentage and round it to 2 decimal places
$reduced_radio = round(($reduced_width / $width) * 100, 2);
//ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places
$reduced_height = round(($height / 100) * $reduced_radio, 2);
//reduce the calculated height from the original height
$after_height = $height - $reduced_height;
//Now detect the file extension
//if the file extension is 'jpg', 'jpeg', 'JPG' or 'JPEG'
if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'JPG' || $extension == 'JPEG') {
//then return the image as a jpeg image for the next step
$img = imagecreatefromjpeg($source_url);
} elseif ($extension == 'png' || $extension == 'PNG') {
//then return the image as a png image for the next step
$img = imagecreatefrompng($source_url);
} else {
//show an error message if the file extension is not available
echo 'image extension is not supporting';
}
//HERE YOU GO :)
//Let's do the resize thing
//imagescale([returned image], [width of the resized image], [height of the resized image], [quality of the resized image]);
$imgResized = imagescale($img, $after_width, $after_height, $quality);
//now save the resized image with a suffix called "-resized" and with its extension.
imagejpeg($imgResized, $filename . '-resized.'.$extension);
//Finally frees any memory associated with image
//**NOTE THAT THIS WONT DELETE THE IMAGE
imagedestroy($img);
imagedestroy($imgResized);
}
?>
Here is an extended version of the answer #Ian Atkin' gave. I found it worked extremely well. For larger images that is :). You can actually make smaller images larger if you're not careful.
Changes:
- Supports jpg,jpeg,png,gif,bmp files
- Preserves transparency for .png and .gif
- Double checks if the the size of the original isnt already smaller
- Overrides the image given directly (Its what I needed)
So here it is. The default values of the function are the "golden rule"
function resize_image($file, $w = 1200, $h = 741, $crop = false)
{
try {
$ext = pathinfo(storage_path() . $file, PATHINFO_EXTENSION);
list($width, $height) = getimagesize($file);
// if the image is smaller we dont resize
if ($w > $width && $h > $height) {
return true;
}
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width - ($width * abs($r - $w / $h)));
} else {
$height = ceil($height - ($height * abs($r - $w / $h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w / $h > $r) {
$newwidth = $h * $r;
$newheight = $h;
} else {
$newheight = $w / $r;
$newwidth = $w;
}
}
$dst = imagecreatetruecolor($newwidth, $newheight);
switch ($ext) {
case 'jpg':
case 'jpeg':
$src = imagecreatefromjpeg($file);
break;
case 'png':
$src = imagecreatefrompng($file);
imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
imagealphablending($dst, false);
imagesavealpha($dst, true);
break;
case 'gif':
$src = imagecreatefromgif($file);
imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
imagealphablending($dst, false);
imagesavealpha($dst, true);
break;
case 'bmp':
$src = imagecreatefrombmp($file);
break;
default:
throw new Exception('Unsupported image extension found: ' . $ext);
break;
}
$result = imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
switch ($ext) {
case 'bmp':
imagewbmp($dst, $file);
break;
case 'gif':
imagegif($dst, $file);
break;
case 'jpg':
case 'jpeg':
imagejpeg($dst, $file);
break;
case 'png':
imagepng($dst, $file);
break;
}
return true;
} catch (Exception $err) {
// LOG THE ERROR HERE
return false;
}
}
ZF cake:
<?php
class FkuController extends Zend_Controller_Action {
var $image;
var $image_type;
public function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) {
$target_dir = APPLICATION_PATH . "/../public/1/";
$target_file = $target_dir . basename($_FILES[$html_element_name]["name"]);
//$image = new SimpleImage();
$this->load($_FILES[$html_element_name]['tmp_name']);
$this->resize($new_img_width, $new_img_height);
$this->save($target_file);
return $target_file;
//return name of saved file in case you want to store it in you database or show confirmation message to user
public 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);
}
}
public 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);
}
}
public 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);
}
}
public function getWidth() {
return imagesx($this->image);
}
public function getHeight() {
return imagesy($this->image);
}
public function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
public function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
public function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
public 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;
}
public function savepicAction() {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$this->_response->setHeader('Access-Control-Allow-Origin', '*');
$this->db = Application_Model_Db::db_load();
$ouser = $_POST['ousername'];
$fdata = 'empty';
if (isset($_FILES['picture']) && $_FILES['picture']['size'] > 0) {
$file_size = $_FILES['picture']['size'];
$tmpName = $_FILES['picture']['tmp_name'];
//Determine filetype
switch ($_FILES['picture']['type']) {
case 'image/jpeg': $ext = "jpg"; break;
case 'image/png': $ext = "png"; break;
case 'image/jpg': $ext = "jpg"; break;
case 'image/bmp': $ext = "bmp"; break;
case 'image/gif': $ext = "gif"; break;
default: $ext = ''; break;
}
if($ext) {
//if($file_size<400000) {
$img = $this->store_uploaded_image('picture', 90,82);
//$fp = fopen($tmpName, 'r');
$fp = fopen($img, 'r');
$fdata = fread($fp, filesize($tmpName));
$fdata = base64_encode($fdata);
fclose($fp);
//}
}
}
if($fdata=='empty'){
}
else {
$this->db->update('users',
array(
'picture' => $fdata,
),
array('username=?' => $ouser ));
}
}
I would suggest an easy way:
function resize($file, $width, $height) {
switch(pathinfo($file)['extension']) {
case "png": return imagepng(imagescale(imagecreatefrompng($file), $width, $height), $file);
case "gif": return imagegif(imagescale(imagecreatefromgif($file), $width, $height), $file);
default : return imagejpeg(imagescale(imagecreatefromjpeg($file), $width, $height), $file);
}
}
private function getTempImage($url, $tempName){
$tempPath = 'tempFilePath' . $tempName . '.png';
$source_image = imagecreatefrompng($url); // check type depending on your necessities.
$source_imagex = imagesx($source_image);
$source_imagey = imagesy($source_image);
$dest_imagex = 861; // My default value
$dest_imagey = 96; // My default value
$dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);
imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);
imagejpeg($dest_image, $tempPath, 100);
return $tempPath;
}
This is an adapted solution based on this great explanation. This guy made a step by step explanation.
Hope all enjoy it.
You can give a try to TinyPNG PHP library. Using this library your image gets optimized automatically during resizing process. All you need to install the library and get an API key from https://tinypng.com/developers. To install a library, run the below command.
composer require tinify/tinify
After that, your code is as follows.
require_once("vendor/autoload.php");
\Tinify\setKey("YOUR_API_KEY");
$source = \Tinify\fromFile("large.jpg"); //image to be resize
$resized = $source->resize(array(
"method" => "fit",
"width" => 150,
"height" => 100
));
$resized->toFile("thumbnail.jpg"); //resized image
I have a written a blog on the same topic http://artisansweb.net/resize-image-php-using-tinypng

resize image on a HTML Page with php script [duplicate]

I want to write some PHP code that automatically resizes any image uploaded via a form to 147x147px, but I have no idea how to go about it (I'm a relative PHP novice).
So far, I've got images uploading successfully, filetypes being recognized and names cleaned up, but I'd like to add the resize functionality into the code. For example, I've got a test image that is 2.3MB, and 1331x1331 in dimension, and I'd like the code to size it down, which I'm guessing will dramatically compress the file size of the image, too.
So far, I've got the following:
if ($_FILES) {
//Put file properties into variables
$file_name = $_FILES['profile-image']['name'];
$file_size = $_FILES['profile-image']['size'];
$file_tmp_name = $_FILES['profile-image']['tmp_name'];
//Determine filetype
switch ($_FILES['profile-image']['type']) {
case 'image/jpeg': $ext = "jpg"; break;
case 'image/png': $ext = "png"; break;
default: $ext = ''; break;
}
if ($ext) {
//Check filesize
if ($file_size < 500000) {
//Process file - clean up filename and move to safe location
$n = "$file_name";
$n = ereg_replace("[^A-Za-z0-9.]", "", $n);
$n = strtolower($n);
$n = "avatars/$n";
move_uploaded_file($file_tmp_name, $n);
} else {
$bad_message = "Please ensure your chosen file is less than 5MB.";
}
} else {
$bad_message = "Please ensure your image is of filetype .jpg or.png.";
}
}
$query = "INSERT INTO users (image) VALUES ('$n')";
mysql_query($query) or die("Insert failed. " . mysql_error() . "<br />" . $query);
You need to use either PHP's ImageMagick or GD functions to work with images.
With GD, for example, it's as simple as...
function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
And you could call this function, like so...
$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);
From personal experience, GD's image resampling does dramatically reduce file size too, especially when resampling raw digital camera images.
Simply use PHP's GD functions (like imagescale):
Syntax:
imagescale ( $image , $new_width , $new_height )
Example:
Step: 1 Read the file
$image_name = 'path_of_Image/Name_of_Image.jpg|png|gif';
Step: 2: Load the Image File
$image = imagecreatefromjpeg($image_name); // For JPEG
//or
$image = imagecreatefrompng($image_name); // For PNG
//or
$image = imagecreatefromgif($image_name); // For GIF
Step: 3: Our Life-saver comes in '_' | Scale the image
$imgResized = imagescale($image , 500, 400); // width=500 and height = 400
// $imgResized is our final product
Note: imagescale will work for (PHP 5 >= 5.5.0, PHP 7)
Step: 4: Save the Resized image to your desired directory.
imagejpeg($imgResized, 'path_of_Image/Name_of_Image_resized.jpg'); //for jpeg
imagepng($imgResized, 'path_of_Image/Name_of_Image_resized.png'); //for png
Source : Click to Read more
This resource(broken link) is also worth considering - some very tidy code that uses GD. However, I modified their final code snippet to create this function which meets the OPs requirements...
function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) {
$target_dir = "your-uploaded-images-folder/";
$target_file = $target_dir . basename($_FILES[$html_element_name]["name"]);
$image = new SimpleImage();
$image->load($_FILES[$html_element_name]['tmp_name']);
$image->resize($new_img_width, $new_img_height);
$image->save($target_file);
return $target_file; //return name of saved file in case you want to store it in you database or show confirmation message to user
}
You will also need to include this PHP file...
<?php
/*
* File: SimpleImage.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 08/11/06
* Link: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/
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;
}
}
?>
If you dont care about the aspect ration (i.e you want to force the image to a particular dimension), here is a simplified answer
// for jpg
function resize_imagejpg($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
// for png
function resize_imagepng($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefrompng($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
// for gif
function resize_imagegif($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefromgif($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
Now let's handle the upload part.
First step, upload the file to your desired directory. Then called one of the above functions based on file type (jpg, png or gif) and pass the absolute path of your uploaded file as below:
// jpg change the dimension 750, 450 to your desired values
$img = resize_imagejpg('path/image.jpg', 750, 450);
The return value $img is a resource object. We can save to a new location or override the original as below:
// again for jpg
imagejpeg($img, 'path/newimage.jpg');
Hope this helps someone. Check these links for more on resizing Imagick::resizeImage and
imagejpeg()
I hope is will work for you.
/**
* Image re-size
* #param int $width
* #param int $height
*/
function ImageResize($width, $height, $img_name)
{
/* Get original file size */
list($w, $h) = getimagesize($_FILES['logo_image']['tmp_name']);
/*$ratio = $w / $h;
$size = $width;
$width = $height = min($size, max($w, $h));
if ($ratio < 1) {
$width = $height * $ratio;
} else {
$height = $width / $ratio;
}*/
/* Calculate new image size */
$ratio = max($width/$w, $height/$h);
$h = ceil($height / $ratio);
$x = ($w - $width / $ratio) / 2;
$w = ceil($width / $ratio);
/* set new file name */
$path = $img_name;
/* Save image */
if($_FILES['logo_image']['type']=='image/jpeg')
{
/* Get binary data from image */
$imgString = file_get_contents($_FILES['logo_image']['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
imagejpeg($tmp, $path, 100);
}
else if($_FILES['logo_image']['type']=='image/png')
{
$image = imagecreatefrompng($_FILES['logo_image']['tmp_name']);
$tmp = imagecreatetruecolor($width,$height);
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
imagecopyresampled($tmp, $image,0,0,$x,0,$width,$height,$w, $h);
imagepng($tmp, $path, 0);
}
else if($_FILES['logo_image']['type']=='image/gif')
{
$image = imagecreatefromgif($_FILES['logo_image']['tmp_name']);
$tmp = imagecreatetruecolor($width,$height);
$transparent = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
imagefill($tmp, 0, 0, $transparent);
imagealphablending($tmp, true);
imagecopyresampled($tmp, $image,0,0,0,0,$width,$height,$w, $h);
imagegif($tmp, $path);
}
else
{
return false;
}
return true;
imagedestroy($image);
imagedestroy($tmp);
}
(IMPORTANT: In the case of animation (animated webp or gif) resizing, the result will be a not animated, but resized image from the first frame! (The original animation remains intact...)
I created this to my php 7.2 project (example imagebmp sure (PHP 7 >= 7.2.0) :php/manual/function.imagebmp) about techfry.com/php-tutorial, with GD2, (so nothing 3rd party library) and very similar to the answer of Nico Bistolfi, but works with the all five basic image mimetype (png, jpeg, webp, bmp and gif), creating a new resized file, without modifying the original one, and the all stuff in one function and ready to use (copy and paste to your project). (You can set the extension of the new file with the fifth parameter, or just leave it, if you want keep the orignal):
function createResizedImage(
string $imagePath = '',
string $newPath = '',
int $newWidth = 0,
int $newHeight = 0,
string $outExt = 'DEFAULT'
) : ?string
{
if (!$newPath or !file_exists ($imagePath)) {
return null;
}
$types = [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_BMP, IMAGETYPE_WEBP];
$type = exif_imagetype ($imagePath);
if (!in_array ($type, $types)) {
return null;
}
list ($width, $height) = getimagesize ($imagePath);
$outBool = in_array ($outExt, ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']);
switch ($type) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg ($imagePath);
if (!$outBool) $outExt = 'jpg';
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng ($imagePath);
if (!$outBool) $outExt = 'png';
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif ($imagePath);
if (!$outBool) $outExt = 'gif';
break;
case IMAGETYPE_BMP:
$image = imagecreatefrombmp ($imagePath);
if (!$outBool) $outExt = 'bmp';
break;
case IMAGETYPE_WEBP:
$image = imagecreatefromwebp ($imagePath);
if (!$outBool) $outExt = 'webp';
}
$newImage = imagecreatetruecolor ($newWidth, $newHeight);
//TRANSPARENT BACKGROUND
$color = imagecolorallocatealpha ($newImage, 0, 0, 0, 127); //fill transparent back
imagefill ($newImage, 0, 0, $color);
imagesavealpha ($newImage, true);
//ROUTINE
imagecopyresampled ($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// Rotate image on iOS
if(function_exists('exif_read_data') && $exif = exif_read_data($imagePath, 'IFD0'))
{
if(isset($exif['Orientation']) && isset($exif['Make']) && !empty($exif['Orientation']) && preg_match('/(apple|ios|iphone)/i', $exif['Make'])) {
switch($exif['Orientation']) {
case 8:
if ($width > $height) $newImage = imagerotate($newImage,90,0);
break;
case 3:
$newImage = imagerotate($newImage,180,0);
break;
case 6:
$newImage = imagerotate($newImage,-90,0);
break;
}
}
}
switch (true) {
case in_array ($outExt, ['jpg', 'jpeg']): $success = imagejpeg ($newImage, $newPath);
break;
case $outExt === 'png': $success = imagepng ($newImage, $newPath);
break;
case $outExt === 'gif': $success = imagegif ($newImage, $newPath);
break;
case $outExt === 'bmp': $success = imagebmp ($newImage, $newPath);
break;
case $outExt === 'webp': $success = imagewebp ($newImage, $newPath);
}
if (!$success) {
return null;
}
return $newPath;
}
I created an easy-to-use library for image resizing. It can be found here on Github.
An example of how to use the library:
// Include PHP Image Magician library
require_once('php_image_magician.php');
// Open JPG image
$magicianObj = new imageLib('racecar.jpg');
// Resize to best fit then crop (check out the other options)
$magicianObj -> resizeImage(100, 200, 'crop');
// Save resized image as a PNG (or jpg, bmp, etc)
$magicianObj -> saveImage('racecar_small.png');
Other features, should you need them, are:
Quick and easy resize - Resize to landscape, portrait, or auto
Easy crop
Add text
Quality adjustment
Watermarking
Shadows and reflections
Transparency support
Read EXIF metadata
Borders, Rounded corners, Rotation
Filters and effects
Image sharpening
Image type conversion
BMP support
I found a mathematical way to get this job done
Github repo - https://github.com/gayanSandamal/easy-php-image-resizer
Live example - https://plugins.nayague.com/easy-php-image-resizer/
<?php
//path for the image
$source_url = '2018-04-01-1522613288.PNG';
//separate the file name and the extention
$source_url_parts = pathinfo($source_url);
$filename = $source_url_parts['filename'];
$extension = $source_url_parts['extension'];
//define the quality from 1 to 100
$quality = 10;
//detect the width and the height of original image
list($width, $height) = getimagesize($source_url);
$width;
$height;
//define any width that you want as the output. mine is 200px.
$after_width = 200;
//resize only when the original image is larger than expected with.
//this helps you to avoid from unwanted resizing.
if ($width > $after_width) {
//get the reduced width
$reduced_width = ($width - $after_width);
//now convert the reduced width to a percentage and round it to 2 decimal places
$reduced_radio = round(($reduced_width / $width) * 100, 2);
//ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places
$reduced_height = round(($height / 100) * $reduced_radio, 2);
//reduce the calculated height from the original height
$after_height = $height - $reduced_height;
//Now detect the file extension
//if the file extension is 'jpg', 'jpeg', 'JPG' or 'JPEG'
if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'JPG' || $extension == 'JPEG') {
//then return the image as a jpeg image for the next step
$img = imagecreatefromjpeg($source_url);
} elseif ($extension == 'png' || $extension == 'PNG') {
//then return the image as a png image for the next step
$img = imagecreatefrompng($source_url);
} else {
//show an error message if the file extension is not available
echo 'image extension is not supporting';
}
//HERE YOU GO :)
//Let's do the resize thing
//imagescale([returned image], [width of the resized image], [height of the resized image], [quality of the resized image]);
$imgResized = imagescale($img, $after_width, $after_height, $quality);
//now save the resized image with a suffix called "-resized" and with its extension.
imagejpeg($imgResized, $filename . '-resized.'.$extension);
//Finally frees any memory associated with image
//**NOTE THAT THIS WONT DELETE THE IMAGE
imagedestroy($img);
imagedestroy($imgResized);
}
?>
Here is an extended version of the answer #Ian Atkin' gave. I found it worked extremely well. For larger images that is :). You can actually make smaller images larger if you're not careful.
Changes:
- Supports jpg,jpeg,png,gif,bmp files
- Preserves transparency for .png and .gif
- Double checks if the the size of the original isnt already smaller
- Overrides the image given directly (Its what I needed)
So here it is. The default values of the function are the "golden rule"
function resize_image($file, $w = 1200, $h = 741, $crop = false)
{
try {
$ext = pathinfo(storage_path() . $file, PATHINFO_EXTENSION);
list($width, $height) = getimagesize($file);
// if the image is smaller we dont resize
if ($w > $width && $h > $height) {
return true;
}
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width - ($width * abs($r - $w / $h)));
} else {
$height = ceil($height - ($height * abs($r - $w / $h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w / $h > $r) {
$newwidth = $h * $r;
$newheight = $h;
} else {
$newheight = $w / $r;
$newwidth = $w;
}
}
$dst = imagecreatetruecolor($newwidth, $newheight);
switch ($ext) {
case 'jpg':
case 'jpeg':
$src = imagecreatefromjpeg($file);
break;
case 'png':
$src = imagecreatefrompng($file);
imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
imagealphablending($dst, false);
imagesavealpha($dst, true);
break;
case 'gif':
$src = imagecreatefromgif($file);
imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
imagealphablending($dst, false);
imagesavealpha($dst, true);
break;
case 'bmp':
$src = imagecreatefrombmp($file);
break;
default:
throw new Exception('Unsupported image extension found: ' . $ext);
break;
}
$result = imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
switch ($ext) {
case 'bmp':
imagewbmp($dst, $file);
break;
case 'gif':
imagegif($dst, $file);
break;
case 'jpg':
case 'jpeg':
imagejpeg($dst, $file);
break;
case 'png':
imagepng($dst, $file);
break;
}
return true;
} catch (Exception $err) {
// LOG THE ERROR HERE
return false;
}
}
ZF cake:
<?php
class FkuController extends Zend_Controller_Action {
var $image;
var $image_type;
public function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) {
$target_dir = APPLICATION_PATH . "/../public/1/";
$target_file = $target_dir . basename($_FILES[$html_element_name]["name"]);
//$image = new SimpleImage();
$this->load($_FILES[$html_element_name]['tmp_name']);
$this->resize($new_img_width, $new_img_height);
$this->save($target_file);
return $target_file;
//return name of saved file in case you want to store it in you database or show confirmation message to user
public 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);
}
}
public 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);
}
}
public 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);
}
}
public function getWidth() {
return imagesx($this->image);
}
public function getHeight() {
return imagesy($this->image);
}
public function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
public function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
public function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
public 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;
}
public function savepicAction() {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$this->_response->setHeader('Access-Control-Allow-Origin', '*');
$this->db = Application_Model_Db::db_load();
$ouser = $_POST['ousername'];
$fdata = 'empty';
if (isset($_FILES['picture']) && $_FILES['picture']['size'] > 0) {
$file_size = $_FILES['picture']['size'];
$tmpName = $_FILES['picture']['tmp_name'];
//Determine filetype
switch ($_FILES['picture']['type']) {
case 'image/jpeg': $ext = "jpg"; break;
case 'image/png': $ext = "png"; break;
case 'image/jpg': $ext = "jpg"; break;
case 'image/bmp': $ext = "bmp"; break;
case 'image/gif': $ext = "gif"; break;
default: $ext = ''; break;
}
if($ext) {
//if($file_size<400000) {
$img = $this->store_uploaded_image('picture', 90,82);
//$fp = fopen($tmpName, 'r');
$fp = fopen($img, 'r');
$fdata = fread($fp, filesize($tmpName));
$fdata = base64_encode($fdata);
fclose($fp);
//}
}
}
if($fdata=='empty'){
}
else {
$this->db->update('users',
array(
'picture' => $fdata,
),
array('username=?' => $ouser ));
}
}
I would suggest an easy way:
function resize($file, $width, $height) {
switch(pathinfo($file)['extension']) {
case "png": return imagepng(imagescale(imagecreatefrompng($file), $width, $height), $file);
case "gif": return imagegif(imagescale(imagecreatefromgif($file), $width, $height), $file);
default : return imagejpeg(imagescale(imagecreatefromjpeg($file), $width, $height), $file);
}
}
private function getTempImage($url, $tempName){
$tempPath = 'tempFilePath' . $tempName . '.png';
$source_image = imagecreatefrompng($url); // check type depending on your necessities.
$source_imagex = imagesx($source_image);
$source_imagey = imagesy($source_image);
$dest_imagex = 861; // My default value
$dest_imagey = 96; // My default value
$dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);
imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);
imagejpeg($dest_image, $tempPath, 100);
return $tempPath;
}
This is an adapted solution based on this great explanation. This guy made a step by step explanation.
Hope all enjoy it.
You can give a try to TinyPNG PHP library. Using this library your image gets optimized automatically during resizing process. All you need to install the library and get an API key from https://tinypng.com/developers. To install a library, run the below command.
composer require tinify/tinify
After that, your code is as follows.
require_once("vendor/autoload.php");
\Tinify\setKey("YOUR_API_KEY");
$source = \Tinify\fromFile("large.jpg"); //image to be resize
$resized = $source->resize(array(
"method" => "fit",
"width" => 150,
"height" => 100
));
$resized->toFile("thumbnail.jpg"); //resized image
I have a written a blog on the same topic http://artisansweb.net/resize-image-php-using-tinypng

Resize image in PHP

I want to write some PHP code that automatically resizes any image uploaded via a form to 147x147px, but I have no idea how to go about it (I'm a relative PHP novice).
So far, I've got images uploading successfully, filetypes being recognized and names cleaned up, but I'd like to add the resize functionality into the code. For example, I've got a test image that is 2.3MB, and 1331x1331 in dimension, and I'd like the code to size it down, which I'm guessing will dramatically compress the file size of the image, too.
So far, I've got the following:
if ($_FILES) {
//Put file properties into variables
$file_name = $_FILES['profile-image']['name'];
$file_size = $_FILES['profile-image']['size'];
$file_tmp_name = $_FILES['profile-image']['tmp_name'];
//Determine filetype
switch ($_FILES['profile-image']['type']) {
case 'image/jpeg': $ext = "jpg"; break;
case 'image/png': $ext = "png"; break;
default: $ext = ''; break;
}
if ($ext) {
//Check filesize
if ($file_size < 500000) {
//Process file - clean up filename and move to safe location
$n = "$file_name";
$n = ereg_replace("[^A-Za-z0-9.]", "", $n);
$n = strtolower($n);
$n = "avatars/$n";
move_uploaded_file($file_tmp_name, $n);
} else {
$bad_message = "Please ensure your chosen file is less than 5MB.";
}
} else {
$bad_message = "Please ensure your image is of filetype .jpg or.png.";
}
}
$query = "INSERT INTO users (image) VALUES ('$n')";
mysql_query($query) or die("Insert failed. " . mysql_error() . "<br />" . $query);
You need to use either PHP's ImageMagick or GD functions to work with images.
With GD, for example, it's as simple as...
function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
And you could call this function, like so...
$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);
From personal experience, GD's image resampling does dramatically reduce file size too, especially when resampling raw digital camera images.
Simply use PHP's GD functions (like imagescale):
Syntax:
imagescale ( $image , $new_width , $new_height )
Example:
Step: 1 Read the file
$image_name = 'path_of_Image/Name_of_Image.jpg|png|gif';
Step: 2: Load the Image File
$image = imagecreatefromjpeg($image_name); // For JPEG
//or
$image = imagecreatefrompng($image_name); // For PNG
//or
$image = imagecreatefromgif($image_name); // For GIF
Step: 3: Our Life-saver comes in '_' | Scale the image
$imgResized = imagescale($image , 500, 400); // width=500 and height = 400
// $imgResized is our final product
Note: imagescale will work for (PHP 5 >= 5.5.0, PHP 7)
Step: 4: Save the Resized image to your desired directory.
imagejpeg($imgResized, 'path_of_Image/Name_of_Image_resized.jpg'); //for jpeg
imagepng($imgResized, 'path_of_Image/Name_of_Image_resized.png'); //for png
Source : Click to Read more
This resource(broken link) is also worth considering - some very tidy code that uses GD. However, I modified their final code snippet to create this function which meets the OPs requirements...
function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) {
$target_dir = "your-uploaded-images-folder/";
$target_file = $target_dir . basename($_FILES[$html_element_name]["name"]);
$image = new SimpleImage();
$image->load($_FILES[$html_element_name]['tmp_name']);
$image->resize($new_img_width, $new_img_height);
$image->save($target_file);
return $target_file; //return name of saved file in case you want to store it in you database or show confirmation message to user
}
You will also need to include this PHP file...
<?php
/*
* File: SimpleImage.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 08/11/06
* Link: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/
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;
}
}
?>
If you dont care about the aspect ration (i.e you want to force the image to a particular dimension), here is a simplified answer
// for jpg
function resize_imagejpg($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
// for png
function resize_imagepng($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefrompng($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
// for gif
function resize_imagegif($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefromgif($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
Now let's handle the upload part.
First step, upload the file to your desired directory. Then called one of the above functions based on file type (jpg, png or gif) and pass the absolute path of your uploaded file as below:
// jpg change the dimension 750, 450 to your desired values
$img = resize_imagejpg('path/image.jpg', 750, 450);
The return value $img is a resource object. We can save to a new location or override the original as below:
// again for jpg
imagejpeg($img, 'path/newimage.jpg');
Hope this helps someone. Check these links for more on resizing Imagick::resizeImage and
imagejpeg()
I hope is will work for you.
/**
* Image re-size
* #param int $width
* #param int $height
*/
function ImageResize($width, $height, $img_name)
{
/* Get original file size */
list($w, $h) = getimagesize($_FILES['logo_image']['tmp_name']);
/*$ratio = $w / $h;
$size = $width;
$width = $height = min($size, max($w, $h));
if ($ratio < 1) {
$width = $height * $ratio;
} else {
$height = $width / $ratio;
}*/
/* Calculate new image size */
$ratio = max($width/$w, $height/$h);
$h = ceil($height / $ratio);
$x = ($w - $width / $ratio) / 2;
$w = ceil($width / $ratio);
/* set new file name */
$path = $img_name;
/* Save image */
if($_FILES['logo_image']['type']=='image/jpeg')
{
/* Get binary data from image */
$imgString = file_get_contents($_FILES['logo_image']['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
imagejpeg($tmp, $path, 100);
}
else if($_FILES['logo_image']['type']=='image/png')
{
$image = imagecreatefrompng($_FILES['logo_image']['tmp_name']);
$tmp = imagecreatetruecolor($width,$height);
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
imagecopyresampled($tmp, $image,0,0,$x,0,$width,$height,$w, $h);
imagepng($tmp, $path, 0);
}
else if($_FILES['logo_image']['type']=='image/gif')
{
$image = imagecreatefromgif($_FILES['logo_image']['tmp_name']);
$tmp = imagecreatetruecolor($width,$height);
$transparent = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
imagefill($tmp, 0, 0, $transparent);
imagealphablending($tmp, true);
imagecopyresampled($tmp, $image,0,0,0,0,$width,$height,$w, $h);
imagegif($tmp, $path);
}
else
{
return false;
}
return true;
imagedestroy($image);
imagedestroy($tmp);
}
(IMPORTANT: In the case of animation (animated webp or gif) resizing, the result will be a not animated, but resized image from the first frame! (The original animation remains intact...)
I created this to my php 7.2 project (example imagebmp sure (PHP 7 >= 7.2.0) :php/manual/function.imagebmp) about techfry.com/php-tutorial, with GD2, (so nothing 3rd party library) and very similar to the answer of Nico Bistolfi, but works with the all five basic image mimetype (png, jpeg, webp, bmp and gif), creating a new resized file, without modifying the original one, and the all stuff in one function and ready to use (copy and paste to your project). (You can set the extension of the new file with the fifth parameter, or just leave it, if you want keep the orignal):
function createResizedImage(
string $imagePath = '',
string $newPath = '',
int $newWidth = 0,
int $newHeight = 0,
string $outExt = 'DEFAULT'
) : ?string
{
if (!$newPath or !file_exists ($imagePath)) {
return null;
}
$types = [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_BMP, IMAGETYPE_WEBP];
$type = exif_imagetype ($imagePath);
if (!in_array ($type, $types)) {
return null;
}
list ($width, $height) = getimagesize ($imagePath);
$outBool = in_array ($outExt, ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']);
switch ($type) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg ($imagePath);
if (!$outBool) $outExt = 'jpg';
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng ($imagePath);
if (!$outBool) $outExt = 'png';
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif ($imagePath);
if (!$outBool) $outExt = 'gif';
break;
case IMAGETYPE_BMP:
$image = imagecreatefrombmp ($imagePath);
if (!$outBool) $outExt = 'bmp';
break;
case IMAGETYPE_WEBP:
$image = imagecreatefromwebp ($imagePath);
if (!$outBool) $outExt = 'webp';
}
$newImage = imagecreatetruecolor ($newWidth, $newHeight);
//TRANSPARENT BACKGROUND
$color = imagecolorallocatealpha ($newImage, 0, 0, 0, 127); //fill transparent back
imagefill ($newImage, 0, 0, $color);
imagesavealpha ($newImage, true);
//ROUTINE
imagecopyresampled ($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// Rotate image on iOS
if(function_exists('exif_read_data') && $exif = exif_read_data($imagePath, 'IFD0'))
{
if(isset($exif['Orientation']) && isset($exif['Make']) && !empty($exif['Orientation']) && preg_match('/(apple|ios|iphone)/i', $exif['Make'])) {
switch($exif['Orientation']) {
case 8:
if ($width > $height) $newImage = imagerotate($newImage,90,0);
break;
case 3:
$newImage = imagerotate($newImage,180,0);
break;
case 6:
$newImage = imagerotate($newImage,-90,0);
break;
}
}
}
switch (true) {
case in_array ($outExt, ['jpg', 'jpeg']): $success = imagejpeg ($newImage, $newPath);
break;
case $outExt === 'png': $success = imagepng ($newImage, $newPath);
break;
case $outExt === 'gif': $success = imagegif ($newImage, $newPath);
break;
case $outExt === 'bmp': $success = imagebmp ($newImage, $newPath);
break;
case $outExt === 'webp': $success = imagewebp ($newImage, $newPath);
}
if (!$success) {
return null;
}
return $newPath;
}
I created an easy-to-use library for image resizing. It can be found here on Github.
An example of how to use the library:
// Include PHP Image Magician library
require_once('php_image_magician.php');
// Open JPG image
$magicianObj = new imageLib('racecar.jpg');
// Resize to best fit then crop (check out the other options)
$magicianObj -> resizeImage(100, 200, 'crop');
// Save resized image as a PNG (or jpg, bmp, etc)
$magicianObj -> saveImage('racecar_small.png');
Other features, should you need them, are:
Quick and easy resize - Resize to landscape, portrait, or auto
Easy crop
Add text
Quality adjustment
Watermarking
Shadows and reflections
Transparency support
Read EXIF metadata
Borders, Rounded corners, Rotation
Filters and effects
Image sharpening
Image type conversion
BMP support
I found a mathematical way to get this job done
Github repo - https://github.com/gayanSandamal/easy-php-image-resizer
Live example - https://plugins.nayague.com/easy-php-image-resizer/
<?php
//path for the image
$source_url = '2018-04-01-1522613288.PNG';
//separate the file name and the extention
$source_url_parts = pathinfo($source_url);
$filename = $source_url_parts['filename'];
$extension = $source_url_parts['extension'];
//define the quality from 1 to 100
$quality = 10;
//detect the width and the height of original image
list($width, $height) = getimagesize($source_url);
$width;
$height;
//define any width that you want as the output. mine is 200px.
$after_width = 200;
//resize only when the original image is larger than expected with.
//this helps you to avoid from unwanted resizing.
if ($width > $after_width) {
//get the reduced width
$reduced_width = ($width - $after_width);
//now convert the reduced width to a percentage and round it to 2 decimal places
$reduced_radio = round(($reduced_width / $width) * 100, 2);
//ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places
$reduced_height = round(($height / 100) * $reduced_radio, 2);
//reduce the calculated height from the original height
$after_height = $height - $reduced_height;
//Now detect the file extension
//if the file extension is 'jpg', 'jpeg', 'JPG' or 'JPEG'
if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'JPG' || $extension == 'JPEG') {
//then return the image as a jpeg image for the next step
$img = imagecreatefromjpeg($source_url);
} elseif ($extension == 'png' || $extension == 'PNG') {
//then return the image as a png image for the next step
$img = imagecreatefrompng($source_url);
} else {
//show an error message if the file extension is not available
echo 'image extension is not supporting';
}
//HERE YOU GO :)
//Let's do the resize thing
//imagescale([returned image], [width of the resized image], [height of the resized image], [quality of the resized image]);
$imgResized = imagescale($img, $after_width, $after_height, $quality);
//now save the resized image with a suffix called "-resized" and with its extension.
imagejpeg($imgResized, $filename . '-resized.'.$extension);
//Finally frees any memory associated with image
//**NOTE THAT THIS WONT DELETE THE IMAGE
imagedestroy($img);
imagedestroy($imgResized);
}
?>
Here is an extended version of the answer #Ian Atkin' gave. I found it worked extremely well. For larger images that is :). You can actually make smaller images larger if you're not careful.
Changes:
- Supports jpg,jpeg,png,gif,bmp files
- Preserves transparency for .png and .gif
- Double checks if the the size of the original isnt already smaller
- Overrides the image given directly (Its what I needed)
So here it is. The default values of the function are the "golden rule"
function resize_image($file, $w = 1200, $h = 741, $crop = false)
{
try {
$ext = pathinfo(storage_path() . $file, PATHINFO_EXTENSION);
list($width, $height) = getimagesize($file);
// if the image is smaller we dont resize
if ($w > $width && $h > $height) {
return true;
}
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width - ($width * abs($r - $w / $h)));
} else {
$height = ceil($height - ($height * abs($r - $w / $h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w / $h > $r) {
$newwidth = $h * $r;
$newheight = $h;
} else {
$newheight = $w / $r;
$newwidth = $w;
}
}
$dst = imagecreatetruecolor($newwidth, $newheight);
switch ($ext) {
case 'jpg':
case 'jpeg':
$src = imagecreatefromjpeg($file);
break;
case 'png':
$src = imagecreatefrompng($file);
imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
imagealphablending($dst, false);
imagesavealpha($dst, true);
break;
case 'gif':
$src = imagecreatefromgif($file);
imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
imagealphablending($dst, false);
imagesavealpha($dst, true);
break;
case 'bmp':
$src = imagecreatefrombmp($file);
break;
default:
throw new Exception('Unsupported image extension found: ' . $ext);
break;
}
$result = imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
switch ($ext) {
case 'bmp':
imagewbmp($dst, $file);
break;
case 'gif':
imagegif($dst, $file);
break;
case 'jpg':
case 'jpeg':
imagejpeg($dst, $file);
break;
case 'png':
imagepng($dst, $file);
break;
}
return true;
} catch (Exception $err) {
// LOG THE ERROR HERE
return false;
}
}
ZF cake:
<?php
class FkuController extends Zend_Controller_Action {
var $image;
var $image_type;
public function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) {
$target_dir = APPLICATION_PATH . "/../public/1/";
$target_file = $target_dir . basename($_FILES[$html_element_name]["name"]);
//$image = new SimpleImage();
$this->load($_FILES[$html_element_name]['tmp_name']);
$this->resize($new_img_width, $new_img_height);
$this->save($target_file);
return $target_file;
//return name of saved file in case you want to store it in you database or show confirmation message to user
public 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);
}
}
public 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);
}
}
public 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);
}
}
public function getWidth() {
return imagesx($this->image);
}
public function getHeight() {
return imagesy($this->image);
}
public function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
public function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
public function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
public 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;
}
public function savepicAction() {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$this->_response->setHeader('Access-Control-Allow-Origin', '*');
$this->db = Application_Model_Db::db_load();
$ouser = $_POST['ousername'];
$fdata = 'empty';
if (isset($_FILES['picture']) && $_FILES['picture']['size'] > 0) {
$file_size = $_FILES['picture']['size'];
$tmpName = $_FILES['picture']['tmp_name'];
//Determine filetype
switch ($_FILES['picture']['type']) {
case 'image/jpeg': $ext = "jpg"; break;
case 'image/png': $ext = "png"; break;
case 'image/jpg': $ext = "jpg"; break;
case 'image/bmp': $ext = "bmp"; break;
case 'image/gif': $ext = "gif"; break;
default: $ext = ''; break;
}
if($ext) {
//if($file_size<400000) {
$img = $this->store_uploaded_image('picture', 90,82);
//$fp = fopen($tmpName, 'r');
$fp = fopen($img, 'r');
$fdata = fread($fp, filesize($tmpName));
$fdata = base64_encode($fdata);
fclose($fp);
//}
}
}
if($fdata=='empty'){
}
else {
$this->db->update('users',
array(
'picture' => $fdata,
),
array('username=?' => $ouser ));
}
}
I would suggest an easy way:
function resize($file, $width, $height) {
switch(pathinfo($file)['extension']) {
case "png": return imagepng(imagescale(imagecreatefrompng($file), $width, $height), $file);
case "gif": return imagegif(imagescale(imagecreatefromgif($file), $width, $height), $file);
default : return imagejpeg(imagescale(imagecreatefromjpeg($file), $width, $height), $file);
}
}
private function getTempImage($url, $tempName){
$tempPath = 'tempFilePath' . $tempName . '.png';
$source_image = imagecreatefrompng($url); // check type depending on your necessities.
$source_imagex = imagesx($source_image);
$source_imagey = imagesy($source_image);
$dest_imagex = 861; // My default value
$dest_imagey = 96; // My default value
$dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);
imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);
imagejpeg($dest_image, $tempPath, 100);
return $tempPath;
}
This is an adapted solution based on this great explanation. This guy made a step by step explanation.
Hope all enjoy it.
You can give a try to TinyPNG PHP library. Using this library your image gets optimized automatically during resizing process. All you need to install the library and get an API key from https://tinypng.com/developers. To install a library, run the below command.
composer require tinify/tinify
After that, your code is as follows.
require_once("vendor/autoload.php");
\Tinify\setKey("YOUR_API_KEY");
$source = \Tinify\fromFile("large.jpg"); //image to be resize
$resized = $source->resize(array(
"method" => "fit",
"width" => 150,
"height" => 100
));
$resized->toFile("thumbnail.jpg"); //resized image
I have a written a blog on the same topic http://artisansweb.net/resize-image-php-using-tinypng

Resize images with PHP, support PNG, JPG

I am using this class:
class ImgResizer {
function ImgResizer($originalFile = '$newName') {
$this -> originalFile = $originalFile;
}
function resize($newWidth, $targetFile) {
if (empty($newWidth) || empty($targetFile)) {
return false;
}
$src = imagecreatefromjpeg($this -> originalFile);
list($width, $height) = getimagesize($this -> originalFile);
$newHeight = ($height / $width) * $newWidth;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (file_exists($targetFile)) {
unlink($targetFile);
}
imagejpeg($tmp, $targetFile, 95);
}
}
Which works excellently, but it fails with png's, it creates a resized black image.
Is there a way to tweak this class to support png images?
function resize($newWidth, $targetFile, $originalFile) {
$info = getimagesize($originalFile);
$mime = $info['mime'];
switch ($mime) {
case 'image/jpeg':
$image_create_func = 'imagecreatefromjpeg';
$image_save_func = 'imagejpeg';
$new_image_ext = 'jpg';
break;
case 'image/png':
$image_create_func = 'imagecreatefrompng';
$image_save_func = 'imagepng';
$new_image_ext = 'png';
break;
case 'image/gif':
$image_create_func = 'imagecreatefromgif';
$image_save_func = 'imagegif';
$new_image_ext = 'gif';
break;
default:
throw new Exception('Unknown image type.');
}
$img = $image_create_func($originalFile);
list($width, $height) = getimagesize($originalFile);
$newHeight = ($height / $width) * $newWidth;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (file_exists($targetFile)) {
unlink($targetFile);
}
$image_save_func($tmp, "$targetFile.$new_image_ext");
}
I've written a class that will do just that and is nice and easy to use. It's called
PHP Image Magician
$magicianObj = new imageLib('racecar.jpg');
$magicianObj -> resizeImage(100, 200);
$magicianObj -> saveImage('racecar_convertd.png', 100);
It supports Read and Write (including converting) the following formats
jpg
png
gif
bmp
And can read only
psd's
Example
// Include PHP Image Magician library
require_once('php_image_magician.php');
// Open JPG image
$magicianObj = new imageLib('racecar.jpg');
// Resize to best fit then crop
$magicianObj -> resizeImage(100, 200, 'crop');
// Save resized image as a PNG
$magicianObj -> saveImage('racecar_small.png');
You can try this. Currently it's assuming the image will always be a jpeg. This will allow you to load a jpeg, png, or gif. I haven't tested but it should work.
function resize($newWidth, $targetFile) {
if (empty($newWidth) || empty($targetFile)) {
return false;
}
$fileHandle = #fopen($this->originalFile, 'r');
//error loading file
if(!$fileHandle) {
return false;
}
$src = imagecreatefromstring(stream_get_contents($fileHandle));
fclose($fileHandle);
//error with loading file as image resource
if(!$src) {
return false;
}
//get image size from $src handle
list($width, $height) = array(imagesx($src), imagesy($src));
$newHeight = ($height / $width) * $newWidth;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
//allow transparency for pngs
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
if (file_exists($targetFile)) {
unlink($targetFile);
}
//handle different image types.
//imagepng() uses quality 0-9
switch(strtolower(pathinfo($this->originalFile, PATHINFO_EXTENSION))) {
case 'jpg':
case 'jpeg':
imagejpeg($tmp, $targetFile, 95);
break;
case 'png':
imagepng($tmp, $targetFile, 8.5);
break;
case 'gif':
imagegif($tmp, $targetFile);
break;
}
//destroy image resources
imagedestroy($tmp);
imagedestroy($src);
}
Try this one and using this you can also save your image to specific path.
function resize($file, $imgpath, $width, $height){
/* Get original image x y*/
list($w, $h) = getimagesize($file['tmp_name']);
/* calculate new image size with ratio */
$ratio = max($width/$w, $height/$h);
$h = ceil($height / $ratio);
$x = ($w - $width / $ratio) / 2;
$w = ceil($width / $ratio);
/* new file name */
$path = $imgpath;
/* read binary data from image file */
$imgString = file_get_contents($file['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
/* Save image */
switch ($file['type']) {
case 'image/jpeg':
imagejpeg($tmp, $path, 100);
break;
case 'image/png':
imagepng($tmp, $path, 0);
break;
case 'image/gif':
imagegif($tmp, $path);
break;
default:
//exit;
break;
}
return $path;
/* cleanup memory */
imagedestroy($image);
imagedestroy($tmp);
}
Now you need to call this function while saving image as like...
<?php
//$imgpath = "Where you want to save your image";
resize($_FILES["image"], $imgpath, 340, 340);
?>
I took the P. Galbraith's version, fixed the errors and changed it to resize by area (width x height). For myself, I wanted to resize images that are too big.
function resizeByArea($originalFile,$targetFile){
$newArea = 375000; //a little more than 720 x 480
list($width,$height,$type) = getimagesize($originalFile);
$area = $width * $height;
if($area > $newArea){
if($width > $height){ $big = $width; $small = $height; }
if($width < $height){ $big = $height; $small = $width; }
$ratio = $big / $small;
$newSmall = sqrt(($newArea*$small)/$big);
$newBig = $ratio*$newSmall;
if($width > $height){ $newWidth = round($newBig, 0); $newHeight = round($newSmall, 0); }
if($width < $height){ $newWidth = round($newSmall, 0); $newHeight = round($newBig, 0); }
}
switch ($type) {
case '2':
$image_create_func = 'imagecreatefromjpeg';
$image_save_func = 'imagejpeg';
$new_image_ext = '.jpg';
break;
case '3':
$image_create_func = 'imagecreatefrompng';
// $image_save_func = 'imagepng';
// The quality is too high with "imagepng"
// but you need it if you want to allow transparency
$image_save_func = 'imagejpeg';
$new_image_ext = '.png';
break;
case '1':
$image_create_func = 'imagecreatefromgif';
$image_save_func = 'imagegif';
$new_image_ext = '.gif';
break;
default:
throw Exception('Unknown image type.');
}
$img = $image_create_func($originalFile);
$tmp = imagecreatetruecolor($newWidth,$newHeight);
imagecopyresampled( $tmp, $img, 0, 0, 0, 0,$newWidth,$newHeight, $width, $height );
ob_start();
$image_save_func($tmp);
$i = ob_get_clean();
// if file exists, create a new one with "1" at the end
if (file_exists($targetFile.$new_image_ext)){
$targetFile = $targetFile."1".$new_image_ext;
}
else{
$targetFile = $targetFile.$new_image_ext;
}
$fp = fopen ($targetFile,'w');
fwrite ($fp, $i);
fclose ($fp);
unlink($originalFile);
}
If you want to allow transparency, check this : http://www.akemapa.com/2008/07/10/php-gd-resize-transparent-image-png-gif/
I tested the function, it works fine!
the accepted answer has alot of errors here is it fixed
<?php
function resize($newWidth, $targetFile, $originalFile) {
$info = getimagesize($originalFile);
$mime = $info['mime'];
switch ($mime) {
case 'image/jpeg':
$image_create_func = 'imagecreatefromjpeg';
$image_save_func = 'imagejpeg';
$new_image_ext = 'jpg';
break;
case 'image/png':
$image_create_func = 'imagecreatefrompng';
$image_save_func = 'imagepng';
$new_image_ext = 'png';
break;
case 'image/gif':
$image_create_func = 'imagecreatefromgif';
$image_save_func = 'imagegif';
$new_image_ext = 'gif';
break;
default:
throw Exception('Unknown image type.');
}
$img = $image_create_func($originalFile);
list($width, $height) = getimagesize($originalFile);
$newHeight = ($height / $width) * $newWidth;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (file_exists($targetFile)) {
unlink($targetFile);
}
$image_save_func($tmp, "$targetFile.$new_image_ext");
}
$img=$_REQUEST['img'];
$id=$_REQUEST['id'];
// echo $img
resize(120, $_SERVER['DOCUMENT_ROOT'] ."/images/$id",$_SERVER['DOCUMENT_ROOT'] ."/images/$img") ;
?>
I know this is very old thread, but I found PHP has imagescale function built in, which does the required job. See documentation here
Example usage:
$temp = imagecreatefrompng('1.png');
$scaled_image= imagescale ( $temp, 200 , 270);
Here 200 is width and 270 is height of resized image.

PHP the proportions of image

I upload the image to my site. Image has width is 498 and height is 402.
I need to make a preview image with the established maximum width of 250px and a maximum height of 250px, but the image should be 250 to 250, and must be proportional to the width of 250 pixels.
How to do it?
EDIT
I upload images to your server. The limit on the size I want to make 250 in width and 250 in height.
This does not mean that if I upload an image 1000h500, then it must do 250x250, which means that the width we're doing 250 pixels and the height is proportional to the first dimension is 125. In the end, I should get a picture 250x125.
Second example: I have an image 100h800. I mean it should be changed
Here's a function I wrote for generating thumbnails using GD. You can pass a max width or height, or both (if zero, means unrestricted) and the thumbnail will be scaled to $dest (+ file extension) with proportions intact. It also works on transparent images. Any extra space left should be fully transparent; If you want a different background, modify $img before the imagecopyresampled() on it.
function picThumb($src, $dest, $width = 0, $height = 0, $quality = 100)
{
$srcType = exif_imagetype($src);
if (!$width && !$height)
{
$ext = image_type_to_extension($srcType, false);
copy($src, $dest . '.' . $ext);
return $ext;
}
ini_set('memory_limit', '134217728');
try
{
switch ($srcType)
{
case IMAGETYPE_JPEG:
$srcImg = imagecreatefromjpeg($src);
break;
case IMAGETYPE_PNG:
$srcImg = imagecreatefrompng($src);
break;
case IMAGETYPE_GIF:
$srcImg = imagecreatefromgif($src);
break;
default:
throw new Exception();
}
$srcWidth = imagesx($srcImg);
$srcHeight = imagesy($srcImg);
if (!$srcWidth || !$srcHeight)
{
throw new Exception();
}
if ($width && $height)
{
$ratio = min($srcWidth / $width, $srcHeight / $height);
$areaWidth = round($width * $ratio);
$areaHeight = round($height * $ratio);
$areaX = round(($srcWidth - $areaWidth) / 2);
$areaY = round(($srcHeight - $areaHeight) / 2);
}
else // if (!$width || !$height)
{
if ($width)
{
$height = round($width / $srcWidth * $srcHeight);
}
else // if ($height)
{
$width = round($height / $srcHeight * $srcWidth);
}
$areaWidth = $srcWidth;
$areaHeight = $srcHeight;
$areaX = 0;
$areaY = 0;
}
$img = imagecreatetruecolor($width, $height);
imagealphablending($img, false);
imagecopyresampled($img, $srcImg, 0, 0, $areaX, $areaY, $width, $height, $areaWidth, $areaHeight);
switch ($srcType)
{
case IMAGETYPE_JPEG:
$ext = 'jpg';
imagejpeg($img, $dest . '.' . $ext, $quality);
break;
case IMAGETYPE_PNG:
case IMAGETYPE_GIF:
$ext = 'png';
imagesavealpha($img, true);
imagepng($img, $dest . '.' . $ext, 9);
break;
default:
throw new Exception();
}
imagedestroy($srcImg);
imagedestroy($img);
}
catch (Exception $e)
{
ini_restore('memory_limit');
throw $e;
}
ini_restore('memory_limit');
return $ext;
}
I recommend to use ImageMagick class for this purposes.
Some strings of code, how to make 250x250 image and save it:
$img = new Imagick('/path/to/image/image.jpg'); //image.jpg - your file
$img->cropThumbnailImage(250, 250); //make thumbnail 250x250
$img->writeImage('/newptah/newfilename.jpg'); //write thumbnail to new path
$img->destroy(); //free resources
newfilename.jpg - would be 250x250 square without losing proportions.
you can use getimagesize function. it will return an array
$size = getimagesize($filename);
$width = $size[0];
$height => $size[1];
Then, since width of your image is greater than height, multiply the original width and height by 250/498
function makeThumbnail($image, $dest)
{
$imageType = exif_imagetype($image);
switch ($imageType)
{
case IMAGETYPE_JPEG:
$img = imagecreatefromjpeg($image);
break;
case IMAGETYPE_PNG:
$img = imagecreatefrompng($image);
break;
case IMAGETYPE_GIF:
$img = imagecreatefromgif($image);
break;
default:
throw new Im_Exception('Bad extension');
}
$width = imagesx($img);
$height = imagesy($img);
if ($height > $width)
{
$ratio = 250 / $height;
$newHeight = 250;
$newWidth = $width * $ratio;
}
else
{
$ratio = 250 / $width;
$newWidth = 250;
$newHeight = $height * $ratio;
}
$previewImg = imagecreatetruecolor($newWidth, $newHeight);
$palsize = ImageColorsTotal($img);
for ($i = 0; $i < $palsize; $i++)
{
$colors = ImageColorsForIndex($img, $i);
ImageColorAllocate($previewImg, $colors['red'], $colors['green'], $colors['blue']);
}
imagecopyresized($previewImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
switch ($imageType)
{
case IMAGETYPE_JPEG:
$ext = 'jpg';
imagejpeg($previewImg, $dest . '.' . $ext);
break;
case IMAGETYPE_PNG:
case IMAGETYPE_GIF:
$ext = 'png';
imagesavealpha($previewImg, true);
imagepng($previewImg, $dest . '.' . $ext, 9);
break;
default:
throw new Im_Exception();
}
imagedestroy($previewImg);
imagedestroy($img);
}

Categories