Search code examples
phphasheid

PHP - how to get the image from hash picture?


I have eID card reader SDK used from ( https://github.com/KeejOow/eidlib ), it works great.

using the SDK it allowed me to read my ID card details but i need to read the picture so i got this Hash Picture value using SDK.

Hash picture: *P¿xxxxxxxxx

CODE:

public function removemeoncetestedAction() {
    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender();
    //$this->_response->setHeader('Access-Control-Allow-Origin', '*');

    $this->db = Application_Model_Db::db_load();
    $sql = "select *From idcard order by id desc limit 1";
    $cresult = $this->db->fetchAll($sql);

    if(count($cresult) > 0) {
      $arr = explode("\n", $cresult[0]['card']);
      $encodedPhoto = base64url_decode($arr[18]); // Hash picture
      //header('Content-Type: image/jpeg');
      echo "<img src='{$encodedPhoto}' />";

    } 
    exit;
  }

How can i get from this hash field the real picture png, jpeg? when i execute above code i do not get any image preview at all.


Solution

  • You're approach won't work because you have placed binary image data in your <img> src attribute where the browser expects to see a URL. You need to provide a URL from which the browser can get the image.

    There is a straightforward way to do this that will work well for small images: a Data URI.

    You can embed a base64 encoded imaged like this (this example gives a red dot):

    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
    

    (Thanks to Wikipedia for this example)

    Using your code, the relevant portion would become:

    if(count($cresult) > 0) {
      $arr = explode("\n", $cresult[0]['card']);
      $encodedPhoto = $arr[18]; // Hash picture - no need to decode.
      echo "<img src='data:image/jpeg;base64,{$encodedPhoto}' />";  // Add the data uri header
    } 
    

    Note: I am assuming that your code is correctly extracting a base64 encoded JPEG image from the source data. If the image format is different, or the code you're using to extract the image is wrong then it's likely this snippet won't work.