PHP: Changing the image quality when condition is met?

后端 未结 2 962
感动是毒
感动是毒 2021-01-03 13:09

I have a php script where the user can upload images. I want to make the script lower the image quality (jpeg) if the file size is bigger than \'X\' kbytes.

Somethin

2条回答
  •  半阙折子戏
    2021-01-03 13:54

    Sure you can. Do something like this.

    $upload = $_FILES['uploaded_img'];
    $uploadPath = 'new/path/for/upload/';
    $uploadName = pathinfo($upload['name'], PATHINFO_FILENAME);
    $restrainedQuality = 75; //0 = lowest, 100 = highest. ~75 = default
    $sizeLimit = 2000;
    
    if($upload['size'] > $sizeLimit) {
        //open a stream for the uploaded image
        $streamHandle = @fopen($upload['tmp_name'], 'r');
        //create a image resource from the contents of the uploaded image
        $resource = imagecreatefromstring(stream_get_contents($streamHandle));
    
        if(!$resource)
            die('Something wrong with the upload!');
    
        //close our file stream
        @fclose($streamHandle);
    
        //move the uploaded file with a lesser quality
        imagejpeg($resource, $uploadPath . $uploadName . '.jpg', $restrainedQuality); 
        //delete the temporary upload
        @unlink($upload['tmp_name']);
    } else {
        //the file size is less than the limit, just move the temp file into its appropriate directory
        move_uploaded_file($upload['tmp_name'], $uploadPath . $upload['name']);
    }
    

    This will accept any image format supported by PHP GD (Assuming that it's installed on your server. Most likely is). If the image is less than the limit, it will just upload the original image to the path you specify.

提交回复
热议问题