Home > Net >  How to return a byte array in laravel controller
How to return a byte array in laravel controller

Time:02-03

public function showphoto()
{
  $bytephoto=DB::select("select photo from photos;");
  return $bytephoto;
}

Hello guys!, This is a PHP code. I want to return a binary data from the database. I am using PostgreSQL. The above code is not giving results. Can anyone help me to overcome this?. I am using Laravel. Thanks in advance

enter image description here

CodePudding user response:

Suppose you just want to show one photo, then

Controller:

public function showphoto()
{
  $bytephoto=DB::select("select photo from photos;");
  return ['bytephoto'=>'data:image/jpeg;base64,' . base64_encode( $bytephoto)];
}

In blade:

<img src="{{$bytephoto}}"/>

CodePudding user response:

I think you just need to select the column like so:

public function showphoto()
{
  $bytephoto=DB::select("select photo from photos;");
  return $bytephoto->photo;
}

Might make more sense to just echo it:

public function showphoto()
{
  $bytephoto=DB::select("select photo from photos;");
  echo $bytephoto->photo;
  exit;
}

But keep in mind that the image would have a mime type and you could detect it and send it out as a header. getimagesize / getimagesizefromstring work out of the box of PHP without needing an extension, and will return a "mime" key which can be used as a header.

So you could do something like this:

public function showphoto()
{
  $bytephoto=DB::select("select photo from photos;");
  $binaryBytes = $bytephoto->photo;
  $imgInfo = getimagesizefromstring($binaryBytes);
  if($imgInfo !== false) {
    header($imgInfo['mime']);
    echo $binaryBytes;
    exit;
  } else {
    echo 'A problem was encountered when trying to serve the image';
    exit;
  }
}

You can also use the data protocol to serve the image:

public function showphoto()
{
  $bytephoto=DB::select("select photo from photos;");
  $binaryBytes = $bytephoto->photo;
  $imgInfo = getimagesizefromstring($binaryBytes);
  if($imgInfo !== false) {
    $mime = $imgInfo['mime'];
    $uri = "data:$mime;base64," . base64_encode($binaryBytes);
    return "<img src=\"$uri\"/>";
  } else {
    return 'A problem was encountered when trying to serve the image';
  }
}
  •  Tags:  
  • Related