image resize with array of height and width - php

i have an array of $h and $w. it will only create the move_uploaded_file($_FILES['image']['tmp_name'],$_FILES['image']['name']); how can i use the array of sizes in creating new images?
for ($resize=1; $resize <= $units; $resize++)
{
$new = $album_name."_".$image_name."_".$resize.".".$image_ext;
$targetImage = imagecreatetruecolor($w, $h);
$image = imagecreatefromstring(file_get_contents($target));
imagecopyresampled($targetImage,$image, 0, 0, 0, 0, $w, $h, $originalWidth, $originalHeight);
imagejpeg($targetImage,'uploads/'.$albumName.'/'.$new,80);
}

In your code snippet $w and $h do not appear to be arrays.
Let assume that $w and $h are arrays of size $resize with different image sizes.
The following code also detects image MIME type using getimagesize function and resizes image of JPG, PNG and GIF formats.
for ($resize=1; $resize <= $units; $resize++)
{
$size = getimagesize($target);
if ($size === false)
return false;
$format = strtolower(substr($size['mime'], strpos($size['mime'], '/') + 1));
$icfunc = "imagecreatefrom" . $format;
if (!function_exists($icfunc))
return false;
$new = $album_name."_".$image_name."_".$resize.".".$image_ext;
$targetImage = imagecreatetruecolor($w[$resize], $h[$resize]);
$image = $icfunc($target);
imagecopyresampled($targetImage,$image, 0, 0, 0, 0, $w[$resize], $h[$resize], $originalWidth, $originalHeight);
switch ($size['mime']) {
case 'image/jpg':
case 'image/jpeg':
case 'image/pjpeg':
return imagejpeg($dst_r, 'uploads/'.$albumName.'/'.$new, 80);
break;
case 'image/png';
return imagepng($dst_r, 'uploads/'.$albumName.'/'.$new, 2);
break;
case 'image/gif';
return imagegif($dst_r, 'uploads/'.$albumName.'/'.$new);
break;
default:
return;
}
}

Related

i want to resize my image but some image save blank

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 'jpg': $img = imagecreatefromjpeg($src); break;
case 'png': $img = imagecreatefrompng($src); break;
default : return "Unsupported picture type!";
}
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);
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 'jpg': imagejpeg($new, $dst); break;
case 'png': imagepng($new, $dst); break;
}
return true;
}
and i call it like
image_resize($path . $NewNameImage, $path . "thumbs/".$NewNameImage, 50, 50, 1);
but i see in server save black image for some images
plz help me

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);
}

Resizing images and padding short edges

Code below resizes the images but I have a new requirement to it.
Requirement: I want to add padding to short edge with any colour. So when it is scaled down to 100(w)X150(h), it should be saved as 150X150 afted being padded.
For the padding option I've seen these two posts but failed to implement. Please help me to modify my code.
Resize/crop/pad a picture to a fixed size
Resize an image and fill gaps of proportions with a color
Thanks in advance
$this->defaults['width'] = 100;
$this->defaults['height'] = 150;
private function createThumbnail($sourceImage, $targetImage)
{
list($sourceWidth, $sourceHeight, $sourceType) = getimagesize($sourceImage);
switch ($sourceType)
{
case IMAGETYPE_GIF:
$sourceGdImage = imagecreatefromgif($sourceImage);
break;
case IMAGETYPE_JPEG:
$sourceGdImage = imagecreatefromjpeg($sourceImage);
break;
case IMAGETYPE_PNG:
$sourceGdImage = imagecreatefrompng($sourceImage);
break;
}
if ($sourceGdImage === false)
{
return false;
}
$sourceAspectRatio = ($sourceWidth / $sourceHeight);
$thumbnailAspectRatio = ($this->defaults['width'] / $this->defaults['height']);
if ($sourceWidth <= $this->defaults['width'] && $sourceHeight <= $this->defaults['height'])
{
$thumbnailWidth = $sourceWidth;
$thumbnailHeight = $sourceHeight;
}
elseif ($thumbnailAspectRatio > $sourceAspectRatio)
{
$thumbnailWidth = (int) ($this->defaults['height'] * $sourceAspectRatio);
$thumbnailHeight = $this->defaults['height'];
}
else
{
$thumbnailWidth = $this->defaults['width'];
$thumbnailHeight = (int) ($this->defaults['width'] / $sourceAspectRatio);
}
$thumbnailGdImage = imagecreatetruecolor($thumbnailWidth, $thumbnailHeight);
imagecopyresampled($thumbnailGdImage, $sourceGdImage, 0, 0, 0, 0, $thumbnailWidth, $thumbnailHeight, $sourceWidth, $sourceHeight);
switch ($sourceType)
{
case IMAGETYPE_GIF:
imagegif($thumbnailGdImage, $targetImage, 90);
break;
case IMAGETYPE_JPEG:
imagejpeg($thumbnailGdImage, $targetImage, 90);
break;
case IMAGETYPE_PNG:
imagepng($thumbnailGdImage, $targetImage, 9);
break;
}
imagedestroy($sourceGdImage);
imagedestroy($thumbnailGdImage);
return true;
}
SOLUTION:
thumbnailDefaults:
height: 200
width: 200
red: 200
green: 0
blue: 0
private function createThumbnailWithPadding($sourceImage, $targetImage)
{
list($sourceWidth, $sourceHeight, $sourceType) = getimagesize($sourceImage);
$sourceGdImage = imagecreatefromstring(file_get_contents($sourceImage));
//Determine scale based on the longest edge
if ($sourceHeight > $sourceWidth)
{
$scale = ($this->thumbnailDefaults['height'] / $sourceHeight);
}
else
{
$scale = ($this->thumbnailDefaults['width'] / $sourceWidth);
}
//Calculate new image dimensions
$thumbnailWidth = ($sourceWidth * $scale);
$thumbnailHeight = ($sourceHeight * $scale);
//Determine offset coordinates so that new image is centered
$offsetX = (($this->thumbnailDefaults['width'] - $thumbnailWidth) / 2);
$offsetY = (($this->thumbnailDefaults['height'] - $thumbnailHeight) / 2);
//Create new image and fill with background colour
$thumbnailGdImage = imagecreatetruecolor($this->thumbnailDefaults['width'], $this->thumbnailDefaults['height']);
//Set background colour
$bgColor = imagecolorallocate(
$thumbnailGdImage,
$this->thumbnailDefaults['red'],
$this->thumbnailDefaults['green'],
$this->thumbnailDefaults['blue']
);
//Fill background colour
imagefill($thumbnailGdImage, 0, 0, $bgColor);
//Copy and resize original image into center of new image
imagecopyresampled($thumbnailGdImage, $sourceGdImage, $offsetX, $offsetY, 0, 0, $thumbnailWidth, $thumbnailHeight, $sourceWidth, $sourceHeight);
//clearstatcache();
switch ($sourceType)
{
case IMAGETYPE_GIF:
imagegif($thumbnailGdImage, $targetImage, 90);
break;
case IMAGETYPE_JPEG:
imagejpeg($thumbnailGdImage, $targetImage, 90);
break;
case IMAGETYPE_PNG:
imagepng($thumbnailGdImage, $targetImage, 9);
break;
}
imagedestroy($sourceGdImage);
imagedestroy($thumbnailGdImage);
return true;
}

Crop from the center and resize in PHP

I want to have a function that resizes to a specific height en weight of an image without losing the aspect ratio. So first i want to crop it and then resizing it.
This is what i got so far:
function image_resize($src, $dst, $width, $height, $crop=1){
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;
}
The function is working fine, but its crops from the upper leftcorner.
I want it to crop from the center.
You have to calculate cropped image shift for imagecopyresampled():
Keep original size before you calculate new:
// resize
$originalW = $w;
$originalH = $h;
if ($crop) {
...
And replace Your imagecopyresampled by this:
imagecopyresampled($new, $img, 0, 0, ($originalW - $width)/2, ($originalH - $height)/2, $width, $height, $w, $h);
You can check manual here.
I solve the black areas in the image. Now this script resize, crop and center.
The final code is here:
if(!list($w, $h) = getimagesize($src)) return array(false,"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 array(false,"Unsupported picture type!");
}
// resize
$originalW = $w;
$originalH = $h;
if($crop){
if ($w < $width or $h < $height) return array(false,"Picture is too small! Min size $width px X $height px");
$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 array(false,"Picture is too small! Min size $width px X $height px");
$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, ($w - $width)/2, ($h - $height)/2, $width, $height, $w - (($w - $width)/2), $h - (($h - $height)/2) );
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 array(true,$dst);

Resize image with scale?

I am using this function
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagesavealpha($new_image, true);
$trans_colour = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
imagefill($new_image, 0, 0, $trans_colour);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
What I want to do is make a square image. I would like to resize by the smallest attribute, then instead of the larger number being squished. I would like the edges chopped off.
So if I have an image which is 213 x 180 which I need resized to 150 x 150
I can resize the image to 150 height before it hits this function.
What I don't know how to do is take the width and chop off the edges to get 150 width without distortion.
Does anyone know how to do this?
By "Chop off" the edge i guess you mean making a crop of you're image, right ?
For croping a image you could use imagecopyresized.
A little example :
$imageSrc = //Your source image;
$tempImage = imagecreatetruecolor(150,150);
// CropStartX et cropStartY have to be computed to suit your needs
imagecopyresized($tempImage,$imageSrc,0,0,$cropStartX,$cropStartY,150,150,150,150);
// $tempImage now contain your cropped image.
This is copied from an old project of mine, does what you need:
static public function resizeCropAndMove($from_path, $to_path, $max_width, $max_height)
{
$image_info = getImageSize($from_path);
switch ($image_info['mime']) {
case 'image/jpeg': $input = imageCreateFromJPEG($from_path); break;
default:
return false;
}
$input_width = imagesx($input);
$input_height = imagesy($input);
$output = imageCreateTrueColor($max_width, $max_height);
if ($input_width <= $input_height) { //portrait
$lamda = $max_width / $input_width;
if ($lamda < 1) {
$temp_width = (int)round($lamda * $input_width);
$temp_height = (int)round($lamda * $input_height);
$temp = imagecreatetruecolor($temp_width, $temp_height);
imageCopyResampled($temp, $input, 0, 0, 0, 0, $temp_width, $temp_height, $input_width, $input_height);
$top = (int)round(($temp_height - $max_height) / 2);
$left = 0;
}
} else { //landscape
$lamda = $max_height / $input_height;
if ($lamda < 1) {
$temp_width = (int)round($lamda * $input_width);
$temp_height = (int)round($lamda * $input_height);
$temp = imagecreatetruecolor($temp_width, $temp_height);
imageCopyResampled($temp, $input, 0, 0, 0, 0, $temp_width, $temp_height, $input_width, $input_height);
$left = (int)round(($temp_width - $max_width) / 2);
$top = 0;
}
}
if ($lamda < 1) {
imageCopyResampled($output, $temp, 0, 0, $left, $top, $max_width, $max_height, $max_width, $max_height);
imagePNG($output, $to_path);
imagedestroy($temp);
} else {
imagePNG($input, $to_path);
}
imageDestroy($input);
imageDestroy($output);
}
function createCroppedThumb($thumbSourcePath, $thumbSavePath, $thumbDim){
// Get dimensions of the original image
$detail = getimagesize($thumbSourcePath);
$current_width = $detail[0];
$current_height = $detail[1];
$imageType = $detail[2];
// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 0;
$top = 0;
// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = $thumbDim;
$crop_height = $thumbDim;
// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
switch($imageType){
case '1':
$current_image = imagecreatefromgif($thumbSourcePath);
break;
case '2':
$current_image = imagecreatefromjpeg($thumbSourcePath);
break;
case '3':
$current_image = imagecreatefrompng($thumbSourcePath);
break;
default:
throw new Exception('unknown image type');
break;
}
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
switch($imageType){
case '1':
imagegif($canvas,$thumbSavePath,100);
break;
case '2':
imagejpeg($canvas,$thumbSavePath,100);
break;
case '3':
imagepng($canvas,$thumbSavePath,100);
break;
default:
throw new Exception('unknown image type');
break;
}
}

Categories