WordPress主题功能,用于压缩和将上传的图像转换为WebP格式,使用Imagick。

huangapple go评论57阅读模式
英文:

WordPress Theme Function For Compress and Covert Uploading Images to WebP Format Using Imagick

问题

I've translated the relevant code for you:

我已经为压缩和转换上传的图像为WebP格式编写了这个函数代码,使用Imagick并将它们添加到媒体库中,然后删除原始上传文件格式。

我在WordPress主题功能(functions.php)中编写了这个函数:

/*
 * 压缩并转换为WebP以上传图像
 */
function compress_and_convert_images_to_webp($file) {
    // 检查文件类型是否受支持
    $supported_types = ['image/jpeg', 'image/jpg', 'image/png'];
    if (!in_array($file['type'], $supported_types)) {
        return $file;
    }

    // 获取上传目录的路径
    $wp_upload_dir = wp_upload_dir();

    // 设置文件路径
    $old_file_path = $file['file'];
    $file_name = basename($file['file']);
    $webp_file_path = $wp_upload_dir['path'] . '/' . pathinfo($file_name, PATHINFO_FILENAME) . '.webp';

    // 检查文件是否已经是WebP图像
    if (pathinfo($old_file_path, PATHINFO_EXTENSION) === 'webp') {
        return $file;
    }

    // 使用Imagick加载图像
    $image = new Imagick($old_file_path);

    // 压缩图像
    $quality = 75; // 调整此值以控制压缩级别
    $image->setImageCompressionQuality($quality);
    $image->stripImage(); // 删除所有配置文件和注释以减小文件大小

    // 将图像转换为WebP
    $image->setImageFormat('webp');
    $image->setOption('webp:lossless', 'false');
    $image->setOption('webp:method', '6'); // 调整此值以控制WebP的压缩级别
    $image->writeImage($webp_file_path);

    // 允许WebP的MIME类型
    add_filter('upload_mimes', function($mimes) {
        $mimes['webp'] = 'image/webp';
        return $mimes;
    });

    // 设置文件权限为0644
    chmod($webp_file_path, 0644);

    // 将新的WebP图像添加到媒体库
    $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("附件ID错误是:" . $attachment_id->get_error_message());
    }

    // 删除旧的图像文件
    unlink($old_file_path);

    // 使用WebP图像URL更新附件元数据
    update_post_meta($attachment_id, '_wp_attached_file', substr($webp_file_path, strlen($wp_upload_dir['basedir']) + 1));

    // 返回更新后的文件信息
    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对象):“指定的文件未通过上传测试”。对于这些警告,您可能需要检查文件上传的设置和文件类型是否正确,以确保一切正常工作。

英文:

I have written this function code for compressing and converting uploading images to WebP format using Imagick and adding them to media library and delete the original uploading file format.

I've written this function at WordPress Theme Functions (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');

This code works fine and compress and convert uploading image files and show them in media library and deletes uploading original format but it raise warnings every time I upload new file.

I've searched about warnings and they are about "$attachment_id" variable problem:

as you can see this variable uses "media_handle_upload" function for getting new attachment ID but it returns this error (WP_ERROR object):

"Specified file failed upload test.".

the warning messages are:

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

What should I do?

答案1

得分: 1

以下是翻译好的部分:

"Finally I've found out the problem:
as I said before, this function works fine but has some warnings.
To resolve the warnings I omitted the parts that related to media_handle_upload and update_post_meta.
The final code is:

/**

  • 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');"

英文:

Finally I've found out the problem:

as I said before, this function works fine but has some warnings.
To resolve the warnings I omitted the parts that related to media_handle_upload and update_post_meta.

The final code is:

/**
* 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');

huangapple
  • 本文由 发表于 2023年5月7日 20:53:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76194055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定