Solved

Aspect Ratios with .jpg Files - Help!

Posted on 2003-11-09
11
602 Views
Last Modified: 2013-12-13
I'm trying to figure out how to write some php code that will allow me to resize a .jpg image and maintain it's aspect ratio - I'd like to change it's width and height yet not make it look too streched in one direction or the other - any help or idea's would be appreciated.

Thanks...
0
Comment
Question by:rfresh
  • 6
  • 4
11 Comments
 
LVL 6

Expert Comment

by:DoppyNL
ID: 9712775
If you only want to display the image smaller (ie: not create a new image) then this code can be informing:

$size = get_image_size('filename'); // manualpage: http://www.php.net/get_image_size

$size[0] contains width of the image (200)
$size[1] contains height of the image (300)
$size[2] contains flag for imagetype (see manual page)
$size[3] contains string you can use in html (height="yyy" width="xxx")

using the info from $size[0] and $size[1] you can set the width and height in your html.

if you want to actually create a new image; you will have to use the GD library, in wich case someone else will have to help you :-/
0
 
LVL 4

Expert Comment

by:intrwrks
ID: 9734817
Here is a function that will resize your images for you.

$image_file_path = path and name to the image you are wanting to resize.
$new_image_file_path = path and name that you want to save the image to. This directory will need write permissions.
$max_width = the maximum size you want the width to be.
$max_height = the maximum size you want the height to be.

Specify either the width or the height and it will adjust the other one to the size it should be.

function resize_jpeg( $image_file_path, $new_image_file_path, $max_width=1600, $max_height=1600 )
{
     
    $return_val = 1;
     
    $return_val = ( ($img = ImageCreateFromJPEG ( $image_file_path )) && $return_val == 1 ) ? "1" : "0";
     
    $FullImage_width = imagesx ($img);    // Original image width
    $FullImage_height = imagesy ($img);    // Original image height
     
            // now we check for over-sized images and pare them down
            // to the dimensions we need for display purposes
    $ratio =  ( $FullImage_width > $max_width ) ? (real)($max_width / $FullImage_width) : 1 ;
    $new_width = ((int)($FullImage_width * $ratio));    //full-size width
    $new_height = ((int)($FullImage_height * $ratio));    //full-size height
            //check for images that are still too high
    $ratio =  ( $new_height > $max_height ) ? (real)($max_height / $new_height) : 1 ;
    $new_width = ((int)($new_width * $ratio));    //mid-size width
    $new_height = ((int)($new_height * $ratio));    //mid-size height
     
            // --Start Full Creation, Copying--
    // now, before we get silly and 'resize' an image that doesn't need it...
    if ( $new_width == $FullImage_width && $new_height == $FullImage_height )
        copy ( $image_file_path, $new_image_file_path );
     
    $full_id = ImageCreateTrueColor( $new_width , $new_height );        //create an image
    ImageCopyResized( $full_id, $img,
                    0,0,  0,0, //starting points
                    $new_width, $new_height,
                    $FullImage_width, $FullImage_height );
    $return_val = ( $full = ImageJPEG( $full_id, $new_image_file_path, 80 )
                 && $return_val == 1 ) ? "1" : "0";
    ImageDestroy( $full_id );
            // --End Creation, Copying--
     
    return ($return_val) ? TRUE : FALSE ;
     
}
0
 

Author Comment

by:rfresh
ID: 9741476
intrwrks -

Can you give me an example of how I would call this function? It looks like I need to be using some kind of image object to receive the function value? How would this syntax look in PHP?

Thanks...

0
 
LVL 4

Expert Comment

by:intrwrks
ID: 9741734
You can use any image that is accessible by your webserver. In the example below I have a JPEG in an images directory called img1.jpg. I want to create a thumbnail of that image that is no wider or higher than 50. I am going to save that image to the images directory as img_thumb.jpg.

The original file that I used as an example was 1152 x 1767. The new thumbnail image that was output was 32 x 50.

// the file to be created
$imgthumb = "images/img_thumb.jpg";

// call the function and get the return value... either true or false
$result = resize_jpeg("images/img1.jpg", $imgthumb, 50, 50);
?>

<html>
<head>
<title>Image Resized</title>
</head>

<body>

<?php
// if the image was successfully resized... show it.
if($result)
      echo "<img src=\"$imgthumb\">";
?>

</body>
</html>
0
 
LVL 4

Expert Comment

by:intrwrks
ID: 9741815
BTW: The newer version of PHP has more security and the above function will not over-write a file that already exists. You will need to add something like this to the above example before you call the resize_jpeg() function:

if (file_exists($imgthumb))
     unlink($imgthumb);
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:rfresh
ID: 9743139
I see - I'm sorry I didn't clarify in my orignal post - I don't want to actually create a new file on the sever, I need to reduce the size of the image so I can use it as a small 'thumbnail' image on an html page inside <TR><TD> tags - so in other words, the smaller image is a temp just for the thumbnail display on the web page - while the original image *is* on the server, I don't want to write additonal images on the server for this thumbnail purpose - I'd prefer to just generate the smaller image on the fly - I think we're very close eh?

Thanks...
0
 
LVL 4

Expert Comment

by:intrwrks
ID: 9747561
Try this... Instead of using a function, like above, you will need to have the code that resizes the jpeg in its own file.

+++++ Code to resize jpeg - makethumb.php
<?php
$max_height = 100;
$max_width = 100;
$image_file_path = $file;

$img = ImageCreateFromJPEG ( $image_file_path );
     
$FullImage_width = imagesx ($img);    // Original image width
$FullImage_height = imagesy ($img);    // Original image height
     
            // now we check for over-sized images and pare them down
            // to the dimensions we need for display purposes
$ratio =  ( $FullImage_width > $max_width ) ? (real)($max_width / $FullImage_width) : 1 ;
$new_width = ((int)($FullImage_width * $ratio));    //full-size width
$new_height = ((int)($FullImage_height * $ratio));    //full-size height

          //check for images that are still too high
$ratio =  ( $new_height > $max_height ) ? (real)($max_height / $new_height) : 1 ;
$new_width = ((int)($new_width * $ratio));    //mid-size width
$new_height = ((int)($new_height * $ratio));    //mid-size height
     
$full_id = ImageCreateTrueColor( $new_width , $new_height );        //create an image
ImageCopyResized( $full_id, $img,
                    0,0,  0,0, //starting points
                    $new_width, $new_height,
                    $FullImage_width, $FullImage_height );
ImageJPEG( $full_id );
ImageDestroy( $full_id );
ImageDestroy( $img );
?>


++++ PHP File that will show the image - index.php
<html>
<head>
<title>Image Resized</title>
</head>

<body>

<?php
echo "<img src=\"makethumb.php?file=images/img1.jpg\" border=\"0\">";
?>

</body>
</html>
0
 

Author Comment

by:rfresh
ID: 9750942
I can't get the <img tag line to work:

echo "<img src=\"makethumb.php?file=images/img1.jpg\" border=\"0\">";

In your makethumb.php file don't you have to use $_GET[] to grab the filename argument? How does makethumb.php know what '$file' is in makethumb.php:

$image_file_path = $file;

I tried adding the $_GET["file"] statement and put a print statement below it but it printed nothing so the filename isn't getting passed to makethumb.php for some reason. I'm calling it from a different .php file which is OK I think. I checked the name of my image on the sever and the filename is correct and I added a print statement in my calling .php file just before the <img tag and the filename is OK - I'm using a folder called 'uploads' but I made that change so that should not matter.

I'm sorry I can't follow your code that well - I've been programming in PHP for only 6 months.

Thanks...
0
 
LVL 4

Expert Comment

by:intrwrks
ID: 9751070
Yes, it is appropriate and recommended that you use $_GET[]. Make sure you use single quotes $_GET['file'] and not the double quotes.

$image_file_path = $_GET['file'];
0
 

Author Comment

by:rfresh
ID: 9751685
This line is not being called for some reason - I have a print statement in makethumb.php and it's not displaying the test message - so that means makethumb.php is not getting called -

echo "<img src=\"makethumb.php?file=uploads/ferris wheel.jpg\" border=\"0\">";

Other than a different image folder and filename, it's the same line as what you provided in your makethumb.php file.

Got any idea why it isn't callng makethumb.php ?

Thanks....
0
 
LVL 4

Accepted Solution

by:
intrwrks earned 125 total points
ID: 9752674
Because of the way we are calling the makethumb.php file, you shouldn't see any print or echo statements on the screen. Lets try calling makethumb.php directly, so that you can see any errors that might be happening in the file. You should be able to put the line directly in your browser...

ie. http://localhost/makethumb.php?file-uploads/ferris wheel.jpg.

If all print and echo statements are removed and it is working properly it should output a picture directly to your browser screen. If there are print and echo statements it will show what you told it to at the beginning or end of a bunch of strange characters

Also I am assuming that you are using the latest PHP and GD. Older versions do not support the ImageCreateTrueColor() function. You can try changing the following line:

$full_id = ImageCreateTrueColor( $new_width , $new_height );        //create an image

to

$full_id = ImageCreate( $new_width , $new_height );        //create an image

I hope that this will help you find the problem.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
The viewer will learn how to dynamically set the form action using jQuery.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now