Reputation: 51
I was successfully able to get an image(which is stored as a BLOB file) from an API endpoint in guzzle, but I am having issues displaying this BLOB file as an image
I have tried several PHP functions for manipulating and converting a BLOB file to an image but all has been abortive.
after sending the request to my guzzle trait, I decided to var_dump the result to be sure that it was successful
$userid = $_COOKIE['id'];
$url = 'users/image/'.$userid;
$requestResult = $this->sendGetWithHeader('users/image/'.$userid);
$result = $requestResult->getBody()->read(1024);
//$res = file_get_contents($result);
// fopen($result, 0);
var_dump($result);
echo "<hr>";
var_dump($requestResult);
// $code = $requestResult->getStatusCode();
// var_dump($code);
My expected result is an image file but the actual is still the raw BLOB file gotten from my Guzzle request
string(1024) "����JFIF��� ��V�"��6 ���UG_ks1��r�[�% ��JMd�CL,��8�Q�B�yoA��g�p�-�a�f� D �)8@�.)ɠ� �yea@4��ԃ(��t��Ew��մPV'J��R��u������Ju��U ��ԥ��zѩaė��ya$�2�C�Sa�R$�4� ���� 2t��$��L�D���R�$�ґ-&RVdm��IDq)Jc�"'9�;/ �sb{��Z�r�̮��Q_MR=5�Gt���
ddA�6�Fa�L���JGi�kh�d�FA�%(�$� �����.�� H�)��-BL������h|#���WW)r�"V[V2˚:��j��˩�>��-$��I�Y�@%dRL(K�(�-�m�I�t��R�JV@�I&JR��0����O2��d�-e@5�2}�2�D'��,Bע��{��!�k�Uw�2ʶ�]cAD�WPw���$��!�Ғu�X!��(�D%I0i�����Lye XI9) �[Nc����@!
�miY,Rkiq(���$����mƬ��y��a����崔͒�t7"����͌ΊJgk Q��Ah�Iq$���ʍA�FmJ���7��AJ�a/�rB�"02A����@�d��J%D� �P�yH���m\ż>�i$��I�(�3jm�542k,��t#��@��@D�F�TJDP" �Z(��7�IZ���h9)$��$�Ԣ�Y� m�D�I�4�����Da�%DX�o ���fhh�.�c��aQhcΉ�٠��)��"
Upvotes: 0
Views: 1346
Reputation: 11
Save your blob response to a file as follows
$stream = \GuzzleHttp\Psr7\Utils::streamFor($requestResult->getBody());
file_put_contents('path/to/file.extension',$stream->getContents())
See Convert blog image to file
Upvotes: 1
Reputation: 998
Look at this example - https://github.com/andriichuk/php-curl-cookbook#download-file
Use 'sink' option to save file from request:
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
$imageFilePath = __DIR__ . '/resource/image.jpeg';
$imageFileResource = fopen($imageFilePath, 'w+');
$httpClient = new Client();
$response = $httpClient->get(
'https://httpbin.org/image/jpeg',
[
RequestOptions::SINK => $imageFileResource,
]
);
if ($response->getStatusCode() === 200) {
echo 'The image has been successfully downloaded: ' . $imageFilePath;
}
Upvotes: 0