base64 data not displaying image from base64_encode - php

I'm trying to convert an image to base64 from an external source, below is my attempt
$imgsrc = file_get_contents('mydomain.com/assets/img/logo.png');
return response()->json([ 'img' => base64_encode($imgsrc) ]);
and below is the output,
data:image/png;base64,PCFET0NUWVBFIGh0bWw+DQo8aHRtbCBsYW5nPSJlbiI+DQogIDxoZWFkPg0KICAgICAgPG1ldGEgY2hhcnNldD0idXRmLTgiPg0KDQogICAgICA8dGl0bGU+Q29ubmVjdG5pZ2VyaWEgfCBFcnJvciA0MDQ8L3RpdGxlPg0KDQogICAgICA8bWV0YSBuYW1lPSJyb2JvdHMiIGNvbnRlbnQ9Ik5PSU5ERVgsIE5PRk9MTE9XLCBOT0FSQ0hJVkUsIE5PU05JUFBFVCIgLz4NCiAgICAgIDxsaW5rIHJlbD0ic2hvcnRjdXQgaWNvbiIgaHJlZj0iaHR0cHM6Ly9kZXZjbm1haW4uY29ubmVjdG5pZ2VyaWEuY29tL2Fzc2V0cy9pY28vZmF2aWNvbi5pY28iIHR5cGU9ImltYWdlL2ljbyI+DQoNCiAgICAgIDxtZXRhIG5hbWU9InZpZXdwb3J0IiBjb250ZW50PSJ3aWR0aD1kZXZpY2Utd2lkdGgsIGluaXRpYWwtc2NhbGU9MS4wLCBtYXhpbXVtLXNjYWxlPTEuMCwgdXNlci1zY2FsYWJsZT1ubyIgLz4NCiAgICAgIDxsaW5rIHJlbD0ibWFuaWZlc3QiIGhyZWY9Imh0dHBzOi8vd3d3LmNvbm5lY3RuaWdlcmlhLmNvbS9hc3NldHMvbWFuaWZlc3QuanNvbiIgLz4NCg0KICAgICAgPGxpbmsgaHJlZj0iaHR0cHM6Ly9kZXZjbm1haW4uY29ubmVjdG5pZ2VyaWEuY29tL2Fzc2V0cy9wbHVnaW5zL2ZvdW5kcnkvY3NzL2ZvbnQtYXdlc29tZS5taW4uY3NzIiByZWw9InN0eWxlc2hlZXQiIHR5cGU9InRleHQvY3NzIiBtZWRpYT0iYWxsIj4NCiAgICAgIDxsaW5rIGhyZWY9Imh0dHBzOi8vZGV2Y25tYWluLmNvbm5lY3RuaWdlcmlhLmNvbS9hc3NldHMvcGx1Z2lucy9ib290c3RyYXAvY3NzL2Jvb3RzdHJhcC5taW4uY3NzIiByZWw9InN0eWxlc2hlZXQiIHR5cGU9InRleHQvY3NzIiBtZWRpYT0iYWxsIiAvPg0KICAgICAgPGxpbmsgaHJlZj0iaHR0cHM6Ly9kZXZjbm1haW4uY29ubmVjdG5pZ2VyaWEuY29tL2Fzc2V0cy9wbHVnaW5zL2FuaW1hdGVjc3MvY3NzL2FuaW1hdGUubWluLmNzcyIgcmVsPSJzdHlsZXNoZWV0IiB0eXBlPSJ0ZXh0L2NzcyIgbWVkaWE9ImFsbCIgLz4NCiAgICAgIDxsaW5rIGhyZWY9Imh0dHBzOi8vZGV2Y25tYWluLmNvbm5lY3RuaWdlcmlhLmNvbS9hc3NldHMvcGx1Z2lucy9pbWFnZWhvdmVyL2Nzcy9pbWFnZWhvdmVyLm1pbi5jc3MiIHJlbD0ic3R5bGVzaGVldCIgdHlwZT0idGV4dC9jc3MiIG1lZGlhPSJhbGwiIC8+DQogICAgICA8bGluayBocmVmPSJodHRwczovL2RldmNubWFpbi5jb25uZWN0bmlnZXJpYS5jb20vYXNzZXRzL2Nzcy92cTlkOVVEYVdoLmNzcyIgcmVsPSJzdHlsZXNoZWV0IiB0eXBlPSJ0ZXh0L2NzcyIgbWVkaWE9ImFsbCIgLz4NCiAgPC9oZWFkPg0KICA8Ym9keT4NCiAgICA8c2VjdGlvbiBjbGFzcz0iZnVsbHNjcmVlbiI+DQogICAgICA8ZGl2IGNsYXNzPSJjb250YWluZXIgdi1hbGlnbi10cmFuc2Zvcm0iPg0KICAgICAgICAgIDxkaXYgY2xhc3M9InJvdyI+DQogICAgICAgICAgICAgIDxkaXYgY2xhc3M9ImNvbC1zbS0xMCBjb2wtc20tb2Zmc2V0LTEiPg0KICAgICAgICAgICAgICAgICAgPGRpdiBjbGFzcz0idGV4dC1jZW50ZXIiPg0KICAgICAgICAgICAgICAgICAgICAgIDxpIGNsYXNzPSJ0aS1yZWNlaXB0IGljb24gaWNvbi1sZyBtYjI0IG1iLXhzLTAiPjwvaT4NCiAgICAgICAgICAgICAgICAgICAgICA8aDEgY2xhc3M9ImxhcmdlIj5QYWdlIE5vdCBGb3VuZDwvaDE+DQogICAgICAgICAgICAgICAgICAgICAgPHA+VGhlIHBhZ2UgeW91IHJlcXVlc3RlZCBjb3VsZG4ndCBiZSBmb3VuZCAtIHRoaXMgY291bGQgYmUgZHVlIHRvIGEgc3BlbGxpbmcgZXJyb3IgaW4gdGhlIFVSTCBvciBhIHJlbW92ZWQgcGFnZS48L3A+DQogICAgICAgICAgICAgICAgICAgICAgPGEgY2xhc3M9ImJ0biIgaHJlZj0iaHR0cHM6Ly93d3cuY29ubmVjdG5pZ2VyaWEuY29tLyI+R28gQmFjayBIb21lPC9hPg0KICAgICAgICAgICAgICAgICAgICAgIDxhIGNsYXNzPSJidG4iIGhyZWY9Imh0dHBzOi8vd3d3LmNvbm5lY3RuaWdlcmlhLmNvbS9wYWdlL2NvbnRhY3QtdXMiPkNvbnRhY3QgVXM8L2E+DQogICAgICAgICAgICAgICAgICA8L2Rpdj4NCiAgICAgICAgICAgICAgPC9kaXY+DQogICAgICAgICAgPC9kaXY+DQogICAgICAgICAgPCEtLWVuZCBvZiByb3ctLT4NCiAgICAgICAgICA8ZGl2IGNsYXNzPSJlbWJlbGlzaC1pY29ucyI+DQogICAgICAgICAgICAgIDxpIGNsYXNzPSJ0aS1oZWxwLWFsdCI+PC9pPg0KICAgICAgICAgICAgICA8aSBjbGFzcz0idGktY3Jvc3MiPjwvaT4NCiAgICAgICAgICAgICAgPGkgY2xhc3M9InRpLXN1cHBvcnQiPjwvaT4NCiAgICAgICAgICAgICAgPGkgY2xhc3M9InRpLWFubm91bmNlbWVudCI+PC9pPg0KICAgICAgICAgICAgICA8aSBjbGFzcz0idGktc2lnbmFsIj48L2k+DQogICAgICAgICAgICAgIDxpIGNsYXNzPSJ0aS1wdWxzZSI+PC9pPg0KICAgICAgICAgICAgICA8aSBjbGFzcz0idGktbWFya2VyIj48L2k+DQogICAgICAgICAgICAgIDxpIGNsYXNzPSJ0aS1wdWxzZSI+PC9pPg0KICAgICAgICAgICAgICA8aSBjbGFzcz0idGktYWxlcnQiPjwvaT4NCiAgICAgICAgICAgICAgPGkgY2xhc3M9InRpLWhlbHAtYWx0Ij48L2k+DQogICAgICAgICAgICAgIDxpIGNsYXNzPSJ0aS1hbGVydCI+PC9pPg0KICAgICAgICAgICAgICA8aSBjbGFzcz0idGktcHVsc2UiPjwvaT4NCiAgICAgICAgICA8L2Rpdj4NCiAgICAgIDwvZGl2Pg0KICAgICAgPCEtLWVuZCBvZiBjb250YWluZXItLT4NCiAgPC9zZWN0aW9uPg0KICAgICAgICAgIDxzY3JpcHQgdHlwZT0idGV4dC9qYXZhc2NyaXB0Ij4gDQoNCiAgICAgICAgICAgIHdpbmRvdy5jbl91cmwgPSAnaHR0cHM6Ly93d3cuY29ubmVjdG5pZ2VyaWEuY29tLyc7DQoNCiAgICAgICAgICAgIHdpbmRvdy5iYXNlX3VybCA9ICdodHRwczovL3d3dy5jb25uZWN0bmlnZXJpYS5jb20vJzsNCg0KICAgICAgICAgICAgd2luZG93LmNhcnNfdXJsID0gJ2h0dHBzOi8vY2Fycy5jb25uZWN0bmlnZXJpYS5jb20vJzsNCg0KICAgICAgICAgICAgd2luZG93LmRlYWxzX3VybCA9ICdodHRwczovL2RlYWxzLmNvbm5lY3RuaWdlcmlhLmNvbS8nOw0KDQogICAgICAgICAgICB3aW5kb3cuZXZlbnRzX3VybCA9ICdodHRwczovL2V2ZW50cy5jb25uZWN0bmlnZXJpYS5jb20vJzsNCg0KICAgICAgICAgICAgd2luZG93LnJlYWxlc3RhdGVfdXJsID0gJ2h0dHBzOi8vcmVhbGVzdGF0ZS5jb25uZWN0bmlnZXJpYS5jb20vJzsNCg0KICAgICAgICAgICAgd2luZG93LmpvYnNfdXJsID0gJ2h0dHBzOi8vam9icy5jb25uZWN0bmlnZXJpYS5jb20vJzsNCg0KDQogICAgICAgICAgICAvLyBjb25zdGFudCBnbG9iYWwgc291cmNlcyByZWZlcmVuY2UNCg0KICAgICAgICAgICAgIHdpbmRvdy5nbG9iYWxfc3JjID0gImh0dHBzOi8vZGV2Y25tYWluLmNvbm5lY3RuaWdlcmlhLmNvbS8iOw0KDQogICAgICAgICAgICAgd2luZG93LmxvY2FsX3NyYyA9ICJodHRwczovL3d3dy5jb25uZWN0bmlnZXJpYS5jb20vYXNzZXRzLyI7DQoNCiAgICAgICAgICAgICANCiAgICAgICAgICAgIHdpbmRvdy5wYWdlID0gJyc7DQogICAgICAgICAgICB3aW5kb3cuY3RybCA9ICcnOw0KDQogICAgICAgIDwvc2NyaXB0Pg0KICAgICAgICA8c2NyaXB0IGRlZmVyIHNyYz0iaHR0cHM6Ly93d3cuY29ubmVjdG5pZ2VyaWEuY29tL2Fzc2V0cy9hc3NldHMvanMvYm9vdC5taW4uanMiPjwvc2NyaXB0Pg0KICA8L2JvZHk+DQo8L2h0bWw+DQoNCg==
but on <img> tag, its not rendering.

If you want to display the image, try this
$imageData = "/9j/4AAQSkZJRgABAQEAYABgAAD........";//base64_encode strong
echo '<img src="data:image/gif;base64,' . $imageData . '" />';
OR
$code_base64 = $row['content'];//base64_encode strong
$code_base64 = str_replace('data:image/jpeg;base64,','',$code_base64);
$code_binary = base64_decode($code_base64);
$image= imagecreatefromstring($code_binary);
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);

Related

Encode Image Url is this possible

How to hide an url with base64 like this?
<img src="show_image.php?url=aHR0cDovL2RvbWFpbi5jb20vaW1hZ2UuanBn">
In php you can encode in base64 with base64_encode(), and decode with base64_decode().
So, in your html page script you can do:
<?php
$imageUrl = 'the image url';
echo '<img src="show_image.php?url=' . base64_encode($imageUrl) . '">';
And of course, you'll need to decode it on your show_image script:
<?php
$imageUrl = base64_decode($_GET['url']);
$image = imagecreatefromstring(file_get_contents($imageUrl));
header('Content-Type: image/png');
imagepng($image);

Image not found or type unknown Dompdf 0.8.1 and CodeIgniter

I want to load an image to PDF from generated image.
I had set isRemoteEnabled to true and
generated QRCode working fine
Here is my code.
$this->load->library(array('pdf', 'ciqrcode'));
$data = array('qrlink' => base_url('generateQR?text=123'));
$this->pdf->set_paper('folio');
$this->pdf->loadHtml($this->load->view('pdfoutput', $data, true));
$this->pdf->set_base_path(base_url());
$this->pdf->render();
$this->pdf->stream('QR-PDF', array("Attachment" => false));
And here is my view
<img src="<?= $qrlink ?>" alt="QRcode" width="150px">
But the output say Image not found or type unknown.
So what should I do?
Thanks in advance.
Cheers.
I had a similar issue and after many hours searching the inter-web, I found out (thanks to Atiruz ) that Dompdf does NOT render images well with remote urls e.g. http://your-domain.com/com/images/img.png" /> always gave me the same error [Image not found or type unknown]. In my case***strong text*** I had to use a base64 encoded image and it seemed to have resolved my issue.
I wrote a small snippet that can encode your image into base64 and return a string to use inside your tag.
Here is how to use the base64 encode data as your img src
//Use a valid base64 encoded data string
<img src="your-base64-encoded-image-string" />
Here is the snippet to convert your image into a base64 encoded image data
function encode_img_base64( $img_path = false, $img_type = 'png' ){
if( $img_path ){
//convert image into Binary data
$img_data = fopen ( $img_path, 'rb' );
$img_size = filesize ( $img_path );
$binary_image = fread ( $img_data, $img_size );
fclose ( $img_data );
//Build the src string to place inside your img tag
$img_src = "data:image/".$img_type.";base64,".str_replace ("\n", "", base64_encode($binary_image));
return $img_src;
}
return false;
}
I hope this helps someone out there!
I had the same issue with pdf and i solved using this function
function encode_img_base64($img_path = false): string
{
if($img_path){
$path = $img_path;
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
return 'data:image/' . $type . ';base64,' . base64_encode($data);
}
return '';
}

imagecreatefromstring(): Data is not in a recognized format in

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);
After looking at the codex https://codex.wordpress.org/Function_Reference/wp_insert_attachment, I found the solution:
//get the image from internet
$coverurl = 'https://api.someurl/api/v1/img/' . $somenumber . '/l';
$iresponse = wp_remote_get($coverurl, $iheaders);
$img = $iresponse['body'];
$directory = "/".date('Y')."/".date('m')."/";
$wp_upload_dir = wp_upload_dir();
//encode $img as with html image tag
$imgdata = base64_encode($img);
$filename = "gtb_". $isbnraw.".jpg";
$fileurl = "../wp-content/uploads".$directory.$filename;
$filetype = wp_check_filetype( basename($fileurl), null);
file_put_contents($fileurl, $img);
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $fileurl ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($fileurl)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $fileurl, $post_id);
require_once('../wp-admin/includes/image.php');
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata($attach_id, $fileurl);
wp_update_attachment_metadata($attach_id, $attach_data);
set_post_thumbnail($post_id, $attach_id);
//add media_category
wp_set_object_terms($attach_id, $mediacat, 'media_category');
This converts a base64 into a jpg and imports it into Wordpress plus attaches it to the post/product. It seems to work well. Thanks for your interest.

Convert binary byte array to image in PHP

I have a web service in Java which returns the requested file contents in byte[] (byte array) form. Sometimes these files are HTML files and sometimes they're images. There is no restriction of which file type it is. I'm looking for a way to convert this array to a valid image/string. My working for text files is below:
$bytes = getArray();
$string = implode(array_map("chr", $bytes));
echo $string;
This is the output of the echo $string;
‰PNG IHDR‘h6 pHYsÄÄ•+ OiCCPPhotoshop ICC profilexÚSgTSé=÷ÞôBKˆ€”KoR RB‹€‘&*! Jˆ!¡ÙQÁEEÈ ˆŽŽ€ŒQ,Š Øä!¢Žƒ£ˆŠÊûá{£kÖ¼÷æÍþµ×>ç¬ó³ÏÀ–H3Q5€©BàƒÇÄÆáä.# $p³d!sý#ø~<<+"À¾xÓÀM›À0‡ÿêB™\€„Àt‘8K€#zŽB¦#F€˜&S `ËcbãP-`'æÓ€ø™{[”! ‘ eˆDh;¬ÏVŠEX0fKÄ9Ø-0IWfH°·Àβ0Qˆ…){`È##x„™FòW<ñ+®ç*x™²<¹$9E[-qWW.(ÎI+6aaš#.Ây™24àóÌ ‘àƒóýxήÎÎ6Ž¶_-ê¿ÿ"bbãþåÏ«p#át~Ñþ,/³€;€mþ¢%îh^ u÷‹f²#µ éÚWópø~<ß5°j>{‘-¨]cöK'XtÀâ÷ò»oÁÔ(€hƒáÏwÿï?ýG %€fI’q^D$.Tʳ?ÇD *°AôÁ,ÀÁÜÁü`6„B$ÄÂBB d€r`)¬‚B(†Í°*`/Ô#4ÀQh†“p.ÂU¸=púažÁ(¼ AÈa!ÚˆbŠX#Ž™…ø!ÁH‹$ ɈQ"K‘5H1RŠT UHò=r9‡\Fº‘;È2‚ü†¼G1”²Q=ÔµC¹¨7„F¢Ðdt1š ›Ðr´=Œ6¡çЫhÚ>CÇ0Àè3Äl0.ÆÃB±8, “c˱"¬«Æ°V¬»‰õcϱwEÀ 6wB aAHXLXNØH¨ $4Ú 7 „QÂ'"“¨K´&ºùÄb21‡XH,#Ö/{ˆCÄ7$‰C2'¹I±¤TÒÒFÒnR#é,©›4H#“ÉÚdk²9”, +È…ääÃä3ää!ò[ b#q¤øSâ(RÊjJåå4åe˜2AU£šRݨ¡T5ZB­¡¶R¯Q‡¨4uš9̓IK¥­¢•Óhh÷i¯ètºÝ•N—ÐWÒËéGè—èôw †ƒÇˆg(›gw¯˜L¦Ó‹ÇT071ë˜ç™™oUX*¶*|‘Ê •J•&•*/T©ª¦ªÞªUóUËT©^S}®FU3Sã© Ô–«UªPëSSg©;¨‡ªg¨oT?¤~Yý‰YÃLÃOC¤Q ±_ã¼Æ c³x,!k «†u5Ä&±ÍÙ|v*»˜ý»‹=ª©¡9C3J3W³Ró”f?ã˜qøœtN ç(§—ó~ŠÞï)â)¦4L¹1e\kª–—–X«H«Q«Gë½6®í§¦½E»YûAÇJ'\'GgÎçSÙSݧ §M=:õ®.ªk¥¡»Dw¿n§î˜ž¾^€žLo§Þy½çú}/ýTýmú§õGX³$ÛÎ<Å5qo</ÇÛñQC]Ã#C¥a•a—á„‘¹Ñ<£ÕFFŒiÆ\ã$ãmÆmÆ£&&!&KMêMîšRM¹¦)¦;L;LÇÍÌÍ¢ÍÖ™5›=1×2ç›ç›×›ß·`ZxZ,¶¨¶¸eI²äZ¦Yn…Z9Y¥XUZ]³F­­%Ö»­»§§¹N“N«žÖgðñ¶É¶©·°åØÛ®¶m¶}agbg·Å®Ã“}º}ý= ‡Ù«Z~s´r:V:ޚΜî?}Åô–é/gXÏÏØ3ã¶Ë)ÄiS›ÓGgg¹sƒóˆ‹‰K‚Ë.—>.›ÆÝȽäJtõq]ázÒõ›³›Âí¨Û¯î6îiî‡ÜŸÌ4Ÿ)žY3sÐÃÈCàQåÑ?Ÿ•0k߬~OCOgµç#/c/‘W­×°·¥wª÷aï>ö>rŸã>ã<7Þ2ÞY_Ì7À·È·ËOÃož_…ßC#ÿdÿzÿѧ€%g‰A[ûøz|!¿Ž?:Ûeö²ÙíAŒ ¹AA‚­‚åÁ­!hÈì­!÷ç˜Î‘Îi…P~èÖÐaæa‹Ã~'…‡…W†?ŽpˆXÑ1—5wÑÜCsßDúD–DÞ›g1O9¯-J5*>ª.j<Ú7º4º?Æ.fYÌÕXXIlK9.*®6nl¾ßüíó‡ââã{˜/È]py¡ÎÂô…§©.,:–#LˆN8”ðA*¨Œ%òw%Ž yÂÂg"/Ñ6шØC\*NòH*Mz’쑼5y$Å3¥,幄'©¼L LÝ›:žšv m2=:½1ƒ’‘qBª!M“¶gêgæfvˬe…²þÅn‹·/•Ék³¬Y- ¶B¦èTZ(×*²geWf¿Í‰Ê9–«ž+Íí̳ÊÛ7œïŸÿíÂá’¶¥†KW-X潬j9²‰Š®Û—Ø(Üxå‡oÊ¿™Ü”´©«Ä¹dÏfÒféæÞ-ž[–ª—æ—n ÙÚ´ ßV´íõöEÛ/—Í(Û»ƒ¶C¹£¿<¸¼e§ÉÎÍ;?T¤TôTúT6îÒݵa×ønÑî{¼ö4ìÕÛ[¼÷ý>ɾÛUUMÕfÕeûIû³÷?®‰ªéø–ûm]­NmqíÇÒý#¶×¹ÔÕÒ=TRÖ+ëGǾþïw- 6 UœÆâ#pDyäé÷ ß÷ :ÚvŒ{¬áÓvg/jBšòšF›Sšû[b[ºOÌ>ÑÖêÞzüGÛœ499â?rýéü§CÏdÏ&žþ¢þË®/~øÕë×Îјѡ—ò—“¿m|¥ýêÀë¯ÛÆÂƾÉx31^ôVûíÁwÜwï£ßOä| (ÿhù±õSЧû“““ÿ˜óüc3-Û cHRMz%€ƒùÿ€éu0ê`:˜o’_ÅFìIDATxÚÁIoUàyËŒ§3žÅN°/Ávš BÛiQ¥J=ô€¢^*nHpAøHÜøœzABÀ$$$TRDQ$$C’62‰—8Nâ‰ñÄÛxÞìoæñ} qðûÁ^Ã%¤T]ÆXl5O¿ÿqǸüo:J²ª)ÊÖÃ{Ÿ}úØš9öÌ~çÞ›èñö»\ˆ)atð²ùõ“Ÿ..NgF£B(§•ÆÑIä;•bŽã\Ô¥J)¿V)®ä–êõÃѳm‹±øÕB‡ÜÀ8ŸL®ž=¯Ó(,&–…çvE>ÇM’ÎIÏuü‚þÉ£íoßùcw÷×?ŸwÍQ»Ý1Œa±£1ÃÖtц>ä(cqÓ·>úà=”’²²tÿöíF·óÍoÏ\׉CŸ"Œ9 0f²`2ªZ-¬ü°³;š«ù…ÀΦ¶šÉ6»ƒ¬¦jXÂæpŒH‰Â5m]¿þBVÿíµùî[FKMK«Çýé|k£¦¨RL#<™â0E{£VãÓZVOï7FSëã÷·oÞ¸ùùW_Ôª¥‡÷ïò¼à{!øùÉ—–íÙsWH+¼ÏOϪÅ%âÞÜ*è‹Š¾Ð1z⢬æ5Ïá¤xàêºf†Oÿn•u­Z)ëZ˜Ñ:³ÑÑÑêu>;íÞÜñÜñXÂù>Ùk­îåúÝŒ9¾šM“±9JÙ Äñt"h®X­”Pry5kœÛ;- T+}bõGãõJe.ºÔóFn¸ ‹›¯—=xwÉ^s6&6Ç(#xAí•l»×{ZßgIÐ䯓þÍ·6’„
But I have no idea how to do this for image files. I could somehow write this array to a file and load the image but my project doesn't allow me to do that. I have to do this on the fly.
If all you want to do is show the image to the user, you simply need to serve the right content header with the response:
if (substr($string, 0, 4) == "\x89PNG") header('Content-Type: image/png');
else if (substr($string, 0, 2) == "\xFF\xD8") header('Content-Type: image/jpeg');
else if (substr($string, 0, 4) == "GIF8") header('Content-Type: image/gif');
echo $string;
An image is really just a blob of data (like the 'string' you have) plus an indication that it's an image (in HTTP, that would be the MIME header). Since you already have the blob, all you need is the header to make the browser interpret it as an image.
Try
$body = file_get_contents('php://input');
and also refer PHP - get image from byte array
You mean like in the examples shown here: http://us.php.net/manual/en/function.imagecreatefromstring.php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
Using below code we can create image from byte array code.
$userId = $userid;
$encoded_image = $imgurl;
$upload_path = $_SERVER["DOCUMENT_ROOT"]."/projectName/uploads/";
$LoginUserDetails = $this->getUserDetails($userId);
if ($LoginUserDetails->profile_image != "") {
$dbimgname = $LoginUserDetails->profile_image;
unlink($upload_path .$dbimgname);
unlink($upload_path . 'thumb_img/' . $dbimgname);
}
$decoded_image = base64_decode($encoded_image);
$imgname = md5(uniqid()) . ".png";
file_put_contents($upload_path . $imgname, $decoded_image);
$thumbnail = $upload_path . "thumb_img/" . $imgname; // Set the thumbnail name
$actual = $upload_path . $imgname; // Set the actual image name
// Get new sizes
$upload_image = $upload_path.$imgname;
// print_r($actual); print_r($thumbnail); print_r($upload_image); die;
list($width, $height) = getimagesize($upload_image);
$newwidth = 196; // This can be a set value or a percentage of original size ($width)
$newheight = 196; // This can be a set value or a percentage of original size ($height)
// Load the images
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefrompng($upload_image);
//print_r($upload_image); print_r($source); die;
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); // Resize the $thumb image.
imagepng($thumb, $thumbnail, 100); // Save the new file to the location specified by $thumbnail
return $imgname;

How can I render a remote image with php?

Here's a jpg: http://i.stack.imgur.com/PIFN0.jpg
Let's say I'd like this rendered from /img.php?file_name=PIFN0.jpg
Here's how I'm trying to make this work:
/sample.php
<p>Here's my image:</p>
<img src="/img.php?file_name=PIFN0.jpg">
/img.php
<?php
$url = 'http://i.stack.imgur.com/' . $_GET['file_name'];
header('Content-type: image/jpeg');
imagejpeg($url);
?>
I would expect /sample.php to show the image. But this doesn't work. All I get is a broken image. What am I doing wrong?
Use imagecreatefromjpeg:
<?php
$url = 'http://i.stack.imgur.com/' . $_GET['file_name'];
header('Content-type: image/jpeg');
imagejpeg(imagecreatefromjpeg($url));
?>
Reference: http://php.net/manual/en/function.imagecreatefromjpeg.php
Here is an working example:
<?php
function img_create($filename, $mime_type)
{
$content = file_get_contents($filename);
$base64 = base64_encode($content);
return ('data:' . $mime_type . ';base64,' . $base64);
}
?>
<img src="<?php print img_create('http://tuxpaint.org/stamps/stamps/animals/birds/cartoon/tux.png','image/png'); ?>" alt="random logo" />
No need to use the GD functions:
<?php
$url = 'http://i.stack.imgur.com/' . $_GET['file_name'];
header('Content-type: image/jpeg');
readfile($url);
?>
<?php
header("Content-Type: image/jpeg");
$url = "http://i.stack.imgur.com/PIFN0.jpg";
$imgContents = file_get_contents($url);
$image = #imagecreatefromstring($imgContents);
imagejpeg($image);
?>
header('Content-type: image/jpeg');
readfile($_GET['id']);
but in the new server, only can read the local images, the remote images is error.

Categories