php resize image on upload
To resize an image on upload in PHP, you can use the getimagesize
function to determine the dimensions of the image, then use the imagecreatetruecolor
function to create a new image with the desired dimensions. Then use the imagecopyresampled
function to copy and resize the image data from the original image into the new image. Finally, use the imagejpeg
function to output the new image as a JPEG file. Here is an example of how you could do this:
<?php
// get the dimensions of the original image
$original_image = 'original.jpg';
list($width, $height) = getimagesize($original_image);
// calculate the new dimensions
$new_width = 100;
$new_height = 100;
// create a new image with the new dimensions
$new_image = imagecreatetruecolor($new_width, $new_height);
// copy and resize the image data from the original image into the new image
imagecopyresampled($new_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// output the new image as a JPEG file
imagejpeg($new_image, 'resized.jpg');
Watch a video course
Learn object oriented PHP
This code will resize the original image to a width of 100 pixels and a height of 100 pixels, and output the resized image as a JPEG file named "resized.jpg".