Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API with images

Tags:

rest

php

I am in the process of putting together a REST API of an image application to be consumed by an Angular Frontend. The API is being put together using PHP. All of the images are securely stored outside of the webroot.

Problem is that I am converting all my images to base64, it increases the payload, in some cases I have 40 images display on a page, not uncommon to wait 30-40 seconds due to the huge payload.

What is the best practice for presenting images using REST API? I have searched round, there is nothing that exactly addresses the problem. Code below. The base64 images bloats the payload by an incredible amount. Any pointers please.

//create presentation array
$presentation_arr=array();
$presentation_arr["records"]=array();
$LargeImageName = $slideName;
$LargefileDir = $largefolder. $fileid . '/';
$Largefile = $LargefileDir . $LargeImageName;

if (file_exists($Largefile)){
    $b64largeImage = base64_encode(file_get_contents($Largefile));
    $datafullpath = 'data:image/jpg;base64,$b64image';
}

$presentation_item=array(
    "id" => $id,
    "smallimage" => $b64image,
    "largeimage" => $b64largeImage
);

array_push($presentation_arr["imagerecords"], $presentation_item);
like image 740
Matt Allen Avatar asked Jun 16 '26 09:06

Matt Allen


1 Answers

Two approaches:

  • Create a "wrapper" endpoint that is just a proxy to the final image itself (e.g. does a readfile() internally, see this: https://stackoverflow.com/a/1353867/1364793)
  • Host the images at a static, web accessible folder (or even consider S3 as a storage for static assets). Then, your main endpoint just returns publicly accessile URLs to those.
like image 180
Dzhuneyt Avatar answered Jun 17 '26 22:06

Dzhuneyt



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!