WordPress - 上传时模糊图像

Dre*_*ker 10 php wordpress upload blur imagick

所以我按照这里给出的示例(我修改为仅模糊,没有水印),在上传时在WordPress中制作模糊图像.问题是,如果上传的文件与设置的大小完全相同或更小,那么WordPress将不会生成图像,因此不会产生模糊的图像.

我尝试使用a isst($meta['sizes']['background-image-blurred']['file'])确定是否制作了一个,如果没有,那么copy()源文件,但是不会为图像生成WordPress"元数据"(对于非WordPress人,元数据与您的想法不同),所以显示使用时,它会给出高度/宽度未定义的问题wp_get_attachment_image.

所以我确信使用wp_get_attachment_image如下所示的钩子可能是错误的方法.它可能需要在图像上载过程中更早发生.

关于如何最好地实现这一目标的任何想法?

/**
 * Several functions relatting to blurring images on uploaded.
 * @see https://codeable.io/community/how-to-watermark-wordpress-images-with-imagemagick/
 */ 
    add_image_size( 'background-image-blurred', 1920, 1080, true );

    function generate_blurred_image( $meta ) {

      $time = substr( $meta['file'], 0, 7); // Extract the date in form "2015/04"
      $upload_dir = wp_upload_dir( $time ); // Get the "proper" upload dir

      $filename = $meta['sizes']['background-image-blurred']['file'];
      $meta['sizes']['background-image-blurred']['file'] = blur_image( $filename, $upload_dir );

      return $meta;

    }
    add_filter( 'wp_generate_attachment_metadata', 'generate_blurred_image' );    

    function blur_image( $filename, $upload_dir ) {

      $original_image_path = trailingslashit( $upload_dir['path'] ) . $filename;

      $image_resource = new Imagick( $original_image_path );
      $image_resource->gaussianBlurImage( 10, 100 ); // See: http://phpimagick.com/Imagick/gaussianBlurImage

      return save_blurred_image( $image_resource, $original_image_path );

    }    

    function save_blurred_image( $image_resource, $original_image_path ) {

      $image_data = pathinfo( $original_image_path );

      $new_filename = $image_data['filename'] . '-blurred.' . $image_data['extension'];

      // Build path to new blurred image
      $blurred_image_path = str_replace($image_data['basename'], $new_filename, $original_image_path);

      if ( ! $image_resource->writeImage( $blurred_image_path ) ) {
        return $image_data['basename'];          
      }

      // Delete the placeholder image WordPress made now that it's been blurred
      unlink( $original_image_path );

      return $new_filename;

    }    
Run Code Online (Sandbox Code Playgroud)

Dav*_*vid 4

不幸的是,wp 没有过滤器来强制调整大小,因此您可以做的是挂钩并调整图像大小(如果未创建)并将其弹出到元数据中。

我没有 imagick,所以你必须自己尝试这些功能,但你有上面的正确过程,你只需要更新文件名并在下面的数组中键入。PS 不要在过滤器内输出任何内容!

function custom_img_size(){
    add_image_size( 'background-image-blurred', 1920, 1080, true );
}

add_action( 'after_setup_theme', 'custom_img_size' );


add_filter('wp_generate_attachment_metadata', 'force_add_size', 100);
function force_add_size( $metadata ) {

   if(!isset($metadata['sizes']['background-image-blurred'])){
        //not set so initiate our custom size...
        //I dont have imagick installed so just use your functions here to duplicate
        //note original file = $filename update the $newfilename below...
        //sample resize code ...
        $upload_dir = wp_upload_dir();
        $filename= $upload_dir['basedir'].'/'.$metadata['file'];
        $extension = strtolower(strrchr($metadata['file'], '.'));
        $newfilename= str_replace($extension, '-1200x1080', $filename).$extension;

        copy($filename, $newfilename );
        //end sample resize code.....



        $filetype= 'image/jpeg';
        $metadata['sizes']['background-image-blurred']= array(
            "file"=> $newfilename,
            "width"=> 1920, 
            "height"=> 1080,
            "mime-type"=> $filetype 
        );

   }


   return $metadata;

}
Run Code Online (Sandbox Code Playgroud)

更新

  1. 其设计目的是仅捕获现有过滤器未能创建模糊的自定义尺寸的位置,否则它不会执行任何操作。您仍应包含原始过滤器。您的原始代码可能存在问题:您正在删除过滤器中的原始文件,这将导致问题,因为有一个名为“_wp_attached_file”的 postmeta 字段需要更新。我在下面对此做了注释。

  2. 过滤器在保存之前捕获元数据,因此一旦您返回 $metadata,任何更改也将被保存。如果您查看源代码: https://core.trac.wordpress.org/browser/tags/3.8.1/src/wp-admin/includes/image.php#L72,您可以准确地看到它是如何工作的。我也确认使用 wp4.3

  3. 我尝试在下面插入您需要的 imagick 函数。我还没有测试过,因为我实际上没有在任何地方安装它。(imagemagick 实际上是一个很棒的开源程序,但服务器非常密集)。尝试用这个函数代替上面的函数:

    add_filter('wp_generate_attachment_metadata', 'force_add_size', 100, 2);
    
    function force_add_size( $metadata, $id ){
    
        $upload_dir = wp_upload_dir();
        $filename= $upload_dir['basedir'].'/'.$metadata['file'];
        $extension = strtolower(strrchr($metadata['file'], '.'));
        $newfilename= str_replace($extension, '-blurred', $filename).$extension;
    
        $image_resource = new Imagick( $filename);
        $image_resource->resizeImage(1920,1080,Imagick::FILTER_LANCZOS,.3);
        $image_resource->writeImage( $newfilename );
        //http://www.dylanbeattie.net/magick/filters/result.html
    
        unlink( $filename );//delete original image altogether ---> you might want to update the post meta on this '_wp_attached_file' , you can actually get the attachment id from the filter, i have added it above. It would be best to have a actual image url in there! something like $sfile= str_replace($upload_dir['basedir'],'', $newfilename); update_post_meta($id, '_wp_attached_file', $sfile );
    
    
    
        switch($extension){
            case '.jpg':
            case '.jpeg':
                $type = 'image/jpeg';
                break;
            case '.gif':
                $type = 'image/gif';
                break;
            case '.png':
                $type = 'image/png';
                break;
            default:
                $type = 'image/jpeg'; // you might want a conditional to check its actually a image...imagick will do this for you as well....it shouldnt get this far if not a image.
                break;
        } 
    
        $metadata['sizes']['background-image-blurred']= array(
            "file"=> $newfilename,
            "width"=> 1920,//your custom image size, has to be this! you could get the global var and check for sizes but its this size in particular we want? 
            "height"=> 1080,
            "mime-type"=> $type 
        );
    
        return $metadata;
    }
    
    Run Code Online (Sandbox Code Playgroud)

更新 以防止图像拉伸较小的图像,用此替换 imagick 代码。

$upload_dir = wp_upload_dir();
$filename= $upload_dir['basedir'].'/'.$metadata['file'];
$extension = strtolower(strrchr($metadata['file'], '.'));
$newfilename= str_replace($extension, '-blurred', $filename).$extension;

$image_resource = new Imagick( $filename);


if($image_resource->getImageWidth() <= 1920 || $image_resource->getImageHeight() > <= 1020) {
    return $metadata;
}

$image_resource->resizeImage(1920,1080,Imagick::FILTER_LANCZOS,.3);
$image_resource->writeImage( $newfilename );
//http://www.dylanbeattie.net/magick/filters/result.html
Run Code Online (Sandbox Code Playgroud)