skip to Main Content

Is it possible to serve a base64 image (GIF) in Nginx that will load in the browser? The encoded string below is a 1×1 white pixel GIF.

I tried this, which isn’t working

location /img.gif {
  default_type "image/gif;base64";
  return 200 "R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=";
}

That image loads fine with

<img width="64" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=">

2

Answers


  1. I have tested a njs approach as you are very flexible with this solution. However – I am not understanding the use case to a 100% but if this is the only solution because you are maybe getting the image bytes b64 encoded from another service on the fly and unable to store them as a file that could be the way to go.

    First load the NGINX njs module load_module modules/ngx_http_js_module.so;

    Create your NJS file

    export default {b64d}
    
    function b64d(r) {
      var imgB64 = "R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=";
      var bytes = Buffer.from(imgB64, 'base64');
      return r.return(200, bytes);
    
    }
    

    save this as gif.js

    NGINX Configuration

    js_import gif from conf.d/gif.js;
    
    server {
      listen 80;
      location / {
        add_header "Content-Type" "image/gif";
        js_content gif.b64d;
      }
    }
    

    This will return the GIF fully rendered.

    $:/etc/nginx/conf.d# curl -s 127.1 --output test.gif && file test.gif
    test.gif: GIF image data, version 89a, 1 x 1
    

    With this you are able to decode and send any image you want.
    Reference: https://nginx.org/en/docs/njs/reference.html#string

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search