Here is how I get my image:
$coverurl = 'https://api.someurl/api/v1/img/' . $somenumber . '/l';
//$iheaders contains: 'Content-type' => 'image/jpeg'
$iresponse = wp_remote_get($coverurl, $iheaders);
$img = $iresponse['body'];
$testimg = base64_encode($img);
When I echo $testimg with an img-tag, everything works fine.
echo '<img class="attachment-shop_single size-shop_single wp-post-image" src="data:image/jpeg;base64,'.$testimg.'" width="274" />';
Since I need to convert the string into a jpg and save it to my uploads folder, I tried to use imagecreatefromstring()
.
$imgx = imagecreatefromstring($testimg);
if ($imgx !== false) {
header('Content-Type: image/jpeg');
imagejpeg($imgx);
imagedestroy($imgx);
} else {
echo 'An error occurred.';
}
But I never get to the point of saving anything, because of the following warning:
Warning: imagecreatefromstring(): Data is not in a recognized format in /etc.
When I echo $testimg
I get:
/9j/4AAQSkZJRgABAQAAAQABAAD ...Many number and characters.. Ggm2JUsEvfqnxAhGFDP/9k=
What must I do to make createimagefromstring
work? Do I have to modify the $testimg
string? Thanks for your interest.
The method imagecreatefromstring
does not take a base_64 encoded string. Try this instead:
$imgx = imagecreatefromstring($img); // Contents of $iresponse['body']
You can see this in the topmost comment in the documentation page (linked above):
<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With