Skip to content
Advertisement

Send a Base64/BLOB image data from PHP to Javascript

TL;DR

Is there a way to send a directly usable base64/BLOB image data to javascript?

I’m trying to send an array(containing string & img) to my Vue component from my page.blade.php returned from my controller in Laravel.

MORE DETAILS

I know data encoding is my problem and json_encode($my_string_data) only works for UTF-8 but not the IMG data. json_encode($my_image_data) will throw an error malformed utf-8 characters possibly incorrectly encoded image.

I am making 1 request then 2 DB queries in my controller and combining both responses(string & MEDIUMBLOB/img data) then return it as an array to my blade.php, in my blade file is the vue component taking in the img data as props.

Possible solutions I wanna know how:

  1. How do I do make this img data directly usable by javascript?
  2. If #1 is not possible, how do I convert this img data directly readable by javascript?
  3. If #2 is not possible, how do I convert this img data JSON-able by json_encode($my_image_data) ?

enter image description here

I’m only assuming that the IMG data returned by the database from a BLOB column is Base64, mb_detect_encoding()-ing the variable containing IMG data always returns false so I cannot know what is it in the first place. All I know Is must convert this data to UTF-8 or anything JSON-able for JS to use.

ATM, I’m still trying to make solution #3.

Advertisement

Answer

 $image = 'yourimage'; 

// Read image path, convert to base64 encoding  
$imageData=base64_encode(file_get_contents($image)); 

// Format the image SRC: data:{mime};base64,{data}; 
$src = 'data: '.mime_content_type($image).';base64,'.$imageData; 

And now the src is urldata and can be ready to be transformed to js.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement