使用 Imagick 将图像压缩和隐蔽上传到 WebP 格式的 WordPress 主题功能

问题描述 投票:0回答:0

我在wordpress主题函数中使用Imagick编写了这个用于压缩和转换上传图片到webp格式的函数代码:

/*
 * Compress and convert to WebP for uploading images
 */
function compress_and_convert_images_to_webp($file) {
    // Check if file type is supported
    $supported_types = ['image/jpeg', 'image/jpg', 'image/png'];
    if (!in_array($file['type'], $supported_types)) {
        return $file;
    }

    // Get the path to the upload directory
    $wp_upload_dir = wp_upload_dir();

    // Set up the file paths
    $old_file_path = $file['file'];
    $file_name = basename($file['file']);
    $webp_file_path = $wp_upload_dir['path'] . '/' . pathinfo($file_name, PATHINFO_FILENAME) . '.webp';
    
    // Check if file is already a WebP image
    if (pathinfo($old_file_path, PATHINFO_EXTENSION) === 'webp') {
        return $file;
    }

    // Load the image using Imagick
    $image = new Imagick($old_file_path);

    // Compress the image
    $quality = 75; // Adjust this value to control the compression level
    $image->setImageCompressionQuality($quality);
    $image->stripImage(); // Remove all profiles and comments to reduce file size

    // Convert the image to WebP
    $image->setImageFormat('webp');
    $image->setOption('webp:lossless', 'false');
    $image->setOption('webp:method', '6'); // Adjust this value to control the compression level for WebP
    $image->writeImage($webp_file_path);
    
    // Allow WebP mime type
    add_filter('upload_mimes', function($mimes) {
        $mimes['webp'] = 'image/webp';
        return $mimes;
    });
    
    // Set file permissions to 0644
    chmod($webp_file_path, 0644);

    // Add the new WebP image to the media library
    $attachment_id = media_handle_upload(pathinfo($file_name, PATHINFO_FILENAME), 0, [
        'post_mime_type' => 'image/webp',
        'file' => $webp_file_path
    ]);
    
    if (is_wp_error($attachment_id)) {
        error_log("The Attachment ID Error is: " . $attachment_id->get_error_message());
    }

    // Delete the old image file
    unlink($old_file_path);

    // Update the attachment metadata with the WebP image URL
    update_post_meta($attachment_id, '_wp_attached_file', substr($webp_file_path, strlen($wp_upload_dir['basedir']) + 1));
    
    // Return the updated file information
    return [
        'file' => $webp_file_path,
        'url' => wp_get_attachment_url($attachment_id),
        'type' => 'image/webp',
    ];
}
add_filter('wp_handle_upload', 'compress_and_convert_images_to_webp');

这段代码工作正常,可以压缩和转换上传的图像文件,但每次上传新文件时都会发出警告。

我搜索过警告,它们是关于“$attachment_id”变量的问题:

如您所见,此变量使用“media_handle_upload”函数获取新的附件 ID,但它返回此错误“指定的文件上传测试失败。”。

我该怎么办?

php wordpress imagick image-conversion image-comparison
© www.soinside.com 2019 - 2024. All rights reserved.