PHP script to calculate image width and height ratio? - php

I am trying to find a way to calculate an image width/height ratio
to resize it and keep the proportions.
For example, I want to resize a 500x750 image and reduce its width to 350. What height should I use that is proportional to 350?

Use Javascript.
See this tutorial:
http://www.ajaxblender.com/howto-resize-image-proportionally-using-javascript.html
Using the function the other guy posted:
<?PHP
$imagePath = "images/your_image.png";
list($oldWidth, $height, $type, $attr) = getimagesize($image_path);
$percentChange = $newWidth / $oldWidth;
$newHeight = round( ( $percentChange *$height ) );
echo '<img src="'.$imagePath.'" height="'.$new_height.'" width="'.$newWidth.'">';
?>

I think this is the php function you're looking for: getimagesize
From the manual:
Returns an array with 7 elements.
Index 0 and 1 contains respectively the width and the height of the
image.
Here's a short example how to work with this for your problem:
// get the current size of your image
$data = getimagesize('link/your/image.jpg');
// your defined width
$new_width = 350;
// calculate the ratio
$ratio = $data[0] / $new_width;
// apply the ratio to get the new height of your image
$new_height = round($data[1] / $ratio);
...done!

use getImagesize and get the new height by dividing by the aspect ratio.
list($width, $height, $type, $attr) = getimagesize("image.jpg");
$aspect = $width / $height;
$newWidth = 350;
$newHeight = $newWidth / $aspect;

You tagged your question with the PHP tag, so assuming you want to use PHP:
To get an image's height or width from an image resource, use imagesx() and imagesy(). http://www.php.net/manual/en/function.imagesx.php
http://www.php.net/manual/en/function.imagesy.php
To get an image's height and width from an image file, use getimagesize(). Items 0 and 1 in the array returned by that function are the width and height of the image.
http://www.php.net/manual/en/function.getimagesize.php
If you have an image that is 500 pixels wide and 750 pixels high, and you have a container that is 350 pixels wide, you can calculate the ratio by dividing the desired width by the actual width: 350/500 which is 0.7. So to calculate the height, multiply it by that ratio (750 * 0.7 or 525).

Related

PHP image resize depending on height

Hey all i am trying to figure out how to resize an image that has a higher height than width. The normal width and height of the area where the image needs to be displayed is:
width = 1000px
height = 700px
What type of math would i need in order to resize that to the proper width/height above without screwing it?
The test image size is:
width = 1451
height = 2200
I was thinking of doing this:
(700/org.height)
But that does not come up with the correct number of 462.
In photoshop, changing the height to 700 yields a width value of 462.
so you want to scale your image so that it fits as large as possible within a 1000x700 square without stretching it? You could do something like this:
$availH = 700;
$availW = 1000;
$imageH = 2200;
$imageW = 1451;
// you know you want to limit the height to 700
$newH = $availH;
// figure out what the ratio was that you adjusted (will equal aprox 0.3181)
$ratio = $availH / $imageH;
// now that you have the $ratio you can apply that to the width (will equal 462)
$newW = round(imageW * $ratio);
Now you have $newW and $newH which are the new sizes for your image properly scaled. You could of course condense this down but I've written it out so each step is more clear.
Formula to keep aspect ratio when resizing is
original height / original width x new width = new height
Source: http://andrew.hedges.name/experiments/aspect_ratio/
But you want to switch it around to the following I think:
original width / original height x new height = new width

Create fixed thumbnail dimensions for images with different sizes

I just want to know if it is possible to get different images' sizes, and create fixed thumbnail dimension measurements for these pictures without losing their accurate aspect ratios.
So far, I have made these:
Resize different images
Maintain their aspect ratios
NOT supplying the same size (for example: 100px- height and 100px- width)
Here's the code that I am working with:
<?php
require("dbinfo.php");
$allPhotosQuery = mysql_query (" SELECT * FROM `placesImages` ");
while ($allPhotosArray = mysql_fetch_assoc ($allPhotosQuery))
{
$filename= $allPhotosArray['fileName'];
$placeId = $allPhotosArray['placeId'];
$imagePath = "placesImages/" . $placeId . "/" . $filename;
$imageSize = getimagesize($imagePath);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$newSize = ($imageWidth + $imageHeight)/($imageWidth*($imageHeight/45));
$newHeight = $imageHeight * $newSize;
$newWidth = $imageWidth * $newSize;
echo "<img src='".$imagePath."' width='".$newWidth."' height='".$newHeight."' />";
}
?>
Short of cropping, the simplest way to maintain aspect ratio while making a thumbnail is to do something similar to what you have, but set one fixed:
For example, if you want all your tumbs to be 100px wide:
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$ratio=ImageWidth/$imageHeight;
$newHeight=(int)$ratio*100;
$newWidth=100;
The caveat with this is that you might end up with some funny sizes if the image has a funny ratio - as in it will happily go ahead and just do it. It might be a good idea to put some sort of check on the ratio in your code - if it it too low or too high, do something else, otherwise use this standard process.
feed this function your original image width and heights followed by the maximum constraints of your thumbnail limits and it will spit out an array with x/y of what you should set your thumbnail at to maintain aspect ratio. (anything smaller than the thumbnail will be enlarged)
function imageResizeDimensions($source_width,$source_height,$thumb_width,$thumb_height)
{
$source_ratio = $source_width / $source_height;
$thumb_ratio = $thumb_width / $thumb_height;
if($thumb_ratio > $source_ratio)
{
return array('x'=>$thumb_height * $source_ratio,'y'=>$thumb_height);
}
elseif($thumb_ratio < $source_ratio)
{
return array('x'=>$thumb_width,'y'=>$thumb_width/$source_ratio);
}
else
{
return array('x'=>$thumb_width,'y'=>$thumb_width);
}
}
Let’s begin with two constants, thumb_width and thumb_height, which are the desired width and height of your thumbnail images. They can be equal, but don’t have to be.
If you have an image that’s wider than it is tall (landscape) we can set the width to the desired width of the thumbnail, thumb_width, and adjust the height to maintain the aspect ratio.
new_width = thumb_width
new_height = thumb_height * old_height / old_width
See imagecreatetruecolor.
Then you can move the image to center it vertically within the limits of the thumbnail, producing a letterbox effect. See imagecopyresampled.
new_y = (thumb_height - new_height) / 2
For images that are taller than they are wide (portrait) the procedure is the same, but the math is a little different.
new_height = thumb_height
new_width = thumb_width * old_width / old_height
Then you can center it horizontally within the limits of the thumbnail.
new_x = (thumb_width - new_width) / 2
For more information on the basics of creating thumbnail images see Resizing images in PHP with GD and Imagick

Resize images of every size to fixed width and height

I tried a lot of methods to do that, but I still have a lot of troubles with that.
Is it possible to resize all images to fixed width and height?
I want every uploaded image with width>=200px and height>=260px to be resized to width=200px and height=260px, but I want to keep a bit of proportionality and if image is bigger than 200x260px to resize it proportionally and then to capture center of image 200x260px.
I just need idea to know where to start and what to do, but if you have an example I would like to see it. Thanks.
If you want to trim the image you can do in the following way:-
//Your Image
$imgSrc = "image.jpg";
//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 = 100;
$thumb = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);
//final output
header('Content-type: image/jpeg');
imagejpeg($thumb);
To begin writing the function, we have to declare it as such… Then we have to throw in our attributes. We want to restrict our image, so we have to let the function know the dimensions to which we want to restrict it, and we have to know what the original image size is to begin with (we’ll get to that part in a second).
<?php
function imageResize($width, $height, $target) {
//takes the larger size of the width and height and applies the
formula accordingly...this is so this script will work
dynamically with any size image
if ($width > $height) {
$percentage = ($target / $width);
} else {
$percentage = ($target / $height);
}
//gets the new value and applies the percentage, then rounds the value
$width = round($width * $percentage);
$height = round($height * $percentage);
//returns the new sizes in html image tag format...this is so you
can plug this function inside an image tag and just get the
return "width=\"$width\" height=\"$height\"";
}
?>
Before we take our new function on a test drive, we need to get the width and height of the image that we want to display. There is a magical command in PHP called getimagesize(). This command, used properly, will return the image width, height, type, and even the width and height in HTML image tag format (width=”x” height=”y”).
$mysock = getimagesize("images/sock001.jpg");
Now, $mysock is an array that holds vital information about the particular image we want to display. In index 0, we have the width ($mysock[0]), and in index 1, we have the height ($mysock[1]). That’s really all we need, in order to get what we want done. Want to see the function… well, function? Here we go!
Let’s say you want to display a list of your beautiful socks, but you want room on the page to show them neatly in a row, and to do that they cannot be larger than 150 pixels tall or wide.
<?php
//get the image size of the picture and load it into an array
$mysock = getimagesize("images/sock001.jpg");
?>
<!-using a standard html image tag, where you would have the
width and height, insert your new imageResize() function with
the correct attributes -->
<img src="images/sock001.jpg" <?php imageResize($mysock[0],
$mysock[1], 150); ?>>
That’s it! Now, no matter what the original file size, it will be restricted to no more than 150 pixels in width or height (or whatever you specify).

How to restrict image width or height on upload

I would like manipulate/resize images in a similar way to Pinterest but I am not sure what is the best way to approach it. The goal is to allow a mix of both portrait and landscape images but put some restrictions on the maximum height and width.
The problem i can see is that if I resize to a width, a portrait image may become too thin, and the opposite it true for a landscape image.
Any ideas on how to achieve those sort of results with PHP?
You just need to understand which of the two edges of the image is longer, and compute the other dimension proportionally. If the maximum long-egde is 1024, then if one of the two edges is larger you will set that to 1024, and compute the other to fit the proportions. Then you will pass those two values to your image management functions.
Like here:
http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/
Or here:
http://www.9lessons.info/2009/03/upload-and-resize-image-with-php.html
try with this
$needheight = 1000;
$needwidth = 1000;
$arrtest = getimagesize($upload_image_physical_path);
$actualwidth = $arrtest[0];
$actualheight = $arrtest[1];
if($needwidth > $actualwidth || $needheight > $actualheight){
//uplaod code
}
cheers
Check for a max size and then resize based on a ratio. Here's a pseudo code example:
if($imageHeight > $maxHeight) {
$newHeight = $maxHeight;
$newWidth = $imageWidth * ($maxHeight / $imageHeight);
}
if($imageWidth > $maxWidth) {
$newWidth = $maxWidth;
$newHeight = $imageHeight * ($maxWidth / $imageWidth);
}
resize($image, $newWidth, $newHeight);
It first checks the height and if the height is greater, it scales it down. Then it checks the width. If the width is too big, it scales it down again. The end result, both height and width will be with in your bounds. It uses the ratio to do the scaling.
Note, this is pseudocodish. The actual resize function call will depend on your image manipulation library -- same goes for calls to obtain image size.

Resize image with PHP, detect longest side, and resize according?

I'm working on an image upload script with PHP, I found one someone was offering and tried modifying it, however, i'm running into a few problems.
I want to do the following:
Detect the longest side of the image (ie. portrait or landscape)
And then resize the image, with the longest side being 800px AND keep proportions.
Here is the code I have so far.. For landscape images it works fine, but with portrait ones it distorts them like crazy.
PS. I'm making a larger image as well as a thumbnail.
list($width,$height)=getimagesize($uploadedfile);
if($width > $height){
$newwidth=800;
$newheight=($height/$width)*$newwidth;
$newwidth1=150;
$newheight1=($height/$width)*$newwidth1;
} else {
$newheight=800;
$newwidth=($height/$width)*$newheight;
$newheight1=150;
$newwidth1=($height/$width)*$newheight;
}
$tmp=imagecreatetruecolor($newwidth,$newheight);
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
You're probably mistaking:
When $width > $height that means it's landscape. Setting maxwidth to 800 means (height/width)*800 = new height. On the other hand $height > $width means setting maxheight to 800 and thus having (width/height)*800 is new width.
Right now your using both the height/width ratio instead of the other way around. Example:
Image: 1600 (w) x 1200 (h)
Type: Landscape
New Width: 800
New Height: (1200 (h) / 1600(w) * 800 (nw) = 600
Image 1200 (w) x 1600 (h)
Type: Portrait
New Height: 800
New Width: (1200 (w) / 1600(h) * 800 (nh) = 600
Hope you get what I'm saying, you just switched them :) Also notice that you multiply with $newheight instead of $newheight1 for the portrait thumbnail
You can take a look in this function I use in my Image class:
public function ResizeProportional($MaxWidth, $MaxHeight)
{
$rate = $this->width / $this->height;
if ( $this->width / $MaxWidth > $this->height / $MaxHeight )
return $this->Resize($MaxWidth, $MaxWidth / $rate);
else
return $this->Resize($MaxHeight * $rate, $MaxHeight);
}
Basically it first calculates the image's proportions in $rate based on width/height. Then it checks if the width is going to get out of bounds when resized ( $this->width / $MaxWidth > $this->height / $MaxHeight ) and if it is - sets width to the desired maximum width and calculates the height accordingly.
$this->width / $MaxWidth is the percentage of the image's width based on the maximum one. So if $this->width / $MaxWidth is larger than $this->height / $MaxHeight the width should be set to maxwidth and the height should be calculated based on it. If the comparison is the other way around just set height to maxheight and calculate the new width.
You should switch height and width in the second part, note the ($width/$height) part:
} else {
$newheight=800;
$newwidth=($width/$height)*$newheight;
$newheight1=150;
$newwidth1=($width/$height)*$newheight;
}

Categories