John Davidson

rest - Download blob image from PHP

0 comments
Message:


I'm trying to use an API that generates QR Code images and download the generated image using PHP. This is what I have so far:


function generateQrCode($message){
$url = 'https://backend.com/qr/create-image';
$data = array("message" => $message);
$postdata = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
$file = fopen("qr_code_image.jpg","w");
fwrite($file,$result);
}

I checked the backend (the application that generates the QR Code) and the image is being correctly generated and returned but I'm not being able to download the image as a JPG file from the PHP side. Using CURL to the API:


curl --location --request POST 'https://backend.com/qr/create-image' \
--header 'Content-Type: application/json' \
--data-raw '{
"message":"123"
}'

When I call the API via Postman, I can see the image correctly. But when I call it via PHP, I cannot download the image as a file



My Answer:
One possible issue could be that the response from the API is not directly the image data, but rather a blob or binary data. In this case, you would need to handle the response differently in order to save it as an image file.

You can try using the `file_put_contents` function instead of `fopen` and `fwrite` to save the image data directly to a file. Here's an updated version of your function that should work for downloading blob images:

php
function generateQrCode($message){
$url = 'https://backend.com/qr/create-image';
$data = array("message" => $message);
$postdata = json_encode($data);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$result = curl_exec($ch);
curl_close($ch);

// Save the image data to a file
file_put_contents("qr_code_image.jpg", $result);
}


This should save the image data returned by the API as a JPG file named `qr_code_image.jpg`. Make sure that the API response is indeed the image data in binary format. If it's not, you may need to adjust the code accordingly.

Rate this post

5 of 5 based on 4589 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us