You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中使用已安装的libjpeg-turbo构建图片压缩上传测试Demo

Using libjpeg-turbo in PHP for Image Upload & Compression Demo

Hey there! Since you've already got libjpeg-turbo installed on your server, let's build that image upload and compression demo you need. I'll walk you through every part, from the upload form to the compression logic, so it's easy to follow.

First: Verify PHP GD Extension is Linked with libjpeg-turbo

libjpeg-turbo works behind the scenes with PHP's GD extension to speed up JPEG processing. Make sure your GD extension is enabled and compiled against libjpeg-turbo:

  • Create a phpinfo.php file with <?php phpinfo(); ?>
  • Access it in your browser, search for the GD section, and check if it mentions libjpeg-turbo under the JPEG support line.
  • Alternatively, run php -i | grep "GD" in your server's terminal to verify.

Complete Demo Code

This demo includes an upload form, validation, compression, and result display. Save it as image-compress-demo.php:

<?php
$uploadDir = './uploads/';
// Create upload directory if it doesn't exist
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$originalSize = '';
$compressedSize = '';
$compressedImagePath = '';
$originalImagePath = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['image'])) {
    $file = $_FILES['image'];
    
    // Check for upload errors
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $error = 'Upload failed: ' . $file['error'];
    } else {
        // Validate file is JPEG
        $mime = mime_content_type($file['tmp_name']);
        if ($mime !== 'image/jpeg' && $mime !== 'image/jpg') {
            $error = 'Only JPEG/JPG files are allowed.';
        } else {
            // Get original image size
            $originalSize = number_format(filesize($file['tmp_name']) / 1024, 2) . ' KB';
            $originalImagePath = $uploadDir . 'original_' . basename($file['name']);
            // Move original file to upload directory
            move_uploaded_file($file['tmp_name'], $originalImagePath);
            
            // Compress image using GD (powered by libjpeg-turbo)
            $sourceImage = imagecreatefromjpeg($originalImagePath);
            if (!$sourceImage) {
                $error = 'Failed to process original image.';
            } else {
                $compressedImagePath = $uploadDir . 'compressed_' . basename($file['name']);
                // Compress with quality 70 (adjust between 0-100; higher = better quality, larger file)
                // libjpeg-turbo optimizes this compression process automatically
                imagejpeg($sourceImage, $compressedImagePath, 70);
                imagedestroy($sourceImage);
                
                // Get compressed image size
                $compressedSize = number_format(filesize($compressedImagePath) / 1024, 2) . ' KB';
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Image Upload & Compression Demo</title>
    <style>
        .result { margin-top: 20px; }
        .image-container { margin: 10px 0; }
        img { max-width: 500px; border: 1px solid #ddd; padding: 5px; }
        .error { color: red; font-weight: bold; }
    </style>
</head>
<body>
    <h2>Upload a JPEG Image to Compress</h2>
    <?php if (isset($error)): ?>
        <p class="error"><?php echo $error; ?></p>
    <?php endif; ?>
    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="image" accept=".jpg,.jpeg" required>
        <button type="submit">Upload & Compress</button>
    </form>

    <?php if ($originalSize && $compressedSize): ?>
        <div class="result">
            <h3>Compression Results</h3>
            <div class="image-container">
                <h4>Original Image (Size: <?php echo $originalSize; ?>)</h4>
                <img src="<?php echo $originalImagePath; ?>" alt="Original Image">
            </div>
            <div class="image-container">
                <h4>Compressed Image (Size: <?php echo $compressedSize; ?>)</h4>
                <img src="<?php echo $compressedImagePath; ?>" alt="Compressed Image">
            </div>
        </div>
    <?php endif; ?>
</body>
</html>

Key Details Explained

  • Upload Directory: The script creates an uploads folder to store original and compressed images (make sure it's writable by the web server).
  • File Validation: We check for upload errors and verify the file is a JPEG using mime_content_type (more reliable than just checking file extensions).
  • Compression Logic:
    • imagecreatefromjpeg() loads the original image, with libjpeg-turbo handling the decoding efficiently in the background.
    • imagejpeg() saves the compressed image—adjust the third parameter (quality, 0-100) to balance file size and image quality. libjpeg-turbo makes this compression faster and more efficient than standard libjpeg.
  • Size Calculation: filesize() gets the file size, which we convert to KB for better readability.

Testing the Demo

  1. Upload the script to your server.
  2. Ensure the uploads folder has proper permissions (use chmod 755 or chmod 775 depending on your server setup).
  3. Access the script in your browser, upload a JPEG image, and you'll see the original and compressed images displayed alongside their respective file sizes.

内容的提问来源于stack exchange,提问作者Marco Ingraiti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:07:59