前言
环境
操作系统:Ubuntu
PHP:7.4
Laravel:^8.12
我正在为我正在开发的网络应用程序编写一个scraper页面,这些是我试图实现的步骤:
- 从目标网站抓取图像
- 将图像从
png
转换为webp
- 通过FTP将转换后的
webp
上传到我的服务器
程序的核心是一行:
Storage::disk('ftp')->put("/FILE_UPLOAD_LOCATION", file_get_contents("scraped-image.png"));
这证实了我的FTP环境配置正确。
尝试和错误
我应该能做以下事情,不是吗?
$image = createimagefromstring(file_get_contents("remote_url.png");
imagepalettetotruecolor($image); // needed for webp
Storage::disk('ftp')->put('remote_desination', imagewebp($image));
答案是否定的。这不起作用,因为它只是创建了一个";图像";以1
作为其内容的文件。
除此之外,我没有尝试过太多,但希望有人能给我一个答案,或者能给我指引一个新的方向。
之所以会发生这种情况,是因为imagewebp()
不返回图像,而是返回一个布尔值,指示图像是否有效。
您必须创建一个句柄来将图像存储在内存中,然后使用它来存储在ftp:上
$handle=fopen("php://memory", "rw");
$image = createimagefromstring(file_get_contents("remote_url.png");
imagepalettetotruecolor($image); // needed for webp
imagewebp($image, $handle);
imagedestroy($image); // free up memory
rewind($handle); // not sure if it's necessary
Storage::disk('ftp')->put('remote_desination', $handle);
fclose($handle); // close the handle and free up memory