亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Introduction
1. Preparation
2. Calling the Object
3. Create the Class Skeleton
5. Opening the Image
7. Resizing. Let's Do It!
10. Crop
11. Save the Image
Conclusion
Home Backend Development PHP Tutorial Image Resizing Made Easy With?PHP

Image Resizing Made Easy With?PHP

Mar 01, 2025 am 10:23 AM

Image Resizing Made Easy With?PHP

Ever wanted an all-purpose, easy-to-use method of resizing your images in PHP? Well, that's what PHP classes are for—reusable pieces of functionality that we call to do the dirty work behind the scenes. We're going to learn how to create our own class that will be well constructed and expandable.?

Introduction

To give you a quick glimpse of what we're trying to achieve with our class, the class should be:

  • easy to use
  • format independent: can open, resize, and save a number of different image formats
  • intelligent sizing: no image distortion!
This isn't a tutorial on how to create classes and objects, and although this skill would help, it isn't necessary in order to follow this tutorial.

There's a lot to cover—let's begin.


1. Preparation

The first step is easy. In your working directory, create two files: one called index.php and the other resize-class.php


2. Calling the Object

To give you an idea of what we're trying to achieve, we'll begin by coding the calls we'll use to resize the images. Open your index.php file and add the following code.

As you can see, there is a nice logic to what we're doing. We open the image file, and we set the dimensions we want to resize the image to and the type of resizing. Then we save the image, choosing the image format and quality we want. Save and close your index.php file.

// *** Include the class<br>include("resize-class.php");<br><br>// *** 1) Initialize / load image<br>$resizeObj = new resize('sample.jpg');<br><br>// *** 2) Resize image (options: exact, height, width, auto, crop)<br>$resizeObj -> resizeImage(150, 100, 'crop');<br><br>// *** 3) Save image<br>$resizeObj -> saveImage('sample-resized.gif', 100);<br>

From the code above, you can see we're opening a jpg file but saving a gif. Remember, it's all about flexibility.


3. Create the Class Skeleton

It's Object-Oriented Programming (OOP) that makes this sense of ease possible. Think of a class like a pattern; you can encapsulate the data—another jargon term that really just means hiding the data. We can then reuse this class over and over without the need to rewrite any of the resizing code—you only need to call the appropriate methods, just as we did in step 2. Once our pattern has been created, we create instances of this pattern, called objects.

Let's begin creating our resize class. Open your resize-class.php file. Below is a really basic class skeleton structure which I've named $fileName.

We need to open the file passed in with PHP (more specifically the PHP GD Library) so PHP can read the image. We're doing this with the custom method $image as a private variable by typing private, you're limiting the scope of that variable so it can only be accessed by the class. From now on, we can make a call to our opened image, known as a resource, which we will be doing later when we resize.

While we're at it, let's store the height and width of the image. I have a feeling these will be useful later.

You should now have the following.

// *** Include the class<br>include("resize-class.php");<br><br>// *** 1) Initialize / load image<br>$resizeObj = new resize('sample.jpg');<br><br>// *** 2) Resize image (options: exact, height, width, auto, crop)<br>$resizeObj -> resizeImage(150, 100, 'crop');<br><br>// *** 3) Save image<br>$resizeObj -> saveImage('sample-resized.gif', 100);<br>

The imagesy() methods are built-in functions that are part of the GD library. They retrieve the width and height of your image, respectively.


5. Opening the Image

In the previous step, we called the custom method strrchr() function in PHP, which returns part of the main string from the last occurrence of the specified character till its end. For example, the filename papaya.jpg will give us .jpg, and the filename i.like.papaya.jpg will also give us .jpg.

After determining the extension, we use the appropriate exact)

  • Resize by width—exact width will be set, height will be adjusted according to aspect ratio. (height)
  • Auto-determine options 2 and 3. If you're looping through a folder with different size photos, let the script determine how to handle this. (crop)

  • 7. Resizing. Let's Do It!

    There are two parts to the resize method. The first is getting the optimal width and height for our new image by creating some custom methods—and of course passing in our resize option as described above. The width and height are returned as an array and set to their respective variables. Feel free to pass by reference—but I'm not a huge fan of that.

    The second part is what performs the actual resizing. We will be using two built-in PHP functions for our resizing. They are:

    • imagecopyresampled

    I recommend that you read about them in the documentation.

    In short, the imagecopyresampled() function is used to copy and resize part of an image with resampling.

    We also save the output of the private $imageResized; with your other class variables.

    Resizing is performed by a PHP module known as the GD Library. Many of the methods we're using are provided by this library.

    		Class resize<br>		{<br>			// *** Class variables<br>			private $image;<br>			private $width;<br>			private $height;<br><br>			function __construct($fileName)<br>			{<br>			    // *** Open up the file<br>			    $this->image = $this->openImage($fileName);<br><br>			    // *** Get width and height<br>			    $this->width  = imagesx($this->image);<br>			    $this->height = imagesy($this->image);<br>			}<br>		}<br>

    In the above code snippet, we calculate the new image dimensions and create a true color image object accordingly. This image object is then passed to height or auto, we use the original width and height of the image to determine whether the resized image should have a fixed width or height. For images in landscape orientation, we keep the width fixed. For images in portrait orientation, we keep the height fixed. If the original image is a square, we pick the fixed dimension using the new width and height value.

    // *** Add to class variables<br>private $imageResized;<br><br>public function resizeImage($newWidth, $newHeight, $option="auto")<br>{<br><br>	// *** Get optimal width and height - based on $option<br>	$optionArray = $this->getDimensions($newWidth, $newHeight, strtolower($option));<br><br>	$optimalWidth  = $optionArray['optimalWidth'];<br>	$optimalHeight = $optionArray['optimalHeight'];<br><br>	// *** Resample - create image canvas of x, y size<br>	$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);<br>	imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);<br><br>	// *** if option is 'crop', then crop too<br>	if ($option == 'crop') {<br>		$this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);<br>	}<br>}<br>

    The $optimalHeight and $optimalWidth<code>$optimalWidth, which we use for resizing. The reason is that instead of cropping the image directly to the specified width and height, our class crops the images after resizing.

    Let's say the dimensions of an image are 1920w and 1080h, and you want to crop it to 1200w and 200h. As you can see, the ratio of the original width to the new width will be lower than the corresponding height ratio. Therefore, the image will first need to be resized in such a way that its width comes down to 1200 and the height changes accordingly.

    The actual cropping of the image will be done after the resizing is complete.


    10. Crop

    If you opted for a crop—that is, you've used the crop option—then you have one more little step. We're going to crop the image from the center. Cropping is a very similar process to resizing but with a couple more sizing parameters passed in.

    // *** Include the class<br>include("resize-class.php");<br><br>// *** 1) Initialize / load image<br>$resizeObj = new resize('sample.jpg');<br><br>// *** 2) Resize image (options: exact, height, width, auto, crop)<br>$resizeObj -> resizeImage(150, 100, 'crop');<br><br>// *** 3) Save image<br>$resizeObj -> saveImage('sample-resized.gif', 100);<br>

    11. Save the Image

    We're getting there; almost done. It's now time to save the image. We pass in the path and specify the image quality we would like ranging from 0-100, 100 being the best. Then we call the appropriate method. A couple of things to note about the image quality: JPG uses a scale of 0-100, 100 being the best. GIF images don't have an image quality setting. PNGs do, but they use the scale 0-9, 0 being the best. This isn't good as we can't expect ourselves to remember this every time we want to save an image. So we can do a bit of magic to standardize everything.

    		Class resize<br>		{<br>			// *** Class variables<br>			private $image;<br>			private $width;<br>			private $height;<br><br>			function __construct($fileName)<br>			{<br>			    // *** Open up the file<br>			    $this->image = $this->openImage($fileName);<br><br>			    // *** Get width and height<br>			    $this->width  = imagesx($this->image);<br>			    $this->height = imagesy($this->image);<br>			}<br>		}<br>

    Now is also a good time to destroy our image resource to free up some memory. If you were to use this in production, it might also be a good idea to capture and return the result of the saved image.


    Conclusion

    Well, that's it, folks. Thank you for following this tutorial, and I hope you find it useful.

    This post has been updated with contributions from?Monty Shokeen. Monty is a full-stack developer who also loves to write tutorials and to learn about new JavaScript libraries.

    The above is the detailed content of Image Resizing Made Easy With?PHP. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    php regex for password strength php regex for password strength Jul 03, 2025 am 10:33 AM

    To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

    How to combine two php arrays unique values? How to combine two php arrays unique values? Jul 02, 2025 pm 05:18 PM

    To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

    PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

    Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

    How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

    To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

    Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

    There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

    How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

    AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

    Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

    The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

    How to create an array in php? How to create an array in php? Jul 02, 2025 pm 05:01 PM

    There are two ways to create an array in PHP: use the array() function or use brackets []. 1. Using the array() function is a traditional way, with good compatibility. Define index arrays such as $fruits=array("apple","banana","orange"), and associative arrays such as $user=array("name"=>"John","age"=>25); 2. Using [] is a simpler way to support since PHP5.4, such as $color

    See all articles