Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Response Image in Laravel 7

I'm trying to create a mini random image generator, as a start I've tried :

Route::get('/img/UoJb9wl.png','Image@random');

All I did is to return this

return '<img src="/assets/fe/img/welcome.jpeg" alt="Smiley face" width="200">';

Then, I tested on the live site :

I see the image loaded if I go to the URL

https://www.bunlongheng.com/img/UoJb9wl.png

enter image description here

If I imported on a site like JSFiddle like this

<img src="https://www.bunlongheng.com/img/UoJb9wl.png">

I can't see it.

Why ?


Edit

Try #2

return env('APP_URL').'/assets/fe/img/welcome.jpeg';

I return image path now

But I still nothing rendering in my JSFiddle still

<img src="https://www.bunlongheng.com/img/UoJb9wl.png">

like image 912
code-8 Avatar asked Jan 26 '26 22:01

code-8


1 Answers

That doesn't work because your controller returns not an image, but an HTML code.

When you use this address in your browser, it sends request to your server, server responds with HTML which contains <img src="..."/> with link to the actual image, so browser shows it.

When you try to use the same address in the <img src="..."/>, your server still returns HTML code which is not an image, so obviously it won't be shown.


  1. You can always serve the image itself:
function random()
{
  return response()->file(/* path to image file */);
}
  1. You can check Accept header to determine what to respond:
function random(Request $request)
{
  $accept = $request->header('Accept');
  if (strpos($accept, 'text/html') !== false) {
    return response()->html('<img ...');
  } elseif (strpos($accept, 'image/') !== false) {
    return response()->file(...);
  }
  abort(403, 'No content for requested type');
}
like image 132
Styx Avatar answered Jan 28 '26 13:01

Styx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!