1

I am finding it surprisingly difficult to post an image that I have manipulated using GD image to an API without first saving it to disk. It seems like there must be some way to post the GD image directly using cURL without the overhead of first saving and then retrieving from disk.

The following code works, however, it has the absurd step of saving the data to disk and then immediately retrieving it again. How can I bypass this absurd step and post the image directly to the API?

One thing that has not worked: replacing realpath with image_data.

//Start with a png image $image that is 1024x1024
//Shrink the image using GD
$temp = imagecreatetruecolor(512, 512);
imagecopyresampled($temp, $image, 0, 0, 0, 0, 512, 512, 1024, 1024);

//Output the GD image to a string named $image_data
ob_start();
imagepng($temp);
$image_data = ob_get_contents();
ob_end_clean();
//Save the image string to disk

//HERE IS THE PART I WANT TO GET RID OF - Saving to and retrieving from disk
$filenamestr = "00tempfile.png";
 $file = fopen($filenamestr, "wb");
    fwrite($file, $image_data);
    fclose($file);
//Get a path to the newly created file on disk
$imagePath = "./".$filenamestr;
$realpath = realpath($imagePath);
//END PART I WANT TO GET RID OF 

//Use cURL to post the file to an API
$url = 'https://anapi.com';

$fields = array(
//HERE IS THE KEY LINE WHERE YOU POST THE DATA. BEHIND THE SCENES CURL SEEMS TO BE PULLING THE DATA FROM THE REALPATH AND
//PUTTING IT IN A STRING BUT THERE MUST BE SOME WAY TO DO THE SAME THING WITHOUT HAVING TO CREATE THIS PATH TO DISK FIRST    
'image' => '@' . $realpath,
    );
    
 $ch = curl_init($url);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
 //other curl options
 $response = curl_exec($ch);

How can I skip this absurd step?

1
  • 1
    Can't you just do 'image' => $image_data? Or use CURLStringFile? Commented Jan 2 at 16:54

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.