PHP Resize Image on or Before Upload

php resize image on or before upload

Try this code this may help you

in this variable $resizeObj = new resize('sample.png'); you need to link your uploaded picture url

Imagerezise.php

<?php

// *** Include the class
include("resize-class.php");

// *** 1) Initialise / load image
$resizeObj = new resize('sample.png');

// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
$resizeObj -> resizeImage(200, 200, 'crop');

// *** 3) Save image
$resizeObj -> saveImage('sample-resizeda.jpg', 1000);

?>

resize-class.php

<?php

# ========================================================================#
# Requires : Requires PHP5, GD library.
# Usage Example:
# include("resize_class.php");
# $resizeObj = new resize('images/cars/large/input.jpg');
# $resizeObj -> resizeImage(150, 100, 0);
# $resizeObj -> saveImage('images/cars/large/output.jpg', 100);
# ========================================================================#

class resize
{
// *** Class variables
private $image;
private $width;
private $height;
private $imageResized;

function __construct($fileName)
{
// *** Open up the file
$this->image = $this->openImage($fileName);

// *** Get width and height
$this->width = imagesx($this->image);
$this->height = imagesy($this->image);
}

## --------------------------------------------------------

private function openImage($file)
{
// *** Get extension
$extension = strtolower(strrchr($file, '.'));

switch($extension)
{
case '.jpg':
case '.jpeg':
$img = @imagecreatefromjpeg($file);
break;
case '.gif':
$img = @imagecreatefromgif($file);
break;
case '.png':
$img = @imagecreatefrompng($file);
break;
default:
$img = false;
break;
}
return $img;
}

## --------------------------------------------------------

public function resizeImage($newWidth, $newHeight, $option="auto")
{
// *** Get optimal width and height - based on $option
$optionArray = $this->getDimensions($newWidth, $newHeight, $option);

$optimalWidth = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];

// *** Resample - create image canvas of x, y size
$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);

// *** if option is 'crop', then crop too
if ($option == 'crop') {
$this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
}
}

## --------------------------------------------------------

private function getDimensions($newWidth, $newHeight, $option)
{

switch ($option)
{
case 'exact':
$optimalWidth = $newWidth;
$optimalHeight= $newHeight;
break;
case 'portrait':
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight= $newHeight;
break;
case 'landscape':
$optimalWidth = $newWidth;
$optimalHeight= $this->getSizeByFixedWidth($newWidth);
break;
case 'auto':
$optionArray = $this->getSizeByAuto($newWidth, $newHeight);
$optimalWidth = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];
break;
case 'crop':
$optionArray = $this->getOptimalCrop($newWidth, $newHeight);
$optimalWidth = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];
break;
}
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}

## --------------------------------------------------------

private function getSizeByFixedHeight($newHeight)
{
$ratio = $this->width / $this->height;
$newWidth = $newHeight * $ratio;
return $newWidth;
}

private function getSizeByFixedWidth($newWidth)
{
$ratio = $this->height / $this->width;
$newHeight = $newWidth * $ratio;
return $newHeight;
}

private function getSizeByAuto($newWidth, $newHeight)
{
if ($this->height < $this->width)
// *** Image to be resized is wider (landscape)
{
$optimalWidth = $newWidth;
$optimalHeight= $this->getSizeByFixedWidth($newWidth);
}
elseif ($this->height > $this->width)
// *** Image to be resized is taller (portrait)
{
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight= $newHeight;
}
else
// *** Image to be resizerd is a square
{
if ($newHeight < $newWidth) {
$optimalWidth = $newWidth;
$optimalHeight= $this->getSizeByFixedWidth($newWidth);
} else if ($newHeight > $newWidth) {
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight= $newHeight;
} else {
// *** Sqaure being resized to a square
$optimalWidth = $newWidth;
$optimalHeight= $newHeight;
}
}

return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}

## --------------------------------------------------------

private function getOptimalCrop($newWidth, $newHeight)
{

$heightRatio = $this->height / $newHeight;
$widthRatio = $this->width / $newWidth;

if ($heightRatio < $widthRatio) {
$optimalRatio = $heightRatio;
} else {
$optimalRatio = $widthRatio;
}

$optimalHeight = $this->height / $optimalRatio;
$optimalWidth = $this->width / $optimalRatio;

return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}

## --------------------------------------------------------

private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
{
// *** Find center - this will be used for the crop
$cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
$cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );

$crop = $this->imageResized;
//imagedestroy($this->imageResized);

// *** Now crop from center to exact requested size
$this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
}

## --------------------------------------------------------

public function saveImage($savePath, $imageQuality="100")
{
// *** Get extension
$extension = strrchr($savePath, '.');
$extension = strtolower($extension);

switch($extension)
{
case '.jpg':
case '.jpeg':
if (imagetypes() & IMG_JPG) {
imagejpeg($this->imageResized, $savePath, $imageQuality);
}
break;

case '.gif':
if (imagetypes() & IMG_GIF) {
imagegif($this->imageResized, $savePath);
}
break;

case '.png':
// *** Scale quality from 0-100 to 0-9
$scaleQuality = round(($imageQuality/100) * 9);

// *** Invert quality setting as 0 is best, not 9
$invertScaleQuality = 9 - $scaleQuality;

if (imagetypes() & IMG_PNG) {
imagepng($this->imageResized, $savePath, $invertScaleQuality);
}
break;

// ... etc

default:
// *** No extension - No save.
break;
}

imagedestroy($this->imageResized);
}

## --------------------------------------------------------

}
?>

php resize image on upload

You can use this library to manipulate the image while uploading. http://www.verot.net/php_class_upload.htm

Is this good way how to resize image before upload?

Resizing an image before uploading it; I would do that on the client-side, and you can perfectly do that by using vanilla javascript only. Think about tons of users uploading the files to your server; that would mean tons of unnecessary server load. If you can do something on the client-side and that does not impact security, I'd do it on the client side.

To do it in js, proceed via the following steps:

  • Assume you have uploaded one file to:
<input type="file" id="my-upload" />
  • Grab the upload via:
const upload = document.getElementById('my-upload').files[0]
  • Eventually check the files' MIME type and its size to respect your conditions, via upload.type and upload.size.

  • Initiate a two-dimensional Canvas, which will be needed as frame to resize your image:

let canvas = document.createElement("canvas");
let canvasContext = canvas.getContext("2d");
  • Use the FileReader API to read your file into a base64 string:
let reader = new FileReader();

// Read the contents of the file
reader.readAsDataURL(upload);

Once that conversion finished, the load event will be triggered on your FileReader object, holding the according base64 string under the result property. This is where the real fun starts:

reader.onload = function () {

// Initiate image element; needed to retrieve the originally uploaded file's
// width and height, to maintain proportions while resizing
let dummyImg = new Image(
0,
0
);

// Set the 'src' attribute of that element to your string
dummyImg.src = this.result;

// The line above causes your base64 string to be loaded into the 'img'
// element. When that process finishes, the 'load' event is triggered on
// your image

dummyImg.onload = function () {

// Get the original width and height of the uploaded file
const origWidth = dummyImg.naturalWidth;
const origHeight = dummyImg.naturalHeight;

// Calculate ratio factor to maintain aspect ratio after resizing
// You may replace '300' with your desired width in pixels
const desiredWidth = 300;

const ratio = desiredWidth / origWidth;

// Calculate the corresponding height, matching 'desiredWidth'
const correspondingHeight = ratio * origHeight;

// Set canvas' width and height according to what has been calculated
canvas.width = desiredWidth;
canvas.height = correspondingHeight;

// Draw the image into the canvas
canvasContext.drawImage(
dummyImg,
0,
0,
desiredWidth,
correspondingHeight
);

// Convert resized image back to base64 string
const resizedImage = canvas.toDataURL(
upload.type,
1.0 // quality. change this to a value < 1.0 for mime types that allow
// lossy compression, such as jpeg, to allow for further compression
// (with quality loss though). On file types that do not allow for
// lossy compression, this value will have no effect.
);

// 'resizedImage' will be the base64 string representation of your
// uploaded file, resized based on a width of 300 pixels,
// conserving the aspect ratio. You can now simply submit that to your
// server, as PHP works pretty well with base64 strings when it comes to
// file contents.

// Note that you do not need formData for this anymore, now that
// you're working with a simple (base64) string; you can easily
// submit the data as simple string to the server. So try to
// simply submit the value 'resizedImage' to your server HERE,
// just like you would submit any other string, and grab it on
// your server side like you would do it with any other string

// If you bind this code as change listener to your upload element
// , I would store the value of 'resizedImage' in a variable,
// which you then submit to the server upon form submit. I
// leave that decision up to you.

}

}

CONCRETE IMPLEMENTATION

// Initiate storage variable for resized image
var resizedFile;

function resizeImage() {

const upload = document.getElementById('your-upload').files[0];

let canvas = document.createElement("canvas");
let canvasContext = canvas.getContext("2d");

let reader = new FileReader();

reader.readAsDataURL(upload);

reader.onload = function () {

let dummyImg = new Image(
0,
0
);

dummyImg.src = this.result;

dummyImg.onload = function () {

const origWidth = dummyImg.naturalWidth;
const origHeight = dummyImg.naturalHeight;

const desiredWidth = 300;

const ratio = desiredWidth / origWidth;

const correspondingHeight = ratio * origHeight;

canvas.width = desiredWidth;
canvas.height = correspondingHeight;

canvasContext.drawImage(
dummyImg,
0,
0,
desiredWidth,
correspondingHeight
);

const resizedImage = canvas.toDataURL(
upload.type,
1.0
);

// If you bind this code as change listener to your upload element
// , I would store the value of 'resizedImage' in a variable,
// which you then submit to the server upon form submit. I
// leave that decision up to you. Personally, I prefer storing
// the obtained base64 string in a variable, and then post to
// the server on submit.
resizedFile = resizedImage;

}

}

}

// Attach as change listener to your <input type="file" id="your-upload"/> element, such that it reacts everytime you upload a file

document.getElementById('your-upload').addEventListener('change',resizeImage);

PHP upload and resize image

You can use the PHP GD library to resize an image on upload.

The following code should give you an idea of how to implement the resize:

// Get the image info from the photo
$image_info = getimagesize($photo);
$width = $new_width = $image_info[0];
$height = $new_height = $image_info[1];
$type = $image_info[2];

// Load the image
switch ($type)
{
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($photo);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($photo);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($photo);
break;
default:
die('Error loading '.$photo.' - File type '.$type.' not supported');
}

// Create a new, resized image
$new_width = 180;
$new_height = $height / ($width / $new_width);
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Save the new image over the top of the original photo
switch ($type)
{
case IMAGETYPE_JPEG:
imagejpeg($new_image, $photo, 100);
break;
case IMAGETYPE_GIF:
imagegif($new_image, $photo);
break;
case IMAGETYPE_PNG:
imagepng($new_image, $photo);
break;
default:
die('Error saving image: '.$photo);
}

Resize image before uploading PHP

Here is the code I'm using to resize images.

In my case I give to the function the original file name and then the thumbnail file name.

You can adapt it for your case very easily.

public static function GenerateThumbnail($im_filename,$th_filename,$max_width,$max_height,$quality = 0.75)
{
// The original image must exist
if(is_file($im_filename))
{
// Let's create the directory if needed
$th_path = dirname($th_filename);
if(!is_dir($th_path))
mkdir($th_path, 0777, true);
// If the thumb does not aleady exists
if(!is_file($th_filename))
{
// Get Image size info
list($width_orig, $height_orig, $image_type) = @getimagesize($im_filename);
if(!$width_orig)
return 2;
switch($image_type)
{
case 1: $src_im = @imagecreatefromgif($im_filename); break;
case 2: $src_im = @imagecreatefromjpeg($im_filename); break;
case 3: $src_im = @imagecreatefrompng($im_filename); break;
}
if(!$src_im)
return 3;

$aspect_ratio = (float) $height_orig / $width_orig;

$thumb_height = $max_height;
$thumb_width = round($thumb_height / $aspect_ratio);
if($thumb_width > $max_width)
{
$thumb_width = $max_width;
$thumb_height = round($thumb_width * $aspect_ratio);
}

$width = $thumb_width;
$height = $thumb_height;

$dst_img = @imagecreatetruecolor($width, $height);
if(!$dst_img)
return 4;
$success = @imagecopyresampled($dst_img,$src_im,0,0,0,0,$width,$height,$width_orig,$height_orig);
if(!$success)
return 4;
switch ($image_type)
{
case 1: $success = @imagegif($dst_img,$th_filename); break;
case 2: $success = @imagejpeg($dst_img,$th_filename,intval($quality*100)); break;
case 3: $success = @imagepng($dst_img,$th_filename,intval($quality*9)); break;
}
if(!$success)
return 4;
}
return 0;
}
return 1;
}

The return codes are just here to differentiate between different types of errors.

By looking back at that code, I don't like the "magic number" trick. I'm gonna have to change that (by exceptions for example).

if (!empty($_FILES["pic$index"]["name"])) {
$ext = substr($_FILES["pic$index"]["name"], strrpos($_FILES["pic$index"]["name"], '.') + 1);
$dir = "../gallery/$mkdir";
// Move it
if(move_uploaded_file($_FILES["pic$index"]["tmp_name"] , "$dir/img-$index.$ext.tmp"))
{
// Resize it
GenerateThumbnail("$dir/img-$index.$ext.tmp","$dir/img-$index.$ext",600,800,0.80);
// Delete full size
unlink("$dir/img-$index.$ext.tmp");
}
}

Use move_uploaded_file to move it (recommanded) and then you can resize it and send it to it's final destination. You might not even need the ".tmp", you can use.

    // Move it
if(move_uploaded_file($_FILES["pic$index"]["tmp_name"] , "$dir/img-$index.$ext"))
// Resize it
GenerateThumbnail("$dir/img-$index.$ext","$dir/img-$index.$ext",600,800);


Related Topics



Leave a reply



Submit