使用WP_Image_Editor_GD :: multi_resize方法调整大小后如何保存图像?

时间:2019-07-17 11:56:40

标签: wordpress

我正在使用WordPress中的特定登录页面,并希望优化图像交付。我在文档中找到了该类,并认为它可以完成工作:https://codex.wordpress.org/Class_Reference/WP_Image_Editor

但是WordPress文档缺少使用multi_resize方法的示例,因此我不知道如何使用所需的目标文件夹和文件名保存调整大小的图像。

我的测试图像路径是wp-content / themes / mytheme-child / inc / assets / test.png

我想将调整大小后的图像放入名为“ resize”的子目录,并将其命名为:

wp-content/themes/mytheme-child/inc/assets/resize/test_300x.png 
wp-content/themes/mytheme-child/inc/assets/resize/test_400x.png 
wp-content/themes/mytheme-child/inc/assets/resize/test_500x.png

我所做的:

<?php
  $assets = get_stylesheet_directory() . '/assets/';
  $cur_img = 'test.png';
  $path_parts = pathinfo($cur_img);

  if ( !file_exists ( $assets . 'resize/' . $path_parts['filename'] . '_300x' . $path_parts['extension'] ) ):
    $image_to_resize = wp_get_image_editor( $assets . $cur_img );
    if ( ! is_wp_error( $image_to_resize ) ) {
      $sizes_array = array(
        array ('width' => 300, 'height' => NULL, 'crop' => false),
        array ('width' => 350, 'height' => NULL, 'crop' => false),
        array ('width' => 400, 'height' => NULL, 'crop' => false),
        array ('width' => 500, 'height' => NULL, 'crop' => false),
        array ('width' => 600, 'height' => NULL, 'crop' => false),
        array ('width' => 700, 'height' => NULL, 'crop' => false),
        array ('width' => 800, 'height' => NULL, 'crop' => false),
        array ('width' => 900, 'height' => NULL, 'crop' => false),
        array ('width' => 1000, 'height' => NULL, 'crop' => false)
      );

      $image_to_resize->multi_resize( $sizes_array );
    }
  endif;
?>

我希望我应该使用类似$ image_to_resize-> save()的方法,但不知道如何为调整大小的图像设置目标目录和文件名。

以下是一些有关我想做什么的详细信息:

  1. 我不打算从管理员那里使用WP Media Library。媒体文件将存储在子主题文件夹中(因此,通过FTP上传文件比通过WP admin更为方便)
  2. 不同的图像将需要不同范围的调整大小分辨率。一个应为300、350,...宽1000像素,其他应为30、40,... 150像素宽等。
  3. 仅应创建一次图像,然后将其存储在磁盘上,以使服务器CPU大部分时间都不会裁剪图像。

0 个答案:

没有答案