以下代码取自"Dynamic image resize"-plugin.
该插件考虑了一个ID和一个字符串。我没有删除这些行,因为它们可能对以后的访问者有用-无论如何,请检查链接。
按ID或URl检索图像
$hw_string = image_hwstring( $width, $height );
$needs_resize = true;
$error = false;
// ID as src
if ( ! is_string( $src ) )
{
$att_id = $src;
// returns false on failure
$src = wp_get_attachment_url( $src );
// If nothing was found:
! $src AND $error = true;
}
// Path as src
else
{
$upload_dir = wp_upload_dir();
$base_url = $upload_dir[\'baseurl\'];
// Let\'s see if the image belongs to our uploads directory...
$img_url = substr(
$src
,0
,strlen( $base_url )
);
// ...And if not: just return the image HTML string
if ( $img_url !== $base_url )
{
return $this->get_markup(
$img_url
,$hw_string
,$classes
);
}
// Look up the file in the database.
$file = str_replace(
trailingslashit( $base_url )
,\'\'
,$src
);
$att_id = $this->get_attachment( $file );
// If no attachment record was found:
! $att_id AND $error = true;
}
检查错误,如果未找到附件,则中止。这意味着上传没有按预期结束。
// Abort if the attachment wasn\'t found
if ( $error )
{
# @TODO Error handling with proper message
# @TODO Needs a test case
# remove $file in favor of $error_msg
/*
$data = get_plugin_data( __FILE__ );
$error_msg = "Plugin: {$data[\'Name\']}: Version {$data[\'Version\']}";
*/
# @TODO In case, we got an ID, but found no image: if ( ! $src ) $file = $att_id;
return new WP_Error(
\'no_attachment\'
,__( \'Attachment not found.\', \'dyn_textdomain\' )
,$file
);
}
检查现有图像大小,以防已经有我们需要的大小的图像。如果用户多次尝试上载同一图像,可能会出现这种情况(您必须进行检查以避免重复)。
// Look through the attachment meta data for an image that fits our size.
$meta = wp_get_attachment_metadata( $att_id );
foreach( $meta[\'sizes\'] as $key => $size )
{
if (
$width === $size[\'width\']
AND $height === $size[\'height\']
)
{
$src = str_replace(
basename( $src )
,$size[\'file\']
,$src
);
$needs_resize = false;
break;
}
}
处理调整大小现在我们确定有附件,需要调整大小。我们还将更新
post
和
attachment
post类型元数据。
// If an image of such size was not found, ...
if ( $needs_resize )
{
$attached_file = get_attached_file( $att_id );
// ...we can create one.
$resized = image_make_intermediate_size(
$attached_file
,$width
,$height
,true
);
if ( ! is_wp_error( $resized ) )
{
// Let metadata know about our new size.
$key = sprintf(
\'resized-%dx%d\'
,$width
,$height
);
$meta[\'sizes\'][ $key ] = $resized;
$src = str_replace(
basename( $src )
,$resized[\'file\']
,$src
);
wp_update_attachment_metadata( $att_id, $meta );
// Record in backup sizes, so everything\'s
// cleaned up when attachment is deleted.
$backup_sizes = get_post_meta(
$att_id
,\'_wp_attachment_backup_sizes\'
,true
);
! is_array( $backup_sizes ) AND $backup_sizes = array();
$backup_sizes[ $key ] = $resized;
update_post_meta(
$att_id
,\'_wp_attachment_backup_sizes\'
,$backup_sizes
);
}
现在一切都应该好了,准备好继续。
如果您不需要所有内容,只需删除您不需要的内容,但确保不遗漏所需的错误检查。安全总比后悔好。