Efficient PHP Image Upload with Automatic Resizing for Optimal Performance



/**
* @param $imageFile
* @param int $maxWidth
* @return string|null
*/
public static function UploadImage($imageFile, $maxWidth = 300) {
try {
// Input validation
if (!isset($imageFile['error']) || $imageFile['error'] !== UPLOAD_ERR_OK) {
throw new \Exception('Invalid file upload.');
}

$extension = pathinfo($imageFile['name'], PATHINFO_EXTENSION);
$validExtensions = ["png", "jpg", "jpeg", "gif", "webp"];
if (!in_array(strtolower($extension), $validExtensions)) {
throw new \Exception('Invalid file type. You can only upload ' . implode(", ", $validExtensions) . ' files.');
}

$name = generateRandomString(5) . "_" . time();
$path = "Uploads/Images/";

// Path concatenation using sprintf
$filePath = sprintf("%s%s.%s", $path, $name, $extension);

if (!is_dir($path)) {
throw new \Exception('Invalid upload directory.');
}

// Size check
if ($imageFile['size'] > 2 * 1024 * 1024) { // 2MB
throw new \Exception('File size is too large, please upload a banner that is no larger than 2MB.');
}

// GD library WebP support check
if (!function_exists('imagewebp')) {
throw new \Exception('WebP conversion is not supported on this server.');
}

// Creating image resource directly from uploaded file
$img = imagecreatefromstring(file_get_contents($imageFile['tmp_name']));
if (!$img) {
throw new \Exception('Unable to create image resource.');
}

// Resize image if width is higher than the specified maximum width
$currentWidth = imagesx($img);
if ($currentWidth > $maxWidth) {
$resizedImg = imagescale($img, $maxWidth);
if ($resizedImg) {
imagedestroy($img);
$img = $resizedImg;
}
}

// Image processing and WebP conversion
imagepalettetotruecolor($img);
imagealphablending($img, true);
imagesavealpha($img, true);
imagewebp($img, "{$path}{$name}.webp", 100);
imagedestroy($img);

// Unlinking the original file
unlink($filePath);

return $name . ".webp";
} catch (\Exception $e) {
session()->setFlashdata(ERROR_MESSAGE, $e->getMessage());
return null;
}
}


For the additional function to generate the random string, check the following snippet PHP random string generator function
  • Input Validation:
    • Checks if the uploaded file has no errors and is in a valid state (UPLOAD_ERR_OK).
    • Throws an exception if the file upload is invalid.
  • File Type Verification:
    • Retrieves the file extension from the uploaded file's name.
    • Compares the extension against a list of valid image extensions (png, jpg, jpeg, gif, webp).
    • Throws an exception if the file type is invalid.
  • Generate Unique Filename:
    • Creates a unique filename by combining a random string and the current timestamp.
    • Prepares the file path using the specified directory and the generated filename.
  • Check Upload Directory:
    • Verifies if the designated upload directory exists.
    • Throws an exception if the directory is invalid.
  • File Size Check:
    • Validates that the size of the uploaded file is within the acceptable limit (2MB).
    • Throws an exception if the file size exceeds the limit.
  • WebP Support Verification:
    • Checks if the GD library supports WebP conversion.
    • Throws an exception if WebP conversion is not supported.
  • Create Image Resource:
    • Reads the content of the uploaded file and creates an image resource using GD's imagecreatefromstring.
    • Throws an exception if an image resource cannot be created.
  • Resize Image (if needed):
    • Checks the width of the image.
    • If the width exceeds the specified maximum width, resizes the image using imagescale.
    • Destroys the original image resource if resizing is performed.
  • Image Processing:
    • Converts the image to true color, enables alpha blending, and saves alpha transparency.
    • Prepares the WebP version of the image using imagewebp.
  • Cleanup:
    • Destroys the image resource.
    • Unlinks the original uploaded file to free up server space.
  • Return WebP Filename:
    • Returns the generated WebP filename if the entire process is successful.
    • If an exception occurs at any step, sets a flash message and returns null.

Last updated

Comments

Leave a Comment