HTTP Responses

The easiest way to return an image directly to the users browser, is to output the response() method. It will automatically send HTTP headers according to the currently image and output encoded image data.

Sending a HTTP response

  1. // create a new image resource
  2. $img = Image::canvas(800, 600, '#ff0000');
  3. // send HTTP header and output image data
  4. echo $img->response('jpg', 70);

Sending HTTP responses manually

  1. // create a new image resource
  2. $img = Image::canvas(800, 600, '#ff0000');
  3. // send HTTP header and output image data
  4. header('Content-Type: image/png');
  5. echo $img->encode('png');

Read more about HTTP responses in the api documentation.


HTTP responses in Laravel Applications

In Laravel applications it is almost the same thing, apart from that you can return the method’s output directly from your route.

Sending a HTTP response in Laravel

  1. Route::get('/', function()
  2. {
  3. $img = Image::canvas(800, 600, '#ff0000');
  4. return $img->response();
  5. });

Attaching images to a HTTP response in Laravel Applications

  1. Route::get('/', function()
  2. {
  3. $img = Image::canvas(800, 600, '#ff0000');
  4. // create response and add encoded image data
  5. $response = Response::make($img->encode('png'));
  6. // set content-type
  7. $response->header('Content-Type', 'image/png');
  8. // output
  9. return $response
  10. });