使用 PHP 压缩和上传图片

在'upload.php'文件中处理图像压缩和上传操作。

  • compressImage() 是一个自定义函数,有助于使用 PHP 在服务器上压缩和保存图像。
  • 如果提交文件,
  • 使用 PHP $_FILES 方法检索文件信息。
  • 使用 'compressImage()' 函数压缩大小并上传图像。
  • 渲染图片上传状态。
<?php 

/* 
 * 使用PHP压缩图像大小并上传到服务器的自定义函数
 */
function compressImage($source, $destination, $quality) { 
    //Get image info 
    $imgInfo = getimagesize($source); 
    $mime = $imgInfo['mime']; 

    //Create a new image from file 
    switch($mime){ 
        case 'image/jpeg': 
            $image = imagecreatefromjpeg($source); 
            break; 
        case 'image/png': 
            $image = imagecreatefrompng($source); 
            break; 
        case 'image/gif': 
            $image = imagecreatefromgif($source); 
            break; 
        default: 
            $image = imagecreatefromjpeg($source); 
    } 

    //Save image 
    imagejpeg($image, $destination, $quality); 

    //Return compressed image 
    return $destination; 
} 

//File upload path 
$uploadPath = "uploads/"; 

//If file upload form is submitted 
$status = $statusMsg = ''; 
if(isset($_POST["submit"])){ 
    $status = 'error'; 
    if(!empty($_FILES["image"]["name"])) { 
        //File info 
        $fileName = basename($_FILES["image"]["name"]); 
        $imageUploadPath = $uploadPath . $fileName; 
        $fileType = pathinfo($imageUploadPath, PATHINFO_EXTENSION); 

        //Allow certain file formats 
        $allowTypes = array('jpg','png','jpeg','gif'); 
        if(in_array($fileType, $allowTypes)){ 
            //Image temp source 
            $imageTemp = $_FILES["image"]["tmp_name"]; 

            //Compress size and upload image 
            $compressedImage = compressImage($imageTemp, $imageUploadPath, 75); 

            if($compressedImage){ 
                $status = 'success'; 
                $statusMsg = "Image compressed successfully."; 
            }else{ 
                $statusMsg = "Image compress failed!"; 
            } 
        }else{ 
            $statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.'; 
        } 
    }else{ 
        $statusMsg = 'Please select an image file to upload.'; 
    } 
} 

//Display status message 
echo $statusMsg; 

?>
使用 PHP上传图片前,如何压缩图片

大尺寸图像需要更多时间来加载网页。
如果要加载大图而不影响页面加载时间,则需要对图像进行优化以减小尺寸。
图像压缩对于减小图像大小非常有帮助。
一般用户在通过上传时不会对图片进行优化。
在这种情况下,上传前压缩图像以优化图像。

上传前压缩/优化图像可以使用 PHP 轻松实现。
在图像压缩功能中,文件大小在上传前减小。
压缩图像有助于减少服务器存储的使用并更快地加载网页。
在本教程中,我们将向我们展示如何在使用 PHP 上传之前压缩图像。

文件上传表单

创建一个带有文件输入字段和提交按钮的 HTML 表单。
确保 <form> 标签包含以下属性。

  • 'method="post"'
  • 'enctype="multipart/form-data"'
<form action="upload.php" method="post" enctype="multipart/form-data">
    <label>Select Image File:</label>
    <input type="file" name="image">
    <input type="submit" name="submit" value="Upload">
</form>

表单提交后,文件数据被提交到'upload.php'文件进行进一步处理。

日期:2020-06-02 22:15:26 来源:oir作者:oir