Preface
Environment
OS: Ubuntu
PHP: 7.4
Laravel: ^8.12
I'm writing a scraper page for a web app that I'm developing and these are the steps that I'm trying to achieve:
- Scrape image from the target website.
- Convert image from
png
towebp
- Upload converted
webp
to my server via FTP.
The core of the program is one line:
Storage::disk('ftp')->put("/FILE_UPLOAD_LOCATION", file_get_contents("scraped-image.png"));
This confirmed that my FTP environment was configured correctly.
Attempts and Errors
I should just be able to do the following should I not?
$image = createimagefromstring(file_get_contents("remote_url.png");
imagepalettetotruecolor($image); // needed for webp
Storage::disk('ftp')->put('remote_desination', imagewebp($image));
The answer is no. This does not work as it just creates a "image" file with 1
as the contents of it.
I haven't tried much outside of this, but hopefully someone has an answer or can point me in a new direction.
CodePudding user response:
This is happening because imagewebp()
doesn't return the image, but a boolean indicating either it worked or not.
You must create a handle to store the image in memory then use it to store on the 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