首页 > 解决方案 > 调整大小并保存图像

问题描述

我试图在 WordPress 中调整大小并保存图像,但wp_get_image_editor没有成功。图像没有被保存,我没有得到任何错误。我究竟做错了什么?你会如何处理它?

代码

$original = 'http://dgli.local.com/wp-content/uploads/2020/03/IMG_7686.jpg';
if(!file_exists($original)) {
  return;
}

$editor = wp_get_image_editor($original, array());

$result = $editor->resize(300, 300, true);

if(!is_wp_error($result)) {
  $editor->save($editor->generate_filename());
  echo 'success';
} else {
  echo 'error';
}

标签: phpwordpress

解决方案


我将此作为评论,但认为值得回答:

文件路径不应该是 URL,它应该是文件的服务器路径。

// Get the upload directory.
$upload_dir = wp_get_upload_dir();
// Get the base directory.
$path = $upload_dir['basedir'];
// Append the directory to your file name.
$original = $path . '/2020/03/IMG_7686.jpg';

$editor = wp_get_image_editor($original, array());

$result = $editor->resize(300, 300, true);

if(!is_wp_error($result)) {
  $editor->save($editor->generate_filename());
  echo 'success';
} else {
  echo 'error';
}

推荐阅读