如何使用 VichUploader 使用 "imagecreate()" 创建的图像?

How to use an image created with "imagecreate()" with VichUploader?

我想从 PHP 函数 imagecreate() 生成一个图像,然后通过 VichUploaderBundle 保存它。供您参考,我使用的是 Symfony 5.1

这是我在控制器中使用的测试代码:

$im = imagecreate(110, 20);
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);
imagepng($im);

$entity->setImageFile($im);
// imagedestroy($im);
$this->getDoctrine()->getManager()->flush();

感谢PHP生成图像的代码来自here

然后我得到这个错误:

Argument 1 passed to setImageFile() must be an instance of Symfony\Component\HttpFoundation\File\File or null, resource given

setImageFile()是使用VichUploader

时要实现的基本功能
/**
 * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile|null $image_file
 */
public function setImageFile(?File $image_file = null): self
{
    $this->image_file = $image_file;
    if (null !== $image_file) {
        // It is required that at least one field changes if you are using doctrine
        // otherwise the event listeners won't be called and the file is lost
        $this->updated_at = new \DateTime('now');
    }

    return $this;
}

setImageFile() 需要一个 File 实例,而您正试图将其传递给一个 resource,正如错误所述..

您需要的是将 imagepng() 输出存储在物理文件中,并使用它来创建 File 的新实例,您将传递给 setImageFile()

一个简单的实现:

$filename = bin2hex(random_bytes(7);
$filePath = sys_get_temp_dir() . "/$filename.png";

$im               = imagecreate(110, 20);
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color       = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);

imagepng($im, $filePath);

$entity->setImageFile(new UploadedFile($filePath, $filename, 'image/png'));

我只是将创建的图像存储在系统临时目录中,并选择一个随机字符串作为文件名。您可能希望根据您的应用程序需求调整其中任何一项。