问题描述
我想从PHP函数imagecreate()
生成图像,然后通过VichUploaderBundle使其持久化。供您参考,我正在使用Symfony 5.1
这是我在控制器中使用的测试代码:
$im = imagecreate(110,20);
$background_color = imagecolorallocate($im,0);
$text_color = imagecolorallocate($im,233,14,91);
imagestring($im,1,5,"A Simple Text String",$text_color);
imagepng($im);
$entity->setimageFile($im);
// imagedestroy($im);
$this->getDoctrine()->getManager()->flush();
然后我得到这个错误:
传递给setimageFile()的参数1必须是Symfony \ Component \ HttpFoundation \ File \ File的实例,或者为null,已指定资源
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);
$text_color = imagecolorallocate($im,233,14,91);
imagestring($im,1,5,"A Simple Text String",$text_color);
imagepng($im,$filePath);
$entity->setImageFile(new UploadedFile($filePath,$filename,'image/png'));
我只是将创建的图像存储在系统临时目录中,然后选择一个随机字符串作为文件名。您可能需要根据应用程序需求调整其中的任何一个。