WordPress主题函数用于使用Imagick压缩和隐藏上传图像到WebP格式

5jvtdoz2  于 2023-05-16  发布在  WordPress
关注(0)|答案(1)|浏览(211)

我已经写了这个函数的代码压缩和转换上传图像到WebP格式使用Imagick和添加到媒体库和删除原来的上传文件格式。
我在WordPress主题函数(functions.php)中写了这个函数:

/*
 * 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,但它返回了这个错误(WP_ERROR对象):
“指定的文件未通过上载测试。"。
警告信息包括:

PHP Warning:  Trying to access array offset on value of type null in wp-admin/includes/file.php on line 906

PHP Deprecated:  is_uploaded_file(): Passing null to parameter #1 ($filename) of type string is deprecated in wp-admin/includes/file.php on line 906

PHP Warning:  Object of class WP_Error could not be converted to int in wp-includes/post.php on line 6590

我该怎么办?

41zrol4v

41zrol4v1#

最后我发现了问题:
正如我之前所说,这个函数工作正常,但有一些警告。为了解决警告,我省略了与media_handle_upload和update_post_ meta相关的部分。
最后的代码是:

/**
 * 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', 'image/webp'];
    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);

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

    // Return the updated file information
    return [
        'file' => $webp_file_path,
        'url' => $wp_upload_dir['url'] . '/' . basename($webp_file_path),
        'type' => 'image/webp',
    ];
}
add_filter('wp_handle_upload', 'compress_and_convert_images_to_webp');

相关问题