Laravel fetch image from external API, then visually crop, resize, and save

408 Views Asked by At

I'm sorry in advance for such a general question, but I'm having a hard time getting it answered by google alone. Perhaps I'm not asking the right question?

Here's what I need to do:

  • Need to fetch an image from an external API.
  • Visually crop and resize the image.
  • Save transformed image to DB.

I was looking at some js libraries such as jcrop, Croppie, and cropperjs, but all of those only let me manually upload the images. I'm wondering if there is a solution for this already? Or perhaps someone has done this before and is willing to share their solution?

I'm doing this in Laravel btw, and all of this will be performed in the backend only.

Thanks.

1

There are 1 best solutions below

0
Ali Sharifi Neyestani On

For downloading an image from url you can use curl directly:

    function downloadImage($url, $saveto)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $raw = curl_exec($ch);
        curl_close($ch);
        if (file_exists($saveto)) {
            unlink($saveto);
        }
        $fp = fopen($saveto, 'x');
        fwrite($fp, $raw);
        fclose($fp);
    }

Or you can use a package like Intervention:

    function downloadImage($url, $saveto)
    {
        $path = '/your_storage/';

        $filename = basename($url);

        $image = Image::make($url);
        //for resize and crop you can use resize and crop methods like below
        //$image =  $image->resize(128, 72);  example for resize
        $image->save(public_path($path . $filename));
    }