如何解决Silverstripe 4.6 从 url 创建/保存图像对象
我们如何在 DataObject 上创建 has_one Image 关系,并将此 Image 从给定 URL 保存到此 DataObject?
我尝试过的:
class VideoObject extends DataObject
{
private static $has_one = [
'AutoThumbnail' => Image::class
];
private static $owns = [
'AutoThumbnail'
];
public function onAfterWrite() {
parent::onAfterWrite();
$this->imagetest();
}
public function imagetest(){
$folder = Folder::find_or_make('Uploads');
$imageSource = $this->EmbedThumbnailURL; // == ( https://i.ytimg.com/vi/1Rhq53sCfRU/maxresdefault.jpg )
$sourcePath = pathinfo($imageSource);
$fileName = basename($this->EmbedThumbnailURL);
$image = new Image();
$pic = imagecreatefromstring(file_get_contents($imageSource));
imagejpeg($pic,'assets/'.$fileName);
$image->ParentID = $folder->ID;
$image->FileFilename = $fileName;
$image->Name = $fileName;
$image->write();
$this->AutoThumbnailID = $this->ID;
$image->doPublish();
$this->AutoThumbnail()->$image;
}
此处文件夹和文件夹路径出现问题,图像在文件 - 部分中显示不正确(红色方块),也未在模板中显示。 我究竟做错了什么? 你能给我一个有效的例子吗? 谢谢。
解决方法
要从 URL 获取图像,您可以使用 File::setFromString。它会为你做所有的事情。因此,在您的情况下,您可以使用以下内容:
$image = new Image();
$image->setFromString(file_get_contents($imageSource),$fileName);
$imageID = $image->write();
然后您需要将其 ID 分配给您的 VideoObject:
$this->AutoThumbnailID = $imageID;
在此之后,您必须保存/写入 VideoObject 以保留更改,当您将 $this->imagetest() 从 onAfterWrite 移动到 onBeforeWrite 时,它将自动完成(就个人而言,我不认为将它放在 onAfterWrite 中是最幸运的事情).
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。