wp_get_webp_info()
云策文档标注
概述
wp_get_webp_info() 函数用于提取 WebP 文件的元信息,包括宽度、高度和类型。它验证文件是否为 WebP 格式,并返回一个包含这些信息的数组。
关键要点
- 参数 $filename 是必需的,表示 WebP 文件的路径。
- 返回一个数组,包含 width(成功时为整数,失败时为 false)、height(成功时为整数,失败时为 false)和 type(成功时为字符串 'lossy'、'lossless' 或 'animated-alpha',失败时为 false)。
- 函数首先使用 wp_get_image_mime() 检查文件是否为 WebP 格式,如果不是则返回默认值。
- 通过读取文件头部字节来解析 WebP 信息,确保有足够的数据。
- 相关函数包括 wp_get_image_mime()、WP_Image_Editor_GD::set_quality()、wp_getimagesize() 和 WP_Image_Editor_Imagick::set_quality()。
- 该函数在 WordPress 5.8.0 版本中引入。
代码示例
function wp_get_webp_info( $filename ) {
$width = false;
$height = false;
$type = false;
if ( 'image/webp' !== wp_get_image_mime( $filename ) ) {
return compact( 'width', 'height', 'type' );
}
$magic = file_get_contents( $filename, false, null, 0, 40 );
if ( false === $magic ) {
return compact( 'width', 'height', 'type' );
}
// Make sure we got enough bytes.
if ( strlen( $magic ) > 6 ) {
// 解析逻辑(示例中未完整显示)
}
}
原文内容
Extracts meta information about a WebP file: width, height, and type.
Parameters
$filenamestringrequired-
Path to a WebP file.
Source
function wp_get_webp_info( $filename ) {
$width = false;
$height = false;
$type = false;
if ( 'image/webp' !== wp_get_image_mime( $filename ) ) {
return compact( 'width', 'height', 'type' );
}
$magic = file_get_contents( $filename, false, null, 0, 40 );
if ( false === $magic ) {
return compact( 'width', 'height', 'type' );
}
// Make sure we got enough bytes.
if ( strlen( $magic ) < 40 ) {
return compact( 'width', 'height', 'type' );
}
/*
* The headers are a little different for each of the three formats.
* Header values based on WebP docs, see https://developers.google.com/speed/webp/docs/riff_container.
*/
switch ( substr( $magic, 12, 4 ) ) {
// Lossy WebP.
case 'VP8 ':
$parts = unpack( 'v2', substr( $magic, 26, 4 ) );
$width = (int) ( $parts[1] & 0x3FFF );
$height = (int) ( $parts[2] & 0x3FFF );
$type = 'lossy';
break;
// Lossless WebP.
case 'VP8L':
$parts = unpack( 'C4', substr( $magic, 21, 4 ) );
$width = (int) ( $parts[1] | ( ( $parts[2] & 0x3F ) << 8 ) ) + 1;
$height = (int) ( ( ( $parts[2] & 0xC0 ) >> 6 ) | ( $parts[3] << 2 ) | ( ( $parts[4] & 0x03 ) << 10 ) ) + 1;
$type = 'lossless';
break;
// Animated/alpha WebP.
case 'VP8X':
// Pad 24-bit int.
$width = unpack( 'V', substr( $magic, 24, 3 ) . "x00" );
$width = (int) ( $width[1] & 0xFFFFFF ) + 1;
// Pad 24-bit int.
$height = unpack( 'V', substr( $magic, 27, 3 ) . "x00" );
$height = (int) ( $height[1] & 0xFFFFFF ) + 1;
$type = 'animated-alpha';
break;
}
return compact( 'width', 'height', 'type' );
}
Changelog
| Version | Description |
|---|---|
| 5.8.0 | Introduced. |