aarontharker's avatar

Having trouble with image download and manipulation

To explain what I'm trying to accomplish. I'm attempting to download an image from a url (of any mime type), ensure it is png format, and then send it to openai's vartion api. This is my code.

$userAgent = 'Mozilla/5.0 (Windows NT 10.0)'
       . ' AppleWebKit/537.36 (KHTML, like Gecko)'
       . ' Chrome/48.0.2564.97'
       . ' Safari/537.36';
   $headers = array('User-Agent' => $userAgent);
    $client = new Client();
	$client1 = \OpenAI::client(env('OPENAI_API_KEY'));

    $response = $client->get($submission->promptImage, $headers);
    $body = $response->getBody();
    $base64 = base64_encode($body);
    $mime = "image/png";
    $img = ('data:' . $mime . ';base64,' . $base64);

    $response = $client1->images()->variation([
        'image' => fopen($img, 'r'),
        'n' => 4,
            'size' => '1024x1024',
            'response_format' => 'url',
        ]);

I'm getting a response back from Openai that th uploaded image must be PNG. Anyone have any ideas?

0 likes
1 reply
LaryAI's avatar
Level 58

The issue seems to be with the conversion of the downloaded image to a PNG format. To ensure that the image is in PNG format, you can use the Intervention Image package in Laravel. Here's an example of how you can modify your code to achieve this:

use Intervention\Image\ImageManagerStatic as Image;

$userAgent = 'Mozilla/5.0 (Windows NT 10.0)'
   . ' AppleWebKit/537.36 (KHTML, like Gecko)'
   . ' Chrome/48.0.2564.97'
   . ' Safari/537.36';
$headers = array('User-Agent' => $userAgent);
$client = new Client();
$client1 = \OpenAI::client(env('OPENAI_API_KEY'));

$response = $client->get($submission->promptImage, $headers);
$body = $response->getBody();

// Convert the image to PNG format using Intervention Image
$image = Image::make($body)->encode('png');

// Save the converted image to a temporary file
$tempImagePath = sys_get_temp_dir() . '/' . uniqid() . '.png';
$image->save($tempImagePath);

// Open the temporary file and send it to OpenAI
$response = $client1->images()->variation([
    'image' => fopen($tempImagePath, 'r'),
    'n' => 4,
    'size' => '1024x1024',
    'response_format' => 'url',
]);

// Delete the temporary file
unlink($tempImagePath);

Make sure you have the Intervention Image package installed in your Laravel project. You can install it using Composer:

composer require intervention/image

This solution downloads the image, converts it to PNG format using Intervention Image, saves it to a temporary file, and then sends the temporary file to OpenAI. Finally, it deletes the temporary file.

Please or to participate in this conversation.