Php image src size

Simplified Image Resizing with PHP

Recently, as I built a Website to show off a range of products, I realized that not only was I going to want to use the same product image over and over again, but I was going to want to use that same image at different sizes throughout the site!

I thought to myself, “I don’t feel like having 4,000 different thumbnails on my server for each product, and I don’t want to have the image look all jacked-up and distorted if I hard code the image width and height in my HTML”.

I know what you’re thinking. Why couldn’t I just use something like ImageMagik?

In most cases, I would use ImageMagik so that I could have a regular version and a thumbnail version of each image. But in this particular case, I wanted to be able to display various sizes of the same image, without having 4,000 different thumbnails sitting around taking up space.

So how did I do it? Well, I improvised. I knew these things:

  • I wanted one image per product.
  • I wanted the size of the altered image to keep its aspect ratio, no matter whether it was landscape or portrait.
  • I wanted one script to do all of this dynamically.

So, with the knowledge I’d gained using PHP almost on a daily basis, I sat down and started figuring out a function to achieve these goals. I am by no means a PHP guru — in fact, I taught myself the language sometime in the summer of 2002, so by most standards, I’m still a newbie. But I thought I could create a script that would do exactly what I wanted…

Читайте также:  Server addr and php
Getting Started

Let’s say you have a great line of socks that you want to sell through your site. Well, you’re proud of these fantastic socks and want people to see as much of them as possible: on the product views page, on the search page, on the listing page, etc. But this doesn’t mean that you have to use the default image size each time, nor risk the quality of the image being degraded when it is stretched or crunched into a space. Some socks are longer than others and so you might have the image sizes ranging from 200×400 up to 600×750 pixels.

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).

 $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!

The Function in Action

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.

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).

Now, you may think “This sounds too good to be true. Is there any circumstance where using this technique could prove disastrous?”

Actually, there is. Keep in mind that you aren’t changing the file’s original size. That same 200×400, 50 KB picture you uploaded only moments ago is still 200×400, 50 KB. This script only changes height and width attribute in HTML, so that your original picture conforms to the height and width you think will look best on your Web page.

Having said that, if you have a page that lists 50-something products, the page will display the way you want it to, but uses will have to download all 50 of those 50 KB pictures, which could take some time. So I’d have to recommend this technique in situations where you’re only showing a few pictures at a time.

Share This Article

Greg started his pursuit of knowledge in PHP and MySQL in the Summer of 2002. Currently, NokX is involved in freelance work under the name NokX, but is expanding and joining forces to create a new identity that has yet to be named.

Источник

getimagesize

The getimagesize() function will determine the size of any supported given image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag and the correspondent HTTP content type.

getimagesize() can also return some more information in image_info parameter.

This function expects filename to be a valid image file. If a non-image file is supplied, it may be incorrectly detected as an image and the function will return successfully, but the array may contain nonsensical values.

Do not use getimagesize() to check that a given file is a valid image. Use a purpose-built solution such as the Fileinfo extension instead.

Note: Note that JPC and JP2 are capable of having components with different bit depths. In this case, the value for «bits» is the highest bit depth encountered. Also, JP2 files may contain multiple JPEG 2000 codestreams . In this case, getimagesize() returns the values for the first codestream it encounters in the root of the file.

Note: The information about icons are retrieved from the icon with the highest bitrate.

Note: GIF images consist of one or more frames, where each frame may only occupy part of the image. The size of the image which is reported by getimagesize() is the overall size (read from the logical screen descriptor).

Parameters

This parameter specifies the file you wish to retrieve information about. It can reference a local file or (configuration permitting) a remote file using one of the supported streams.

This optional parameter allows you to extract some extended information from the image file. Currently, this will return the different JPG APP markers as an associative array. Some programs use these APP markers to embed text information in images. A very common one is to embed » IPTC information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable.

Note:

The image_info only supports JFIF files.

Return Values

Returns an array with up to 7 elements. Not all image types will include the channels and bits elements.

Index 0 and 1 contains respectively the width and the height of the image.

Note:

Some formats may contain no image or may contain multiple images. In these cases, getimagesize() might not be able to properly determine the image size. getimagesize() will return zero for width and height in these cases.

Index 2 is one of the IMAGETYPE_XXX constants indicating the type of the image.

Index 3 is a text string with the correct height=»yyy» width=»xxx» string that can be used directly in an IMG tag.

mime is the correspondant MIME type of the image. This information can be used to deliver images with the correct HTTP Content-type header:

Example #1 getimagesize() and MIME types

channels will be 3 for RGB pictures and 4 for CMYK pictures.

bits is the number of bits for each color.

For some image types, the presence of channels and bits values can be a bit confusing. As an example, GIF always uses 3 channels per pixel, but the number of bits per pixel cannot be calculated for an animated GIF with a global color table.

On failure, false is returned.

Errors/Exceptions

If accessing the filename image is impossible getimagesize() will generate an error of level E_WARNING . On read error, getimagesize() will generate an error of level E_NOTICE .

Changelog

Version Description
8.2.0 Now returns the actual image dimensions, bits and channels of AVIF images; previously, the dimensions were reported as 0x0 , and bits and channels were not reported at all.
7.1.0 Added WebP support.

Examples

Example #2 getimagesize() example

\"getimagesize()

list( $width , $height , $type , $attr ) = getimagesize ( «img/flag.jpg» );
echo «» ;
?>

Example #3 getimagesize (URL)

$size = getimagesize ( «http://www.example.com/gifs/logo.gif» );

// if the file name has space in it, encode it properly
$size = getimagesize ( «http://www.example.com/gifs/lo%20go.gif» );

Example #4 getimagesize() returning IPTC

$size = getimagesize ( «testimg.jpg» , $info );
if (isset( $info [ «APP13» ])) $iptc = iptcparse ( $info [ «APP13» ]);
var_dump ( $iptc );
>
?>

Notes

Note:

This function does not require the GD image library.

See Also

  • image_type_to_mime_type() — Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
  • exif_imagetype() — Determine the type of an image
  • exif_read_data() — Reads the EXIF headers from an image file
  • exif_thumbnail() — Retrieve the embedded thumbnail of an image
  • imagesx() — Get image width
  • imagesy() — Get image height

User Contributed Notes 24 notes

As noted below, getimagesize will download the entire image before it checks for the requested information. This is extremely slow on large images that are accessed remotely. Since the width/height is in the first few bytes of the file, there is no need to download the entire file. I wrote a function to get the size of a JPEG by streaming bytes until the proper data is found to report the width and height:

// Retrieve JPEG width and height without downloading/reading entire image.
function getjpegsize ( $img_loc ) $handle = fopen ( $img_loc , «rb» ) or die( «Invalid file stream.» );
$new_block = NULL ;
if(! feof ( $handle )) $new_block = fread ( $handle , 32 );
$i = 0 ;
if( $new_block [ $i ]== «\xFF» && $new_block [ $i + 1 ]== «\xD8» && $new_block [ $i + 2 ]== «\xFF» && $new_block [ $i + 3 ]== «\xE0» ) $i += 4 ;
if( $new_block [ $i + 2 ]== «\x4A» && $new_block [ $i + 3 ]== «\x46» && $new_block [ $i + 4 ]== «\x49» && $new_block [ $i + 5 ]== «\x46» && $new_block [ $i + 6 ]== «\x00» ) // Read block size and skip ahead to begin cycling through blocks in search of SOF marker
$block_size = unpack ( «H*» , $new_block [ $i ] . $new_block [ $i + 1 ]);
$block_size = hexdec ( $block_size [ 1 ]);
while(! feof ( $handle )) $i += $block_size ;
$new_block .= fread ( $handle , $block_size );
if( $new_block [ $i ]== «\xFF» ) // New block detected, check for SOF marker
$sof_marker = array( «\xC0» , «\xC1» , «\xC2» , «\xC3» , «\xC5» , «\xC6» , «\xC7» , «\xC8» , «\xC9» , «\xCA» , «\xCB» , «\xCD» , «\xCE» , «\xCF» );
if( in_array ( $new_block [ $i + 1 ], $sof_marker )) // SOF marker detected. Width and height information is contained in bytes 4-7 after this byte.
$size_data = $new_block [ $i + 2 ] . $new_block [ $i + 3 ] . $new_block [ $i + 4 ] . $new_block [ $i + 5 ] . $new_block [ $i + 6 ] . $new_block [ $i + 7 ] . $new_block [ $i + 8 ];
$unpacked = unpack ( «H*» , $size_data );
$unpacked = $unpacked [ 1 ];
$height = hexdec ( $unpacked [ 6 ] . $unpacked [ 7 ] . $unpacked [ 8 ] . $unpacked [ 9 ]);
$width = hexdec ( $unpacked [ 10 ] . $unpacked [ 11 ] . $unpacked [ 12 ] . $unpacked [ 13 ]);
return array( $width , $height );
> else // Skip block marker and read block size
$i += 2 ;
$block_size = unpack ( «H*» , $new_block [ $i ] . $new_block [ $i + 1 ]);
$block_size = hexdec ( $block_size [ 1 ]);
>
> else return FALSE ;
>
>
>
>
>
return FALSE ;
>
?>

There’s a code snippet for getting JPEG image dimensions by getting only first few bytes of the file, but it doesn’t work for PNG files, so I wrote one. It will download only the first 24 bytes instead of the whole image, and thus being much faster than getimagesize() and it will save bandwidth at the same time:

// Retrieve PNG width and height without downloading/reading entire image.
function getpngsize ( $img_loc ) $handle = fopen ( $img_loc , «rb» ) or die( «Invalid file stream.» );

Источник

Оцените статью