image resize in my wordpress plugin using php - php

I am trying to resize an image in my wordpress plugin using php, But they don't work. How can I resize image as propotion wise using php?
anyone know if that's possible?
Thanks

You can use wordpress built-in resize function:
<?php image_resize( $file, $max_w, $max_h, $crop, $suffix, $dest_path, $jpeg_quality ); ?>
You can find more details in here: http://codex.wordpress.org/Function_Reference/image_resize

This function takes the imagePath as parameter and the size to which you want it to resize the image.This will resize image with proportion constraints
suppose size = 300
then there will be three scenarios
1) if image's height is greater than width then its height will be 300
2) if width is greater then its width will be 300
3) if image is of ratio 1:1 then both its height and width will be of size 300
function resizeImage($imagePath,$size)
{
$sizeData = getimagesize($imagePath);
$width = $sizeData[0];
$height = $sizeData[1];
# Loading image to memory according to type
switch ( $sizeData[2] ) {
case IMAGETYPE_GIF: $src = imagecreatefromgif($imagePath); break;
case IMAGETYPE_JPEG: $src = imagecreatefromjpeg($imagePath); break;
case IMAGETYPE_PNG: $src = imagecreatefrompng($imagePath); break;
default: return false;
}
if(!$src)
{
return false;
}
if($height >= $width)
{
$newheight = $size;
$newwidth = ($newheight*$width)/$height;
}
else
{
$newwidth = $size;
$newheight = ($height/$width)*$newwidth;
}
$tmp = imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
# Writing image according to type to the output destination
switch ( $sizeData[2] ) {
case IMAGETYPE_GIF: imagegif($tmp, $imagePath); break;
case IMAGETYPE_JPEG: imagejpeg($tmp, $imagePath, 100); break;
case IMAGETYPE_PNG: imagepng($tmp, $imagePath, 9); break;
default: return false;
}
imagedestroy($src);
imagedestroy($tmp);
return true;
}

Related

php image resize code and high cpu usage

I have the following php code which resizes images in cbimages folder and creates thumbnail images in another folder cbimages/thumbs/
<?php
//Maximize script execution time
ini_set('max_execution_time', 0);
//Initial settings, Just specify Source and Destination Image folder.
$ImagesDirectory = '/var/www/example.com/public_html/cbimages/'; //Source Image Directory End with Slash
$DestImagesDirectory = '/var/www/example.com/public_html/cbimages/thumbs/'; //Destination Image Directory End with Slash
$NewImageWidth = 150; //New Width of Image
$NewImageHeight = 150; // New Height of Image
$Quality = 80; //Image Quality
//Open Source Image directory, loop through each Image and resize it.
if($dir = opendir($ImagesDirectory)){
while(($file = readdir($dir))!== false){
$imagePath = $ImagesDirectory.$file;
$destPath = $DestImagesDirectory.$file;
$checkValidImage = #getimagesize($imagePath);
if(file_exists($imagePath) && $checkValidImage) //Continue only if 2 given parameters are true
{
//Image looks valid, resize.
if(resizeImage($imagePath,$destPath,$NewImageWidth,$NewImageHeight,$Quality))
{
echo $file.' - Resize Success!<br />';
/*
Now Image is resized, may be save information in database?
*/
}else{
echo $file.' - Resize Failed!<br />';
}
}
}
closedir($dir);
}
//Function that resizes image.
function resizeImage($SrcImage,$DestImage, $MaxWidth,$MaxHeight,$Quality)
{
list($iWidth,$iHeight,$type) = getimagesize($SrcImage);
$ImageScale = min($MaxWidth/$iWidth, $MaxHeight/$iHeight);
$NewWidth = ceil($ImageScale*$iWidth);
$NewHeight = ceil($ImageScale*$iHeight);
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
switch(strtolower(image_type_to_mime_type($type)))
{
case 'image/jpeg':
case 'image/png':
case 'image/gif':
$NewImage = imagecreatefromjpeg($SrcImage);
break;
default:
return false;
}
// Resize Image
if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight))
{
// copy file
if(imagejpeg($NewCanves,$DestImage,$Quality))
{
imagedestroy($NewCanves);
return true;
}
}
}
?>
The script is running fine at my local development environment with ubuntu 14.04 and runs fast. On my ubuntu 14.04 server the cup usage shoots upto 100% and takes time to complete.
It is taking too much time to run the script and CPU usage shoots upto 100%. Everytime i start this script it starts resizing all the images..even those resized.
How can i optimize the script ??
Help requested. Thanks in advance.
See if this class makes any difference:
class thumb{
var $image;
var $type;
var $width;
var $height;
//read image method
function loadImage($name){
//get image dimensions
$info = getimagesize($name);
if($info){
$this->width = $info[0];
$this->height = $info[1];
$this->type = $info[2];
//create new image
switch($this->type){
case IMAGETYPE_BMP:
$this->image = imagecreatefromwbmp($name);
break;
case IMAGETYPE_JPEG:
$this->image = imagecreatefromjpeg($name);
break;
case IMAGETYPE_GIF:
$this->image = imagecreatefromgif($name);
break;
case IMAGETYPE_PNG:
$this->image = imagecreatefrompng($name);
break;
default: $this->image = false;
}
return $this->image;
}
else{return false;}
}
//store the image
function saveImage($name, $quality = 100){
switch($this->type){
case IMAGETYPE_BMP:
$go = imagewbmp($this->image, $name);
break;
case IMAGETYPE_JPEG:
$go = imagejpeg($this->image, $name, $quality);
break;
case IMAGETYPE_GIF:
$go = imagegif($this->image, $name);
break;
case IMAGETYPE_PNG:
$pngquality = floor(($quality - 10) / 10);
$go = imagepng($this->image, $name, $pngquality);
break;
default: $go = false;
}
return $go;
}
//resize image dimensions proportionally
function resizeImage($x, $y){
//get resizing properties
$wd = $x;
$hg = $y;
if($this->width >= $this->height){$hg = round($this->height / ($this->width / $x));}
else{$wd = round($this->width / ($this->height / $y));}
if($wd < $x){
$wd = $x;
$hg = round($this->height / ($this->width / $x));
}
else{
if($hg < $y){
$hg = $y;
$wd = round($this->width / ($this->height / $y));
}
}
//create image based on properties
$image = imagecreatetruecolor($wd, $hg);
//make image copy based on properties
$go = imagecopyresampled($image, $this->image, 0, 0, 0, 0, $wd, $hg, $this->width, $this->height);
//refresh image with new dimensions on success
if($go){
$this->width = imagesx($image);
$this->height = imagesy($image);
$this->image = $image;
}
return $go;
}
}

Best output when resizing images in PHP

I want to make a thumbnail(64X64) of images uploaded by user to reduce the overall page size. I did it using the following PHP code, But the result is really disappointing! in one instance the original file size was 554 byte (70X70). by converting it to a 64X64 image, the file size has increase to 1.43 KB! while the quality of the image is terribly degraded.
What is wrong here? Isn't it any other way to resize the images by PHP and have a better output?
Thank you very much
function image_resize($src, $dst, $width, $height, $crop=0){
if(!list($w, $h) = getimagesize($src)) return "Unsupported picture type!";
$type = strtolower(substr(strrchr($src,"."),1));
if($type == 'jpeg') $type = 'jpg';
switch($type){
case 'bmp': $img = imagecreatefromwbmp($src); break;
case 'gif': $img = imagecreatefromgif($src); break;
case 'jpg': $img = imagecreatefromjpeg($src); break;
case 'png': $img = imagecreatefrompng($src); break;
default : return "Unsupported picture type!";
}
// resize
if($crop){
if($w < $width or $h < $height) return "Picture is too small!";
$ratio = max($width/$w, $height/$h);
$h = $height / $ratio;
$x = ($w - $width / $ratio) / 2;
$w = $width / $ratio;
}
else{
if($w < $width and $h < $height) return "Picture is too small!";
$ratio = min($width/$w, $height/$h);
$width = $w * $ratio;
$height = $h * $ratio;
$x = 0;
}
$new = imagecreatetruecolor($width, $height);
// preserve transparency
if($type == "gif" or $type == "png"){
imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
imagealphablending($new, false);
imagesavealpha($new, true);
}
imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);
switch($type){
case 'bmp': imagewbmp($new, $dst); break;
case 'gif': imagegif($new, $dst); break;
case 'jpg': imagejpeg($new, $dst); break;
case 'png': imagepng($new, $dst); break;
}
return true;
}
I think that probably nothing is wrong here. 1.43KB is not very much, so it's not clear that the image produced is inefficiently stored. As for image quality, we're talking about a very small image; resizing from 70x70 to 64x64 is very likely to produce an odd-looking result. If you have a larger image to start with then it will probably work better.
There are other PHP image libraries (e.g. WideImage), but I'd be surprised if using them would make a great deal of difference here. In fact they probably use GD internally anyway.

How to create Thumbnail Image in PHP without loosing its Original Quality using GD Library

if(isset($_POST["insert"]))
{
foreach($_FILES as $imgfile)
{
$tmp_name = $imgfile['tmp_name'];
$type = $imgfile['type'];
$name = $imgfile['name']; //name of original image
$size = $imgfile['size'];
if (file_exists($tmp_name))
{
if(is_uploaded_file($tmp_name))
{
$target="realimage/";
$target .= basename($_FILES['image']['name']); //path of original image
$file = fopen($tmp_name,'r');
$data = fread($file,filesize($tmp_name));
fclose($file);
$data = chunk_split(base64_encode($data));
move_uploaded_file($tmp_name,$target);
}
$extension= explode(".", $target);
$extension=$extension[count($extension)-1]; //gives the image extension
$maxwidth=400;
$maxheight=200;
switch($extension) {
case 'gif':
$tmpimg = imagecreatefromgif($target);
break;
case 'jpg':
$tmpimg = imagecreatefromjpeg($target);
break;
case 'png':
$tmpimg = imagecreatefrompng($target);
break;
}
list($width,$height)=getimagesize($target);
if($width > $height)
{
$thumb_width=$maxwidth;
$thumb_height= intval($height*$thumb_width/$width);
}
else
{
$thumb_height= $maxheight;
$thumb_width=intval($width*$thumb_height/$height);
}
$dest_x = intval(($maxwidth - $thumb_width) / 2);
$dest_y = intval(($maxheight - $thumb_height) / 2);
$newimg= imagecreatetruecolor($maxwidth,$maxheight);
imagecopyresampled($newimg,$tmpimg,$dest_x,$dest_y,0,0,$thumb_width,$thumb_height,$width,$height);
imagejpeg($newimg,"thumbimage/$name",100);
}
}
}
The code is like this
1) I am uploading an Image in the folder "realimage" .
2) I want to display a resized image of the realimage on my website . For that I hav created a folder "thumbimage" which stores the thumbnail image of the original.
The code does create Thumbnails for the images which are larger than the specified thumbnail width and height, but the quality Looses and I get blur Images. I want the Image quality to be same as the original image , just the size should be small then the original.
I have got another problem as well, when I upload an Image smaller than the specified Thumbnail Width & Height , then the image does not fit into the area and fills just some part of the area leaving other area black.
Help Me in Creating Ideal Thumbnail meeting all the scenarios.
try this:
$type = exif_imagetype($pathToImages);
$width = imagesx($img);
$height = imagesy($img);
// calculate thumbnail size
if ($width >= $height) {
//If width is greater than height
$new_width = $thumbWidth;
$new_height = floor($height * ($thumbWidth / $width));
} else {
//If height is greater than width
$new_height = $thumbWidth;
$new_width = floor($width * ($thumbWidth / $height));
}
// create a new temporary image
// echo $new_height;
$tmp_img = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// save thumbnail into a file
switch($type) {
case 1 :
imagegif($tmp_img, $pathToThumbs . $file_name,90);
break;
case 2 :
imagejpeg($tmp_img, $pathToThumbs . $file_name,90);
break;
case 3 :
imagepng($tmp_img, $pathToThumbs . $file_name,90);
break;
case 6 :
imagewbmp($tmp_img, $pathToThumbs . $file_name,90);
break;
}

Image resize and keep ratio bug

I found and modified a GD image resize and keep ratio script but it's not working as it should.
For example I want to resize a picture to MAXIMUM 200w x 200h keeping ratio. The picture I want to resize is 518w x 691h and the script should resize it to 150w x 200h to keep the aspect ratio but instead it resize it to 200w x 226h. What is the problem?
function resize_image($source_image, $name, $new_width, $new_height, $destination)
{
list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image);
switch($source_image_type)
{
case IMAGETYPE_GIF:
$source_gd_image = imagecreatefromgif($source_image);
break;
case IMAGETYPE_JPEG:
$source_gd_image = imagecreatefromjpeg($source_image);
break;
case IMAGETYPE_PNG:
$source_gd_image = imagecreatefrompng($source_image);
break;
}
$source_aspect_ratio = $source_image_width / $source_image_height;
$thumbnail_aspect_ratio = $new_width / new_height;
if($source_image_width <= $new_width && $source_image_height <= new_height)
{
$thumbnail_image_width = $source_image_width;
$thumbnail_image_height = $source_image_height;
}
elseif ($thumbnail_aspect_ratio > $source_aspect_ratio)
{
$thumbnail_image_width = (int)(new_height * $source_aspect_ratio);
$thumbnail_image_height = new_height;
}
else
{
$thumbnail_image_width = $new_width;
$thumbnail_image_height = (int)($new_width / $source_aspect_ratio);
}
$thumbnail_gd_image = imagecreatetruecolor($thumbnail_image_width, $thumbnail_image_height);
imagealphablending($thumbnail_gd_image, false);
imagesavealpha($thumbnail_gd_image, true);
imagecopyresampled($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height);
$destination = $destination.$name;
switch($source_image_type)
{
case IMAGETYPE_GIF:
imagegif($thumbnail_gd_image, $destination);
break;
case IMAGETYPE_JPEG:
imagejpeg($thumbnail_gd_image, $destination, 100);
break;
case IMAGETYPE_PNG:
imagepng($thumbnail_gd_image, $destination, 9);
break;
}
imagedestroy($source_gd_image);
imagedestroy($thumbnail_gd_image);
}
This section:
elseif ($thumbnail_aspect_ratio > $source_aspect_ratio)
should never execute, since you want to keep the aspect ratios the same. To determine the new width / height, try something like this:
if($width > $MAX_SIZE || $height > $MAX_SIZE) {
$aspect = $width / $height;
if($width > $height) {
$width = $MAX_SIZE;
$height = intval($MAX_SIZE / $aspect);
} else {
$height = $MAX_SIZE;
$width = intval($MAX_SIZE * $aspect);
}
}
Update
All this code is doing is attempting to determine a new width / height based on a restriction $MAX_SIZE, while keeping the aspect ratio the same. It's not going to be perfect because floating point arithemetic is rarely ever so (especially since in this case you can't have 'fractional' pixels, which is why the calculations above use intval). Consider if, for example, before this code is ran $width, $height and $MAX_SIZE are set as follows:
$MAX_SIZE = 100;
$width = 1920;
$height = 1080;
The original aspect ratio is 1.77777777.... After running the snippet above, the width / height will be set to 100 x 56, which is an aspect ratio of 1.7857. Moving the output width/height either up or down by a pixel will not ever get you the exact input aspect ratio, unless you allow pixel values with fractional components.
However you're uploading the file and determining the input file's height / width shouldn't matter, the snippet above is only supposed to get you the resized dimensions as close as possible to the input aspect ratio.

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