Optimal image scaling - php

I would like to ask for help in optimizing the image. I made a class where I call the function, working perfectly, just when I upload my profile picture I want to cut it into a square (800x800) and make it as optimal as possible from the center of the original picture. I don't want to use extra scripts, rather upload an optimally cropped image.
Imagecopyresampled proper parameter drop is the key :), I googled and watched videos but couldn't fix it properly or it either shifted the image or it wasn't in or distorted. I probably miscalculated the coordinates of the image.
function createthumb($name, $filename, $new_w, $new_h) {
try{
$system = explode(".", $name);
$tipus = $system[count($system)-1];
$tipus = strtolower($tipus);
$vizjel_fajl = "assets/img/watermark.png";
$vizjel_kep = imagecreatefrompng($vizjel_fajl);
if (($tipus == 'jpg') || ($tipus == 'jpeg')){
$src_img = imagecreatefromjpeg($name);
}
if ($tipus == 'gif'){
$src_img = imagecreatefromgif($name);
}
if ($tipus == 'png'){
$src_img = imagecreatefrompng($name);
}
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);
$vizjel_szelesseg = imagesx($vizjel_kep);
$vizjel_magassag = imagesy($vizjel_kep);
$szelesseg_szorzo = $old_x / $vizjel_szelesseg;
$magassag_szorzo = $old_y / $vizjel_magassag;
if (($szelesseg_szorzo) >= ($magassag_szorzo)){
$aktual_szorzo = $magassag_szorzo;
} else {
$aktual_szorzo = $szelesseg_szorzo;
}
$vizjel_x = intval(($old_x - ($aktual_szorzo * $vizjel_szelesseg)) / 3);
$vizjel_y = intval(($old_y - ($aktual_szorzo * $vizjel_magassag)) / 1);
$vizjel_w = intval($aktual_szorzo * $vizjel_szelesseg);
$vizjel_h = intval($aktual_szorzo * $vizjel_magassag);
if($old_x > $old_y && $this->type != 'user'){
$thumb_w = $new_w;
$thumb_h = $old_y * ($new_h / $old_x);
}
if($old_x < $old_y && $this->type != 'user') {
$thumb_w = $old_x * ($new_w / $old_y);
$thumb_h = $new_h;
}
if($old_x == $old_y){
$thumb_w = $new_w;
$thumb_h = $new_h;
}
if($this->type == 'user'){
$thumb_w = 800;
$thumb_h = 800;
}
$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
imagealphablending($dst_img, false);
imagesavealpha($dst_img, true);
$transparent = imagecolorallocatealpha($dst_img, 0, 0, 0, 127);
imagefilledrectangle($dst_img, 0, 0, $thumb_w, $thumb_h, $transparent);
imagecopyresampled($src_img, $vizjel_kep, $vizjel_x, $vizjel_y, 0, 0, $vizjel_w, $vizjel_h, $vizjel_szelesseg, $vizjel_magassag);
imagecopyresampled( $dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y );
if ((preg_match( "/png/", $system[1])) || (preg_match("/gif/", $system[1]))){
imagepng($dst_img, $filename, 1);
}else{
imagejpeg($dst_img, $filename);
}
imagedestroy($dst_img);
if (!unlink($this->target_dir.$this->name)) {
throw new userException('','Hiba a törlés során ->'. $this->name,451);
}
}
catch (userException $e){
$e->handleException();
}
}

Welcome LGB,
your function is not clear, I see some variables that not defined, please next time attach all of the codes.
this code returns exactly the center of the original image 800x800
<?php
//image path
$im = imagecreatefromjpeg('Images/baby.jpg');
// find the size of image
$size = min(imagesx($im), imagesy($im));
//calculate X position
if(imagesx($im) < 800){$xPos = 0;}
else{$xPos = floor((imagesx($im) - 800) / 2);}
//calculate Y position
if(imagesy($im) < 800){$yPos = 0;}
else{$yPos = floor((imagesy($im) - 800) / 2);}
//set the crop image size
$im2 = imagecrop($im, ['x' => $xPos, 'y' => $yPos, 'width' => 800, 'height' => 800]);
if ($im2 !== FALSE) {
header("Content-type: image/jpg");
imagejpeg($im2);
imagedestroy($im2);
}
imagedestroy($im);
?>
I'm guessing that your point is in this part:
//calculate X position
if(imagesx($im) < 800){$xPos = 0;}
else{$xPos = floor((imagesx($im) - 800) / 2);}
//calculate Y position
if(imagesy($im) < 800){$yPos = 0;}
else{$yPos = floor((imagesy($im) - 800) / 2);}

Related

Add metadata to image using GD

I have image uploaded on the server in jpg format, everytime browser request a image if image not exist in webp i resize and conver image into webp format.
Since here everything work fine but new converted image (webp) is missing metadata like author, copyright, comment .... from original image.
Is there any way to add medatata from original image to converted (webp) image during resizing or converting ?
this is my code
$image = new Image(DIR_IMAGE . $old_image);
$image->resize($width, $height);
$image->save_webp(DIR_IMAGE . $new_image_webp, $quality);
public function resize($width = 0, $height = 0, $default = '') {
if (!$this->info['width'] || !$this->info['height']) {
return;
}
$xpos = 0;
$ypos = 0;
$scale = 1;
$scale_w = $width / $this->info['width'];
$scale_h = $height / $this->info['height'];
if ($default == 'w') {
$scale = $scale_w;
} elseif ($default == 'h') {
$scale = $scale_h;
} else {
$scale = min($scale_w, $scale_h);
}
if ($scale == 1 && $scale_h == $scale_w && $this->info['mime'] != 'image/png') {
return;
}
$new_width = (int)($this->info['width'] * $scale);
$new_height = (int)($this->info['height'] * $scale);
$xpos = (int)(($width - $new_width) / 2);
$ypos = (int)(($height - $new_height) / 2);
$image_old = $this->image;
$this->image = imagecreatetruecolor($width, $height);
if (isset($this->info['mime']) && $this->info['mime'] == 'image/png') {
imagealphablending($this->image, false);
imagesavealpha($this->image, true);
$background = imagecolorallocatealpha($this->image, 255, 255, 255, 127);
imagecolortransparent($this->image, $background);
} else {
$background = imagecolorallocate($this->image, 255, 255, 255);
}
imagefilledrectangle($this->image, 0, 0, $width, $height, $background);
imagecopyresampled($this->image, $image_old, $xpos, $ypos, 0, 0, $new_width, $new_height, $this->info['width'], $this->info['height']);
imagedestroy($image_old);
$this->info['width'] = $width;
$this->info['height'] = $height;
}
public function save_webp($file, $quality = 40) {
if (is_resource($this->image)) {
imagewebp($this->image, $file, $quality);
imagedestroy($this->image);
}
}

Create square 1:1 thumbnail in PHP

How can I set this code to return images in 1:1 (square)?
The purpose is to create a square (non stretched) thumbnail.
I've tried making changes in the 'if section'. I get a square image but stretched. I want it to be cropped.
define('THUMBNAIL_IMAGE_MAX_WIDTH', 150);
define('THUMBNAIL_IMAGE_MAX_HEIGHT', 150);
$source_image_path = {here the source filename};
$thumbnail_image_path = {here de thumb filename};
list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image_path);
switch ($source_image_type) {
case IMAGETYPE_GIF:
$source_gd_image = imagecreatefromgif($source_image_path);
break;
case IMAGETYPE_JPEG:
$source_gd_image = imagecreatefromjpeg($source_image_path);
break;
case IMAGETYPE_PNG:
$source_gd_image = imagecreatefrompng($source_image_path);
break;
}
$source_aspect_ratio = $source_image_width / $source_image_height;
$thumbnail_aspect_ratio = THUMBNAIL_IMAGE_MAX_WIDTH / THUMBNAIL_IMAGE_MAX_HEIGHT;
if ($source_image_width <= THUMBNAIL_IMAGE_MAX_WIDTH && $source_image_height <= THUMBNAIL_IMAGE_MAX_HEIGHT) {
$thumbnail_image_width = $source_image_width;
$thumbnail_image_height = $source_image_height;
} elseif ($thumbnail_aspect_ratio > $source_aspect_ratio) {
$thumbnail_image_width = (int) (THUMBNAIL_IMAGE_MAX_HEIGHT * $source_aspect_ratio);
$thumbnail_image_height = THUMBNAIL_IMAGE_MAX_HEIGHT;
} else {
$thumbnail_image_width = THUMBNAIL_IMAGE_MAX_WIDTH;
$thumbnail_image_height = (int) (THUMBNAIL_IMAGE_MAX_WIDTH / $source_aspect_ratio);
}
$thumbnail_gd_image = imagecreatetruecolor($thumbnail_image_width, $thumbnail_image_height);
imagecopyresampled($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height);
imagejpeg($thumbnail_gd_image, $thumbnail_image_path, 90);
PS. It's not a duplicate, I've read several questions of this topic, but I'm unable to integrate it whit my code.
This function did the trick
function crop_img($imgSrc){
//getting the image dimensions
list($width, $height) = getimagesize($imgSrc);
//saving the image into memory (for manipulation with GD Library)
$myImage = imagecreatefromjpeg($imgSrc);
// calculating the part of the image to use for thumbnail
if ($width > $height) {
$y = 0;
$x = ($width - $height) / 2;
$smallestSide = $height;
} else {
$x = 0;
$y = ($height - $width) / 2;
$smallestSide = $width;
}
// copying the part into thumbnail
$thumbSize = min($width,$height);
$thumb = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);
unlink($imgSrc);
imagejpeg($thumb,$imgSrc);
#imagedestroy($myImage);
#imagedestroy($thumb);
}
Found in: PHP crop image to fix width and height without losing dimension ratio
Use this code this code uploads image to folder and renames the file and thumb will be created with same name
HTML
<INPUT NAME="userfile[]" TYPE="file">
image directory "upimg/"
thumb directory thimg
php processing
$rename = md5(rand() * time());
$add = "upimg/" . $rename . $_FILES['userfile']['name'];
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $add)) {
echo "Successfully uploaded the image";
chmod("$add", 0777);
} else {
exit;
}
$n_width = 200;
$n_height = 200;
$tsrc = "thimg/" . $rename . $_FILES['userfile']['name'];
if (!($_FILES['userfile']['type'] == "image/jpeg" OR $_FILES['userfile']['type'] == "image/gif")) {
exit;
}
if ($_FILES['userfile']['type'] == "image/gif") {
$im = ImageCreateFromGIF($add);
$width = ImageSx($im);
$height = ImageSy($im);
$newimage = imagecreatetruecolor($n_width, $n_height);
imageCopyResized($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
if (function_exists("imagegif")) {
Header("Content-type: image/gif");
ImageGIF($newimage, $tsrc);
} elseif (function_exists("imagejpeg")) {
Header("Content-type: image/jpeg");
ImageJPEG($newimage, $tsrc);
}
chmod("$tsrc", 0777);
}
if ($_FILES['userfile']['type'] == "image/jpeg") {
$im = ImageCreateFromJPEG($add);
$width = ImageSx($im);
$height = ImageSy($im);
$newimage = imagecreatetruecolor($n_width, $n_height);
imageCopyResized($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
ImageJpeg($newimage, $tsrc);
chmod("$tsrc", 0777);
}

PHP - Create Thumbnail & maintaining aspect ratio

EDIT: This can be easily done in CSS, I didn't know CSS much at the time of writing this
I have created a thumbnail creator using PHP. The thumbnails generated should be of the same size. But the problem is the use of uploads images having different aspect ratio like landscape or portrait the thumbnail becomes ugly. So I created the picture above for clarification. Whatever be the uploaded image, it will be put into a rectangle image. So the aspect ratio doesn't change and thumbnails will be of the same size. Can anyone pls help me or tell some ideas?
define('THUMBNAIL_IMAGE_MAX_WIDTH', 150);
define('THUMBNAIL_IMAGE_MAX_HEIGHT', 150);
function generate_image_thumbnail($source_image_path, $thumbnail_image_path)
{
list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image_path);
switch ($source_image_type) {
case IMAGETYPE_GIF:
$source_gd_image = imagecreatefromgif($source_image_path);
break;
case IMAGETYPE_JPEG:
$source_gd_image = imagecreatefromjpeg($source_image_path);
break;
case IMAGETYPE_PNG:
$source_gd_image = imagecreatefrompng($source_image_path);
break;
}
if ($source_gd_image === false) {
return false;
}
$source_aspect_ratio = $source_image_width / $source_image_height;
$thumbnail_aspect_ratio = THUMBNAIL_IMAGE_MAX_WIDTH / THUMBNAIL_IMAGE_MAX_HEIGHT;
if ($source_image_width <= THUMBNAIL_IMAGE_MAX_WIDTH && $source_image_height <= THUMBNAIL_IMAGE_MAX_HEIGHT) {
$thumbnail_image_width = $source_image_width;
$thumbnail_image_height = $source_image_height;
} elseif ($thumbnail_aspect_ratio > $source_aspect_ratio) {
$thumbnail_image_width = (int) (THUMBNAIL_IMAGE_MAX_HEIGHT * $source_aspect_ratio);
$thumbnail_image_height = THUMBNAIL_IMAGE_MAX_HEIGHT;
} else {
$thumbnail_image_width = THUMBNAIL_IMAGE_MAX_WIDTH;
$thumbnail_image_height = (int) (THUMBNAIL_IMAGE_MAX_WIDTH / $source_aspect_ratio);
}
$thumbnail_gd_image = imagecreatetruecolor($thumbnail_image_width, $thumbnail_image_height);
imagecopyresampled($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height);
$img_disp = imagecreatetruecolor(THUMBNAIL_IMAGE_MAX_WIDTH,THUMBNAIL_IMAGE_MAX_WIDTH);
$backcolor = imagecolorallocate($img_disp,0,0,0);
imagefill($img_disp,0,0,$backcolor);
imagecopy($img_disp, $thumbnail_gd_image, (imagesx($img_disp)/2)-(imagesx($thumbnail_gd_image)/2), (imagesy($img_disp)/2)-(imagesy($thumbnail_gd_image)/2), 0, 0, imagesx($thumbnail_gd_image), imagesy($thumbnail_gd_image));
imagejpeg($img_disp, $thumbnail_image_path, 90);
imagedestroy($source_gd_image);
imagedestroy($thumbnail_gd_image);
imagedestroy($img_disp);
return true;
}
generate_image_thumbnail('original_image.jpg', 'thumb_image.jpg'); //call the function
with that code, you will get something similar to
Look at the source code of my Mr Thumb Image Resizing. :)
public function proportion($max_width, $max_height) {
if (!( $this->halt )) {
if ($this->image['extension'] == 'gif') {
$this->image['ratio'] = ( $this->image['width'] > $this->image['height'] ) ? $max_width / $this->image['width'] : $max_height / $this->image['height'];
if ($this->image['width'] > $max_width || $this->image['height'] > $max_height) {
$new_width = $this->image['width'] * $this->image['ratio'];
$new_height = $this->image['height'] * $this->image['ratio'];
} else {
$new_width = $this->image['width'];
$new_height = $this->image['height'];
}
$this->image['composite'] = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($this->image['composite'], $this->image['render'], 0, 0, 0, 0, $new_width, $new_height, $this->image['width'], $this->image['height']);
$this->image['colorcount'] = imagecolorstotal($this->image['render']);
imagetruecolortopalette($this->image['composite'], true, $this->image['colorcount']);
imagepalettecopy($this->image['composite'], $this->image['render']);
$this->image['transparentcolor'] = imagecolortransparent($this->image['render']);
imagefill($this->image['composite'], 0, 0, $this->image['transparentcolor']);
imagecolortransparent($this->image['composite'], $this->image['transparentcolor']);
} else {
$this->image['ratio'] = ( $this->image['width'] > $this->image['height'] ) ? $max_width / $this->image['width'] : $max_height / $this->image['height'];
if ($this->image['width'] > $max_width || $this->image['height'] > $max_height) {
$new_width = $this->image['width'] * $this->image['ratio'];
$new_height = $this->image['height'] * $this->image['ratio'];
} else {
$new_width = $this->image['width'];
$new_height = $this->image['height'];
}
$this->image['composite'] = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($this->image['composite'], $this->image['render'], 0, 0, 0, 0, $new_width, $new_height, $this->image['width'], $this->image['height']);
}
} else {
echo 'Execution halted!';
}
}
Here's a function that might help you out. You tell it the width you want to maintain, and it will preserve the aspect ratio while also producing a thumbnail.
public static function makeThumb($src, $dest, $desired_width, $format = 'image/jpeg')
{
/* read the source image */
$source_image = null;
if($format == 'image/jpeg')
{
$source_image = imagecreatefromjpeg($src);
}
else if($format == 'image/png')
{
$source_image = imagecreatefrompng($src);
}
$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" of this thumbnail, relative to the desired width */
$desired_height = floor($height * ($desired_width / $width));
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
imageAlphaBlending($virtual_image, false);
imageSaveAlpha($virtual_image, true);
/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
/* create the physical thumbnail image to its destination */
if($format == 'image/jpeg')
{
imagejpeg($virtual_image, $dest);
}
else if($format == 'image/png')
{
imagepng($virtual_image, $dest);
}
}
Use ImageMagick API .Check out this
define('THUMB_WIDTH', 60);
define('THUMB_HEIGHT', 80);
define('MAGICK_PATH','/usr/local/bin/');
function makeThumbnail($in, $out) {
$width = THUMB_WIDTH;
$height = THUMB_HEIGHT;
list($w,$h) = getimagesize($in);
$thumbRatio = $width/$height;
$inRatio = $w/$h;
$isLandscape = $inRatio > $thumbRatio;
$size = ($isLandscape ? '1000x'.$height : $width.'x1000');
$xoff = ($isLandscape ? floor((($inRatio*$height)-$width)/2) : 0);
$command = MAGICK_PATH."convert $in -resize $size -crop {$width}x{$height}+{$xoff}+0 ".
"-colorspace RGB -strip -quality 90 $out";
exec($command);
}
Refer to this link - http://coffeeshopped.com/2009/01/creating-image-thumbnails-using-php-and-imagemagick or http://in1.php.net/manual/en/class.imagick.php

Image resize with php [duplicate]

This question already has answers here:
Resize image in PHP
(13 answers)
Closed 6 years ago.
function resize($originalImage){
list($width, $height) = getimagesize($originalImage);
$newName=basename($originalImage);
$imageResized = imagecreatetruecolor(128, 128);
$imageTmp = imagecreatefromjpeg ($originalImage);
imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, 128, 128, $width, $height);
imagejpeg($imageResized, "resizedImg/$newName",100);
imageDestroy($imageResized);
}
The script returns the image with the correct name but it's just black? Any ideas?
If you have trouble with image resizing use this code for it. Do the modifications as you need it.
function resizeImage($file){
define ('MAX_WIDTH', 1500);//max image width
define ('MAX_HEIGHT', 1500);//max image height
define ('MAX_FILE_SIZE', 10485760);
//iamge save path
$path = 'storeResize/';
//size of the resize image
$new_width = 128;
$new_height = 128;
//name of the new image
$nameOfFile = 'resize_'.$new_width.'x'.$new_height.'_'.basename($file['name']);
$image_type = $file['type'];
$image_size = $file['size'];
$image_error = $file['error'];
$image_file = $file['tmp_name'];
$image_name = $file['name'];
$image_info = getimagesize($image_file);
//check image type
if ($image_info['mime'] == 'image/jpeg' or $image_info['mime'] == 'image/jpg'){
}
else if ($image_info['mime'] == 'image/png'){
}
else if ($image_info['mime'] == 'image/gif'){
}
else{
//set error invalid file type
}
if ($image_error){
//set error image upload error
}
if ( $image_size > MAX_FILE_SIZE ){
//set error image size invalid
}
switch ($image_info['mime']) {
case 'image/jpg': //This isn't a valid mime type so we should probably remove it
case 'image/jpeg':
$image = imagecreatefromjpeg ($image_file);
break;
case 'image/png':
$image = imagecreatefrompng ($image_file);
break;
case 'image/gif':
$image = imagecreatefromgif ($image_file);
break;
}
if ($new_width == 0 && $new_height == 0) {
$new_width = 100;
$new_height = 100;
}
// ensure size limits can not be abused
$new_width = min ($new_width, MAX_WIDTH);
$new_height = min ($new_height, MAX_HEIGHT);
//get original image h/w
$width = imagesx ($image);
$height = imagesy ($image);
//$align = 'b';
$zoom_crop = 1;
$origin_x = 0;
$origin_y = 0;
//TODO setting Memory
// generate new w/h if not provided
if ($new_width && !$new_height) {
$new_height = floor ($height * ($new_width / $width));
} else if ($new_height && !$new_width) {
$new_width = floor ($width * ($new_height / $height));
}
// scale down and add borders
if ($zoom_crop == 3) {
$final_height = $height * ($new_width / $width);
if ($final_height > $new_height) {
$new_width = $width * ($new_height / $height);
} else {
$new_height = $final_height;
}
}
// create a new true color image
$canvas = imagecreatetruecolor ($new_width, $new_height);
imagealphablending ($canvas, false);
if (strlen ($canvas_color) < 6) {
$canvas_color = 'ffffff';
}
$canvas_color_R = hexdec (substr ($canvas_color, 0, 2));
$canvas_color_G = hexdec (substr ($canvas_color, 2, 2));
$canvas_color_B = hexdec (substr ($canvas_color, 2, 2));
// Create a new transparent color for image
$color = imagecolorallocatealpha ($canvas, $canvas_color_R, $canvas_color_G, $canvas_color_B, 127);
// Completely fill the background of the new image with allocated color.
imagefill ($canvas, 0, 0, $color);
// scale down and add borders
if ($zoom_crop == 2) {
$final_height = $height * ($new_width / $width);
if ($final_height > $new_height) {
$origin_x = $new_width / 2;
$new_width = $width * ($new_height / $height);
$origin_x = round ($origin_x - ($new_width / 2));
} else {
$origin_y = $new_height / 2;
$new_height = $final_height;
$origin_y = round ($origin_y - ($new_height / 2));
}
}
// Restore transparency blending
imagesavealpha ($canvas, true);
if ($zoom_crop > 0) {
$src_x = $src_y = 0;
$src_w = $width;
$src_h = $height;
$cmp_x = $width / $new_width;
$cmp_y = $height / $new_height;
// calculate x or y coordinate and width or height of source
if ($cmp_x > $cmp_y) {
$src_w = round ($width / $cmp_x * $cmp_y);
$src_x = round (($width - ($width / $cmp_x * $cmp_y)) / 2);
} else if ($cmp_y > $cmp_x) {
$src_h = round ($height / $cmp_y * $cmp_x);
$src_y = round (($height - ($height / $cmp_y * $cmp_x)) / 2);
}
// positional cropping!
if ($align) {
if (strpos ($align, 't') !== false) {
$src_y = 0;
}
if (strpos ($align, 'b') !== false) {
$src_y = $height - $src_h;
}
if (strpos ($align, 'l') !== false) {
$src_x = 0;
}
if (strpos ($align, 'r') !== false) {
$src_x = $width - $src_w;
}
}
// positional cropping!
imagecopyresampled ($canvas, $image, $origin_x, $origin_y, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h);
} else {
imagecopyresampled ($canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
}
//Straight from Wordpress core code. Reduces filesize by up to 70% for PNG's
if ( (IMAGETYPE_PNG == $image_info[2] || IMAGETYPE_GIF == $image_info[2]) && function_exists('imageistruecolor') && !imageistruecolor( $image ) && imagecolortransparent( $image ) > 0 ){
imagetruecolortopalette( $canvas, false, imagecolorstotal( $image ) );
}
$quality = 100;
$nameOfFile = 'resize_'.$new_width.'x'.$new_height.'_'.basename($file['name']);
if (preg_match('/^image\/(?:jpg|jpeg)$/i', $image_info['mime'])){
imagejpeg($canvas, $path.$nameOfFile, $quality);
} else if (preg_match('/^image\/png$/i', $image_info['mime'])){
imagepng($canvas, $path.$nameOfFile, floor($quality * 0.09));
} else if (preg_match('/^image\/gif$/i', $image_info['mime'])){
imagegif($canvas, $path.$nameOfFile);
}
}

PHP/GD - Cropping and Resizing Images

I've coded a function that crops an image to a given aspect ratio and finally then resizes it and outputs it as JPG:
<?php
function Image($image, $crop = null, $size = null)
{
$image = ImageCreateFromString(file_get_contents($image));
if (is_resource($image) === true)
{
$x = 0;
$y = 0;
$width = imagesx($image);
$height = imagesy($image);
/*
CROP (Aspect Ratio) Section
*/
if (is_null($crop) === true)
{
$crop = array($width, $height);
}
else
{
$crop = array_filter(explode(':', $crop));
if (empty($crop) === true)
{
$crop = array($width, $height);
}
else
{
if ((empty($crop[0]) === true) || (is_numeric($crop[0]) === false))
{
$crop[0] = $crop[1];
}
else if ((empty($crop[1]) === true) || (is_numeric($crop[1]) === false))
{
$crop[1] = $crop[0];
}
}
$ratio = array
(
0 => $width / $height,
1 => $crop[0] / $crop[1],
);
if ($ratio[0] > $ratio[1])
{
$width = $height * $ratio[1];
$x = (imagesx($image) - $width) / 2;
}
else if ($ratio[0] < $ratio[1])
{
$height = $width / $ratio[1];
$y = (imagesy($image) - $height) / 2;
}
/*
How can I skip (join) this operation
with the one in the Resize Section?
*/
$result = ImageCreateTrueColor($width, $height);
if (is_resource($result) === true)
{
ImageSaveAlpha($result, true);
ImageAlphaBlending($result, false);
ImageFill($result, 0, 0, ImageColorAllocateAlpha($result, 255, 255, 255, 127));
ImageCopyResampled($result, $image, 0, 0, $x, $y, $width, $height, $width, $height);
$image = $result;
}
}
/*
Resize Section
*/
if (is_null($size) === true)
{
$size = array(imagesx($image), imagesy($image));
}
else
{
$size = array_filter(explode('x', $size));
if (empty($size) === true)
{
$size = array(imagesx($image), imagesy($image));
}
else
{
if ((empty($size[0]) === true) || (is_numeric($size[0]) === false))
{
$size[0] = round($size[1] * imagesx($image) / imagesy($image));
}
else if ((empty($size[1]) === true) || (is_numeric($size[1]) === false))
{
$size[1] = round($size[0] * imagesy($image) / imagesx($image));
}
}
}
$result = ImageCreateTrueColor($size[0], $size[1]);
if (is_resource($result) === true)
{
ImageSaveAlpha($result, true);
ImageAlphaBlending($result, true);
ImageFill($result, 0, 0, ImageColorAllocate($result, 255, 255, 255));
ImageCopyResampled($result, $image, 0, 0, 0, 0, $size[0], $size[1], imagesx($image), imagesy($image));
header('Content-Type: image/jpeg');
ImageInterlace($result, true);
ImageJPEG($result, null, 90);
}
}
return false;
}
?>
The function works as expected but I'm creating a non-required GD image resource, how can I fix it? I've tried joining both calls but I must be doing some miscalculations.
<?php
/*
Usage Examples
*/
Image('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png', '1:1', '600x');
Image('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png', '2:1', '600x');
Image('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png', '2:', '250x300');
?>
Any help is greatly appreciated, thanks.
You will have to modify your resizing code not to be based on the cropped image to start with. Since you want to do the cropping and resizing in one go you need to calculate it independently.
<?php
function Image($image, $crop = ':', $size = null) {
$image = ImageCreateFromString(file_get_contents($image));
if (is_resource($image)) {
$x = 0;
$y = 0;
$width = imagesx($image);
$height = imagesy($image);
// CROP (Aspect Ratio) Section
$crop = array_filter(explode(':', $crop));
if (empty($crop)) {
$crop = [$width, $height];
} else {
$crop[0] = $crop[0] ?: $crop[1];
$crop[1] = $crop[1] ?: $crop[0];
}
$ratio = [$width / $height, $crop[0] / $crop[1]];
if ($ratio[0] > $ratio[1]) {
$width = $height * $ratio[1];
$x = (imagesx($image) - $width) / 2;
} else {
$height = $width / $ratio[1];
$y = (imagesy($image) - $height) / 2;
}
// Resize Section
if (is_null($size)) {
$size = [$width, $height];
} else {
$size = array_filter(explode('x', $size));
if (empty($size)) {
$size = [imagesx($image), imagesy($image)];
} else {
$size[0] = $size[0] ?: round($size[1] * $width / $height);
$size[1] = $size[1] ?: round($size[0] * $height / $width);
}
}
$result = ImageCreateTrueColor($size[0], $size[1]);
if (is_resource($result)) {
ImageSaveAlpha($result, true);
ImageAlphaBlending($result, true);
ImageFill($result, 0, 0, ImageColorAllocate($result, 255, 255, 255));
ImageCopyResampled($result, $image, 0, 0, $x, $y, $size[0], $size[1], $width, $height);
ImageInterlace($result, true);
ImageJPEG($result, null, 90);
}
}
return false;
}
header('Content-Type: image/jpeg');
Image('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png', '1:1', '600x');
?>

Categories