Home > Software engineering >  How do i send image in php cUrl to api
How do i send image in php cUrl to api

Time:10-07

I'm trying to create a wordpress php connction to a stable diffusion model on replicate.com. It seems to work but when i'm adding an init image the processing won't start. Actually it halts on "status: starting" with no output prompts. I can see the image on my api prediction on the replicate Dashboard, but i think the image isn't really uploaded. When i click "Tweek" and replaces the image it works. What am i doing wrong here?

curl_setopt($resource, CURLOPT_URL, 'https://api.replicate.com/v1/predictions');
curl_setopt($resource, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($resource, CURLOPT_POST, 1);
$data = array(
   'version' => '56f26876a159c10b429c382f66ccda648c1d5678d7ce15ed010734b715be5ab9', 
   'input' => array(
        'prompt' => 'circles',
        'init_image' => 'https://example.com/wp-content/uploads/img.jpg'
    )
);
curl_setopt($resource, CURLOPT_POSTFIELDS, json_encode($data));
$headers = array();
$headers[] = 'Authorization: Token njdscknjk3nkjn32nk3jn3j';
$headers[] = 'Content-Type: application/json';
curl_setopt($resource, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec($resource); 

CodePudding user response:

You curl is doing what you are asking it to do.
This is what the server will see:

Content-Length: 174
Content-Type: application/json
Accept: */*
BODY=
{"version":"56f26876a159c10b429c382f66ccda648c1d5678d7ce15ed010734b715be5ab9","input":{"prompt":"circles","init_image":"https:\/\/example.com\/wp-content\/uploads\/img.jpg"}}

You are transmitting the image url rather than the image. Try this:

$image = base64_encode(file_get_contents('https://example.com/wp-content/uploads/img.jpg'));

'init_image' => $image;

The image may also need to be prefixed by: 'data:[<mediatype>][;base64],<data>'

$image = 'data: image/jpeg;base64,' .  base64_encode(file_get_contents('https://example.com/wp-content/uploads/img.jpg'));

And the base64 data may (or may not) need to be URL encoded with PHP's urlencode() function.

You are doing an HTTPS post so you may (or may not) need these but the request would not be secure and the server would likely reject it.

curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  • Related