使用Jetpack Photon从顶部中心裁剪图像

时间:2013-07-15 作者:Harish Chouhan

我正在建立一个网站画廊,上传的截图宽1400px,高度不一。

在我的帖子索引页面上,我需要显示一个只有900像素×600像素的缩略图。但是,这是从中心/中心裁剪的。有没有办法从顶部居中裁剪图像?

有一张类似的票How can I make add_image_size() crop from the top? 但我无法理解。

此外,我还激活了Jetpack插件的光子模块,该模块提供来自WordPress云的图像。它接受URL和大小并将其转换为

http://i0.wp.com/flattrendz.com/wp-content/uploads/symbolset.jpg?resize=900,600 原始图像是http://flattrendz.com/wp-content/uploads/symbolset.jpg.

有人知道如何使光子模块从顶部中心裁剪图像吗?

1 个回复
最合适的回答,由SO网友:jeherve 整理而成

我们讨论了这个问题in the WordPress.org support forums. 下面是一段代码,可以实现此目的:

/* 
 * Let\'s add support for Photon - that won\'t be necessary once Jetpack 2.3.2 is out. 
 * You\'ll be able to use apply_filters( \'jetpack_photon_url\'... directly
 * See http://jetpack.me/2013/07/11/photon-and-themes/
 */
if( function_exists( \'jetpack_photon_url\' ) ) {
    add_filter( \'jetpack_photon_url\', \'jetpack_photon_url\', 10, 3 );
}

/* 
 * Let\'s add resized post thumbnails
 * We use a different size on single pages
 */
function jeherve_display_custom( $content, $post ) {
    global $post;

    // If you didn\'t define a post thumnail, let\'s forget about all this
    if ( !has_post_thumbnail( $post->ID ) )
        return $content;

    // What\'s the cropping and the size of image we should use on Single pages? Here we crop to top center and create a 500 x 500px image
    // See http://developer.wordpress.com/docs/photon/api/#crop for parameters
    if ( is_single() ) {
        $args = array(
            \'crop\'   => \'30,0,40,50\',
            \'resize\'   => \'500,500\',
        );
    }
    // resizing on other pages - some random resizing here
    else {
        $args = array(
            \'resize\'   => \'200,400\',
        );
    }

    // Let\'s create a Photon Image URL from the Post Thumbnail
    $feat_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), \'full\');
    $photon_image_url = jetpack_photon_url( $feat_image_url[0], $args );

    // Let\'s build the image tag, as it was built before in your example
    $our_image = sprintf( \'<div class="post-media"><a class="featured-image" href="%1$s" title="%2$s"><img src="%3$s" class="wp-post-image" alt="Featured Image"></a></div>\',
        esc_url( get_permalink() ),
        esc_attr( sprintf( __( \'Open %s\', \'dot\' ), get_the_title() ) ),
        esc_attr( $photon_image_url )
    );

    // Let\'s return the image, right before the post content
    return $our_image . $content;

}
add_filter( \'the_content\', \'jeherve_display_custom\' );
下面是一个示例,上面提到了单页裁剪:

有关参考,您可以查看可用的光子API文档here.

结束