How to change the aspect ratio of images in php?

by jasen_gottlieb , in category: PHP General , 8 months ago

How to change the aspect ratio of images in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 4 months ago

@jasen_gottlieb 

To change the aspect ratio of images in PHP, you can use the GD library which provides functions for image manipulation. Here's an example code snippet that resizes an image while maintaining the aspect ratio:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Load the image
$image = imagecreatefromjpeg('image.jpg');

// Get the current dimensions of the image
$width = imagesx($image);
$height = imagesy($image);

// Specify the new dimensions while maintaining the aspect ratio
$newWidth = 300; // new width
$newHeight = ($height / $width) * $newWidth;

// Create a blank image with the new dimensions
$newImage = imagecreatetruecolor($newWidth, $newHeight);

// Resize the image while maintaining the aspect ratio
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

// Save or output the resized image
imagejpeg($newImage, 'resized_image.jpg'); 

// Free up memory
imagedestroy($image);
imagedestroy($newImage);


In this code snippet, we load an image using imagecreatefromjpeg(), get its current dimensions, calculate the new dimensions to maintain the aspect ratio, create a new blank image with the new dimensions, resize the image using imagecopyresampled(), and save the resized image using imagejpeg(). Finally, we free up the memory using imagedestroy().


You can modify this code snippet based on your specific requirements and image format (e.g., imagecreatefrompng() for PNG images).