I want to cut out part of the photo without stretch it.
Something like the photo I posted, cut out the red part and get photo number 2
With a width of 150px and height of 100px and cuting from top left of photo
enter image description here
I tried to do it with this code but it didn't work.
This codes separates part of the image, but does not do so from the top left of the image.
function resizejpeg($dir, $newdir, $img, $max_w, $max_h, $th_w, $th_h)
{
// set destination directory
if (!$newdir) $newdir = $dir;
// get original images width and height
list($or_w, $or_h, $or_t) = getimagesize($dir.$img);
// make sure image is a jpeg
if ($or_t == 2) {
// obtain the image's ratio
$ratio = ($or_h / $or_w);
// original image
$or_image = imagecreatefromjpeg($dir.$img);
// resize image?
if ($or_w > $max_w || $or_h > $max_h) {
// resize by height, then width (height dominant)
if ($max_h < $max_w) {
$rs_h = $max_h;
$rs_w = $rs_h / $ratio;
}
// resize by width, then height (width dominant)
else {
$rs_w = $max_w;
$rs_h = $ratio * $rs_w;
}
// copy old image to new image
$rs_image = imagecreatetruecolor($rs_w, $rs_h);
imagecopyresampled($rs_image, $or_image, 0, 0, 0, 0, $rs_w, $rs_h, $or_w, $or_h);
}
// image requires no resizing
else {
$rs_w = $or_w;
$rs_h = $or_h;
$rs_image = $or_image;
}
// generate resized image
imagejpeg($rs_image, $newdir.$img, 100);
$th_image = imagecreatetruecolor($th_w, $th_h);
// cut out a rectangle from the resized image and store in thumbnail
$new_w = (($rs_w / 2) - ($th_w / 2));
$new_h = (($rs_h / 2) - ($th_h / 2));
imagecopyresized($th_image, $rs_image, 0, 0, $new_w, $new_h, $rs_w, $rs_h, $rs_w, $rs_h);
// generate thumbnail
imagejpeg($th_image, $newdir.'thumb_'.$img, 100);
return true;
}
// Image type was not jpeg!
else {
return false;
}
}
$dir = './';
$img = '1.jpg';
$size = getimagesize($img);
$width = $size[0];
$height = $size[1];
resizejpeg($dir, '', $img, $width, $height, 150, 100);
I didn't understand correctly what you mean, but based on your description you are trying to get the image no 2 which means you are trying to crop an image. If that your mean, maybe this code will help
function crop($image_path, $output_path, $x, $y, $width, $height) {
// load image
$image = imagecreatefromjpeg($image_path);
// crop the image
$cropped_image = imagecrop($image, [
'x' => $x,
'y' => $y,
'width' => $width,
'height' => $height
]
);
// save it
imagejpeg($cropped_image, $output_path);
}
you can use it like this
// input image path
$image = "img.jpg";
// output image path
$output = "crop_img.jpg";
// crop it from (0,0)
crop($image, $output, 0, 0, 150, 100);
Related
in my project i just do image watermarking or image combine it's working fine and code for that.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<?php
if(isset($_POST['submit']))
{
// Give the Complete Path of the folder where you want to save the image
$folder="uploads/";
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "$folder".$_FILES["fileToUpload"]["name"]);
$file='uploads/'.$_FILES["fileToUpload"]["name"];
$uploadimage=$folder.$_FILES["fileToUpload"]["name"];
$newname= time();
$ext = pathinfo($_FILES["fileToUpload"]["name"], PATHINFO_EXTENSION);
// Set the thumbnail name
$thumbnail = $folder.$newname.".".$ext;
$imgname=$newname.".".$ext;
// Load the mian image
if ($ext=="png" || $ext=="PNG") {
$source = imagecreatefrompng($uploadimage);
}
else if ($ext=="gif" || $ext=="GIF") {
$source = imagecreatefromgif($uploadimage);
}
else if ($ext=="bmp" || $ext=="BMP") {
$source = imagecreatefrombmp($uploadimage);
}
else{
$source = imagecreatefromjpeg($uploadimage);
}
// load the image you want to you want to be watermarked
$watermark = imagecreatefrompng('uploads/logo1.png');
// get the width and height of the watermark image
$water_width = imagesx($source)/2;
$water_height = imagesy($watermark);
// get the width and height of the main image image
$main_width = imagesx($source);
$main_height = imagesy($source);
$im_middle_w = $main_width/2;
$im_middle_h = $main_height/2;
// Set the dimension of the area you want to place your watermark we use 0
// from x-axis and 0 from y-axis
$dime_x = $im_middle_w - $water_width/2;
$dime_y = $im_middle_h - $water_height/2;
// copy both the images
imagecopy($source, $watermark, $dime_x, $dime_y, 0, 0, $water_width, $water_height);
// Final processing Creating The Image
imagejpeg($source, $thumbnail, 100);
unlink($file);
}
?>
<img src='uploads/<?php echo $imgname;?>'>
</body>
</html>
but problem with setting $water_width and i want set as half of my source image. but when i have source image of less width or more width compare to $water_width it's set it like that. see image when source image width is more.
and when width is less.
so my problem is how to set $water_width as half of source image width?
by Alex your answer it's came up like this.
This will resize watermark to half-width of original image and put it in the centre:
// load the image you want to you want to be watermarked
$watermark = imagecreatefrompng('uploads/logo1.png');
// get the width and height of the watermark image
$water_width = imagesx($watermark);
$water_height = imagesy($watermark);
// get the width and height of the main image image
$main_width = imagesx($source);
$main_height = imagesy($source);
// resize watermark to half-width of the image
$new_height = round($water_height * $main_width / $water_width / 2);
$new_width = round($main_width / 2);
$new_watermark = imagecreatetruecolor($new_width, $new_height);
// keep transparent background
imagealphablending( $new_watermark, false );
imagesavealpha( $new_watermark, true );
imagecopyresampled($new_watermark, $watermark, 0, 0, 0, 0, $new_width, $new_height, $water_width, $water_height);
// Set the dimension of the area you want to place your watermark we use 0
// from x-axis and 0 from y-axis
$dime_x = round(($main_width - $new_width)/2);
$dime_y = round(($main_height - $new_height)/2);
// copy both the images
imagecopy($source, $new_watermark, $dime_x, $dime_y, 0, 0, $new_width, $new_height);
// Final processing Creating The Image
imagejpeg($source, $thumbnail, 100);
imagedestroy($source);
imagedestroy($watermark);
imagedestroy($new_watermark);
You can try imagettftext method, if you don't want any such high perfection in transparency. You can have try of this code. You have to save a font file in your directory, here I used arial.ttf.
$im = imagecreatefrompng("png.png"); //create image data
$font = 'arial.ttf'; //font file name
$randomString = "example.com"; //string need to be shown
$main_width = imagesx($im); //finding width and height
$main_height = imagesy($im);
$posx= $main_width/2; //finding center
$posy = $main_height/2;
$color = imagecolorallocate($im, 200, 200, 200); //Creating color
$size = ($main_width/25)+1; //determine size of font. +1 to avoid 0
$temp = $size*5;
$posx = $posx-$temp; //adjust to average center
imagettftext($im,$size,0, $posx, $posy, $color, $font , $randomString); //apply a text
You have to adjust posx and posy for your text position. Size also can be adjusted with some logics.
$color = imagecolorallocate($im, 0, 0, 0);= black
and $color = imagecolorallocate($im, 255, 255, 255); = white.
You have to adjust this for your required text color.
I have the below script, it all works fine, apart from if I enter a value into the function arguments for the percentage, the overlay's are too large, they should scale down by #% of the max size.
Here is an example:
But then if I change the "80" to "0" in the function call I get this:
If I change the same value to lets say "20" to scale the overlay down by 20%, I simply get the same as above...
Any ideas as to why it isn't scaling the overlay down by inputted %?
<?php
session_start();
//Set the content-type
header('Content-Type: image/png');
//Overlay URLS
$overlay_url = $_SESSION['ROOT_PATH']."images/logos/overlay.png";
$logo_url = $_SESSION['ROOT_PATH']."images/logos/".$_GET['logo'].".png";
//How much of the image will the overlays take up
$logo_percent = 0.60;
$overlay_percent = 0.90;
//Get the image size first
$size = explode(",",$_GET['size']);
$width = (int)$size[0];
$height = (int)$size[1];
$background = imagecreatetruecolor($width,$height);
$bg_color = imagecolorallocate($background,20,100,255);
imagefill($background, 0, 0, $bg_color);
//Apply company logo first
$company_logo = apply_watermark($background,$overlay_url,80,0,0,90);
//Now venue logo
imagepng(apply_watermark($company_logo,$logo_url,80,1,0,90));
//background(url/resource), watermarl(url), size percent, left0/right1, padding(px),rotate
function apply_watermark($bg,$wt,$p,$lr,$pad=0,$rt=false) {
//Load background image into memory,can apply more watermarks to same image
if (gettype($bg) == "resource") {
$background = $bg;
} else {
$background = imagecreatefromjpeg($bg);
}
//Get the width and height and generate watermark max size
$bx = imagesx($background);
$by = imagesy($background);
$overlay_max = (($bx > $by) ? $bx : $by) / 100 * $p;
//Create container for image
$imagecontainer = imagecreatetruecolor($bx,$by);
//Allow alpha channels to be saved and fill it with alpha
imagesavealpha($imagecontainer,true);
$alphacolor = imagecolorallocatealpha($imagecontainer,0,0,0,127);
imagefill($imagecontainer,0,0,$alphacolor);
//Copy background image into the container
imagecopyresampled($imagecontainer,$background,0,0,0,0,$bx,$by,$bx,$by);
//Load the watermark
$overlay = imagecreatefrompng($wt);
if($rt != false){$overlay = imagerotate($overlay,$rt,0);}
//get the watermark width and height and generate the aspect ratio
$ratio = $overlay_max / imagesx($overlay);
if ($ratio > ($bx / $by)) {
$scale = imagesx($overlay) / $bx;
} else {
$scale = imagesy($overlay) / $by;
}
$newwidth = (int)(imagesx($overlay) / $scale);
$newheight = (int)(imagesy($overlay) / $scale);
//Create container for the watermark and apply alpha to it
$newoverlay = imagecreatetruecolor($newwidth,$newheight);
imagesavealpha($newoverlay,true);
imagefill($newoverlay,0,0,$alphacolor);
//Copy the watermark to the watermark container with alpha
imagecopyresized($newoverlay, $overlay, 0, 0, 0, 0, $newwidth, $newheight, imagesx($overlay), imagesy($overlay));
//Copy the watermark to the background image container, choose left or right
if ($lr == 0) {
imagecopyresampled($imagecontainer,$newoverlay,0+$pad,($by-$newheight-$pad),0,0,$newwidth,$newheight,$newwidth,$newheight);
} elseif ($lr == 1) {
imagecopyresampled($imagecontainer,$newoverlay,($bx-$newwidth-$pad),($by-$newheight-$pad),0,0,$newwidth,$newheight,$newwidth,$newheight);
}
//Return the generated image back to the function call to further handle
return $imagecontainer;
}
?>
I'm currently coding an uploader script based on Uploadify. Right now I resize the given image and watermark one of the sizes. It all works well, but I need the script to resize the height and then crop the width so that the aspect ratio does not get messed up.
This is my code so far:
if ($fileExtension == "jpg" ||
$fileExtension == "jpeg" ||
$fileExtension == "png" ||
$fileExtension == "gif"){
// GD variables:
list($width, $height, $type) = GetImageSize($uploadedFile['tmp_name']);
// Image sizes:
$bigImage = array(800, 453);
$mediumImage = array(410, 231);
$listImage = array(120, 68);
$thumbnail = array(90, 51);
$sourceAspect = $width / $height;
$bigAspect = $bigImage[0] / $bigImage[1];
$mediumAspect = $mediumImage[0] / $mediumImage[1];
$listAspect = $listImage[0] / $listImage[1];
$thumbnailAspect = $thumbnail[0] / $thumbnail[1];
// Image is PNG:
if ($type == IMAGETYPE_PNG){
$image = imagecreatefrompng($uploadedFile['tmp_name']);
$valid = true;
}
// Image is JPEG:
else if ($type == IMAGETYPE_JPEG){
$image = imagecreatefromjpeg($uploadedFile['tmp_name']);
$valid = true;
}
// Image is GIF:
else if ($type == IMAGETYPE_GIF){
$image = imagecreatefromgif($uploadedFile['tmp_name']);
$valid = true;
}
// Format not allowed:
else {
$valid = false;
}
// Start creating images:
if ($valid){
// Get size:
$imageSize = getimagesize($uploadedFile['tmp_name']);
// Generate canvas:
$bCanvas = imagecreatetruecolor($bigImage[0], $bigImage[1]);
$mCanvas = imagecreatetruecolor($mediumImage[0], $mediumImage[1]);
$lCanvas = imagecreatetruecolor($listImage[0], $listImage[1]);
$tCanvas = imagecreatetruecolor($thumbnail[0], $thumbnail[1]);
// Copy content:
imagecopyresampled($bCanvas, $image, 0, 0, 0, 0, ($bigImage[0] * $sourceAspect), ($bigImage[1] / $sourceAspect), $imageSize[0], $imageSize[1]);
imagecopyresampled($mCanvas, $image, 0, 0, 0, 0, $mediumImage[0], $mediumImage[1], $imageSize[0], $imageSize[1]);
imagecopyresampled($lCanvas, $image, 0, 0, 0, 0, $listImage[0], $listImage[1], $imageSize[0], $imageSize[1]);
imagecopyresampled($tCanvas, $image, 0, 0, 0, 0, $thumbnail[0], $thumbnail[1], $imageSize[0], $imageSize[1]);
// Save images:
$saveB = imagejpeg($bCanvas, $targetFile.'_big.jpg', 90);
$saveM = imagejpeg($mCanvas, $targetFile.'_medium.jpg', 90);
$saveT = imagejpeg($lCanvas, $targetFile.'_list.jpg', 90);
$saveT = imagejpeg($tCanvas, $targetFile.'_thumb.jpg', 90);
// Destroy images:
imagedestroy($image);
imagedestroy($bCanvas);
imagedestroy($mCanvas);
imagedestroy($lCanvas);
imagedestroy($tCanvas);
// Watermark images:
$mark = imagecreatefrompng("logo.png");
list($mwidth, $mheight) = getimagesize("logo.png");
$img = imagecreatefromjpeg($targetFile.'_big.jpg');
list($bwidth, $bheight) = getimagesize($targetFile.'_big.jpg');
imagecopy($img, $mark, $bwidth-$mwidth-25, $bheight-$mheight-25, 0, 0, $mwidth, $mheight);
imagejpeg($img, $targetFile.'_big.jpg', 100);
imagedestroy($img);
} else {
echo "0";
}
} else {
move_uploaded_file($tempFile,$targetFile.'.'.$fileExtension);
}
I would be really happy if someone could help me solve this. I've been trying several methods but none of them seemed to work properly. As you can see in the top I have already defined the canvas sizes that I want to use in the variables "bigImage", "mediumImage", "listImage" and "thumbnail".
Thanks in advance! //
Jonathan
There is more than one way to resize an image. I'll spell them out for you:
Stretch to fit -- the image is resized to the desired size ignoring aspect ratio
Scale to fit -- the image is resized so that one dimension (width or height) has the desired size while the other is same or shorter while maintaining aspect ratio (one extra step may be required to fill the shorter side with solid color)
Crop to fit -- the image is resized so that one dimension (width or height) has the desired size while the other is same or longer while maintaining aspect ratio (one extra step is required to trim the outside region)
PS: both articles were written by me.
I'm using jQuery's imgAreaSelect plugin in order to crop an image and save the thumbnail to use in cases where, for example, the ratio changes. Unfortunelly the results are far from what I would expect, and I can't get it right. The image gets resized as a whole instead of being cropped.
Here's the test example :
<?php
/***
*
* $_GET returned values
*
* x1 = 0
* x2 = 400
* y1 = 66
* y2 = 258
* w = 400
* h = 192
* folder = widethumb
* filename = IMG_4591.jpg
* scale = 48
*
* Original image properties
*
* width = 600px
* height = 900px
*
***/
define('DOCROOT', realpath(dirname(__FILE__)).DIRECTORY_SEPARATOR);
extract($_GET);
$fn = $filename;
$filename = DOCROOT.$filename;
list($width, $height) = getimagesize($filename);
$src = imagecreatefromjpeg($filename);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, (int) $x1, (int) $y1, (int) $w, (int) $h, $width, $height);
header('Content-Type: image/jpeg');
imagejpeg($dst);
What am I mising here?
Cheers!
From PHP Documentation:
bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.
In other words, imagecopyresampled() will take an rectangular area from src_image of width src_w and height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x,dst_y).
So to get the result you are looking for, you need to avoid scaling. for that use:
imagecopy($dst, $src, 0, 0, $x1, $y1, $w, $h);
// this can also be done but is less efficient (over 10 times slower)
imagecopyresampled($dst, $src, 0, 0, (int) $x1, (int) $y1, $w, $h, $w, $h);
Here we are are taking the same sized rectangle from source as we are putting it into destination image.
I have just tested it and it works just fine.
Update:
I have just tried again on my test server and it is working fine. I'm using following code:
$filename = "test.jpg";
extract($_GET);
$src = imagecreatefromjpeg($filename);
$dst = imagecreatetruecolor($w, $h);
imagecopy($dst, $src, 0, 0, $x1, $y1, $w, $h);
// this is over 10 times slower, as we are only cropping we should use imagecopy
//imagecopyresampled($dst, $src, 0, 0, $x1, $y1, $w, $h, $w, $h);
header('Content-Type: image/jpeg');
imagejpeg($dst);
And I'm calling it like this:
http://localserver/test/gd_crop.php?x1=906&y1=267&w=501&h=355
Performance Update
As we are not resizing we can simply use imagecopy. Performance of 3 functions as i have measured is given below.
imagecopyresampled 69ms
imagecopyresized 5.5ms
imagecopy 4.5ms
So there is an order of 10 speed difference between resampled and the two other functions.
I have finally come up with following line in place of imagecopyresampled function, try it, I have also updated the above code listing:
imagecopy($dst, $src, 0, 0, $x1, $y1, $w, $h);
Use the WideImage library instead.
This is my own cropping function:
function createThumbnail($file, $cropX, $cropY, $cropWidth, $cropHeight, $desiredWidth, $desiredHeight, $shrink = false)
{
if(file_exists(MPS_ROOT_PATH . "$file") && $cropWidth && $cropHeight)
{
$source_path = MPS_ROOT_PATH . $file;
list( $source_width, $source_height, $source_type ) = getimagesize( $source_path );
switch ( $source_type )
{
case IMAGETYPE_GIF:
$source_gdim = imagecreatefromgif( $source_path );
break;
case IMAGETYPE_JPEG:
$source_gdim = imagecreatefromjpeg( $source_path );
break;
case IMAGETYPE_PNG:
$source_gdim = imagecreatefrompng( $source_path );
break;
default:
return false;
}
if(!$desiredWidth)
{
// Desired width not set, computing new width based on original
// image's aspect ratio...
$desiredWidth = $cropWidth * ($desiredHeight / $cropHeight);
}
if(!$desiredHeight)
{
// Desired height not set, computing new height based on original
// image's aspect ratio
$desiredHeight = $cropHeight * ($desiredWidth / $cropWidth);
}
if(!$desiredWidth || !$desiredHeight)
{
// Desired height or width not set.
// Halting image processing and returning file
return $file;
}
$source_aspect_ratio = $cropWidth / $cropHeight;
$desired_aspect_ratio = $desiredWidth / $desiredHeight;
if($shrink)
{
// Shrink to fit flag set. Inverting computations to make image fit
// within the desired dimensions...
if($source_aspect_ratio > $desired_aspect_ratio)
{
// Source image is wider than desired aspect ratio,
// setting thumbnail width to the desired width and the height
// will be computed based on the original image's aspect ratio
$temp_width = $desiredWidth;
$temp_height = (int) ($desiredWidth / $source_aspect_ratio);
}
else
{
// Source image is taller than desired aspect ratio,
// setting thumbnail height to the desired height and the width
// will be computed based on the original image's aspect ratio
$temp_height = $desiredHeight;
$temp_width = (int) ($desiredHeight * $source_aspect_ratio);
}
}
// shrink to fit not set
else
{
if($source_aspect_ratio > $desired_aspect_ratio)
{
// Source image is wider than desired aspect ratio,
// setting thumbnail height to the desired height to fill the
// desired aspect ratio and the width will be computed based on
// the original image's aspect ratio
$temp_height = $desiredHeight;
$temp_width = (int) ($desiredHeight * $source_aspect_ratio);
}
else
{
// Source image is taller than desired aspect ratio,
// setting thumbnail width to the desired width to fill the
// desired aspect ratio and the width will be computed based on
// the original image's aspect ratio");
$temp_width = $desiredWidth;
$temp_height = (int) ($desiredWidth / $source_aspect_ratio);
}
}
$temp_gdim = imagecreatetruecolor($temp_width, $temp_height);
// Copying a $cropWidth x $cropHeight image from the source
// file at ($cropX, $cropY) and resampling it to fit the temporary
// $temp_width x $temp_height thumbnail at (0, 0)
imagecopyresampled(
$temp_gdim,
$source_gdim,
0, 0,
$cropX, $cropY,
$temp_width, $temp_height,
$cropWidth, $cropHeight
);
$x0 = ($desiredWidth - $temp_width) / 2;
$y0 = ($desiredHeight - $temp_height) / 2;
// Positioning the temporary $temp_width x $temp_height thumbnail in
// the center of the final $desiredWidth x $desiredHeight thumbnail...
// Creating final thumbnail canvas at $desiredWidth x $desiredHeight
$desired_gdim = imagecreatetruecolor($desiredWidth, $desiredHeight);
$white = imagecolorallocate($desired_gdim, 255, 255, 255);
imagefill($desired_gdim, 0, 0, $white);
// Filling final thumbnail canvas with white
// Copying a $temp_width x $temp_height image from the temporary
// thumbnail at (0, 0) and placing it in the final
// thumbnail at ($x0, $y0)
imagecopy(
$desired_gdim,
$temp_gdim,
$x0, $y0,
0, 0,
$temp_width, $temp_height
);
$pathInfo = pathinfo($file);
$thumbFile = "images/thumbs/thumb_" . basename($pathInfo["filename"]) . ".jpg";
if(imagejpeg($desired_gdim, MPS_ROOT_PATH . $thumbFile, 80))
{
return $thumbFile;
}
else
{
return 1;
}
}
else
{
echo "Image File Does not exist or Invalid crop parameters!";
return false;
}
}
Why don't you look into using imagemagik; it's great for image manipulation and cropping is just a simple case of using cropImage($width, $height, $x, $y);
Here's a function that you can pass the destination dimension to and will scale and crop from the center, maintain aspect ratio, and will scale up. This is easy to implement with the picture element for responsive design. If you change your destination dimensions, just delete the outputted files and this will recreate the images in their absence.
<?php
function scaleCrop($src, $dest, $destW, $destH, $anchor){
if(!file_exists($dest) && is_file($src) && is_readable($src)){
$srcSize = getimagesize($src);
$srcW = $srcSize[0];
$srcH = $srcSize[1];
$srcRatio = $srcW / $srcH;
$destRatio = $destW / $destH;
$img = (imagecreatefromjpeg($src));
$imgNew = imagecreatetruecolor($destW, $destH);
if ($srcRatio < $destRatio){
$scale = $srcW / $destW;
}
elseif($srcRatio >= $destRatio){
$scale = $srcH / $destH;
}
$srcX = ($srcW - ($destW * $scale)) / 2;
if($anchor = 'middle'){
$srcY = ($srcH - ($destH * $scale)) / 2;
}
elseif($anchor = 'top'){
$srcY = 0;
}
elseif($anchor = 'bottom'){
$srcY = $srcH - ($destH * $scale);
}
if($srcX < 0){$srcX = 0;};
if($srcY < 0){$srcY = 0;};
imagecopyresampled($imgNew, $img, 0, 0, $srcX, $srcY, $destW, $destH, $destW * $scale, $destH * $scale);
imagejpeg($imgNew, $dest, 70);
imagedestroy($img);
imagedestroy($imgNew);
}
return $dest;
}
?>
<img src="<?php echo scaleCrop('srcfolder/srcfile.jpg', 'destfolder/destfile.jpg', 320, 240, 'top'); ?>">
here is the website im talking about
http://makeupbyarpi.com/portfolio.php
you'll notice some of the images are smushed width-wise.
the code i used is this:
$width="500";
$height="636";
$img_src = $_FILES['galleryimg']['tmp_name'];
$thumb = "../gallery/".rand(0,100000).".jpg";
//Create image stream
$image = imagecreatefromjpeg($img_src);
//Gather and store the width and height
list($image_width, $image_height) = getimagesize($img_src);
//Resample/resize the image
$tmp_img = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp_img, $image, 0, 0, 0, 0, $width, $height, $image_width, $image_height);
//Attempt to save the new thumbnail
if(is_writeable(dirname($thumb))){
imagejpeg($tmp_img, $thumb, 100);
}
//Free memory
imagedestroy($tmp_img);
imagedestroy($image);
the images that get uploaded are huge sometimes 3000px by 2000px and i have php crop it down to 500 x 536 and some landscape based images get smushed. is there a formula i can use to crop it carefully so that the image comes out good?
thanks
You could resize and add a letterbox if required. You simply need to resize the width and then calculate the new height (assuming width to height ratio is same as original) then if the height is not equal to the preferred height you need to draw a black rectangle (cover background) and then centre the image.
You could also do a pillarbox, but then you do the exact same as above except that width becomes height and height becomes width.
Edit: Actually, you resize the one that is the biggest, if width is bigger, you resize that and if height is bigger then you resize that. And depending on which one you resize, your script should either letterbox or pillarbox.
EDIT 2:
<?php
// Define image to resize
$img_src = $_FILES['galleryimg']['tmp_name'];
$thumb = "../gallery/" . rand(0,100000) . ".jpg";
// Define resize width and height
$width = 500;
$height = 636;
// Open image
$img = imagecreatefromjpeg($img_src);
// Store image width and height
list($img_width, $img_height) = getimagesize($img_src);
// Create the new image
$new_img = imagecreatetruecolor($width, $height);
// Calculate stuff and resize image accordingly
if (($width/$img_width) < ($height/$img_height)) {
$new_width = $width;
$new_height = ($width/$img_width) * $img_height;
$new_x = 0;
$new_y = ($height - $new_height) / 2;
} else {
$new_width = ($height/$img_height) * $img_width;
$new_height = $height;
$new_x = ($width - $new_width) / 2;
$new_y = 0;
}
imagecopyresampled($new_img, $img, $new_x, $new_y, 0, 0, $new_width, $new_height, $img_width, $img_height);
// Save thumbnail
if (is_writeable(dirname($thumb))) {
imagejpeg($new_img, $thumb, 100);
}
// Free up resources
imagedestroy($new_img);
imagedestroy($img);
?>
Sorry it took a while, I ran across a small bug in the calculation part which I was unable to fix for like 10 minutes =/ This should work.