PHP image compression after upload

PHP has several ways to compress uploaded images.

One way is to use the GD library, one of the most commonly used graphics libraries in PHP. Uploaded images can be compressed and resized using functions of the GD library. The following is an example of image compression using the GD library:

// 获取上传的图片
$uploadedImage = $_FILES['image']['tmp_name'];

// 创建一个新的图片资源
$image = imagecreatefromjpeg($uploadedImage);

// 压缩图片为指定的宽度和高度
$width = 800;
$height = 600;
$newImage = imagecreatetruecolor($width, $height);
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, imagesx($image), imagesy($image));

// 保存压缩后的图片
$compressedImagePath = 'path/to/save/compressed_image.jpg';
imagejpeg($newImage, $compressedImagePath);

// 释放资源
imagedestroy($newImage);
imagedestroy($image);

echo "图片已压缩并保存为 {
      
      $compressedImagePath}";

Another way is to use a third-party library such as Intervention Image. It provides more functions and options to process and manipulate pictures. You can install it using the Composer package manager:

First, create a file in the project root directory composer.jsonwith the following content:

{
    
    
    "require": {
    
    
        "intervention/image": "^2.5"
    }
}

Then run composer installthe command to install the library.

The following is an example of image compression using Intervention Image:

require 'vendor/autoload.php';

use Intervention\Image\ImageManagerStatic as Image;

// 获取上传的图片
$uploadedImage = $_FILES['image']['tmp_name'];

// 压缩图片为指定的宽度和高度
$width = 800;
$height = 600;
$compressedImage = Image::make($uploadedImage)->resize($width, $height);

// 保存压缩后的图片
$compressedImagePath = 'path/to/save/compressed_image.jpg';
$compressedImage->save($compressedImagePath);

echo "图片已压缩并保存为 {
      
      $compressedImagePath}";

The above are two common ways to compress images in PHP, and you can choose one of them according to your needs.

Guess you like

Origin blog.csdn.net/qq_27487739/article/details/131580809