I\'m wanting to write some PHP code which 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
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
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;
}
}
?>
Simple Use PHP function (imagescale):
Syntax:
imagescale ( $image , $new_width , $new_height )
Example:
Step: 1 Read the file
$image_name = 'path_of_Image/Name_of_Image.jpg|png';
Step: 2: Load the Image File
$image = imagecreatefromjpeg($image_name); // For JPEG
//or
$image = imagecreatefrompng($image_name); // For PNG
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 works for (PHP 5 >= 5.5.0, PHP 7)
Source : Click to Read more
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 ));
}
}
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.
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;
}
}