Base 64 encode vs loading an image file

55,814

Solution 1

  • Base64 encoding makes the file bigger and therefore slower to transfer.
  • By including the image in the page, it has to be downloaded every time. External images are normally only downloaded once and then cached by the browser.
  • It isn't compatible with all browsers

Solution 2

Why regenerate the image again and again if it will not be modified. Hypothetically, even if there are a 1000 different possible images to be shown based on 1000 different conditions, I still think that 1000 images on the disks are better. Remember, disk based images can be cached by the browser and save bandwidth etc etc.

Solution 3

Don't think data:// works in IE7 or below.

When an image is requested you could save it to the filesystem then serve that from then on. If the image data in the database changes then just delete the file. Serve it from another domain too like img.domain.com. You can get all the benefits of last-modified, or e-tags for free from your webserver without having to start up PHP unless you need too.

If you're using apache:

# If the file doesn't exist:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/(image123).jpg$ makeimage.php?image=$1

Solution 4

To answer the initial question, I ran a test measuring a jpeg image 400x300 px in 96 ppi:

base64ImageData.Length
177732

bitmap.Length
129882

Solution 5

I have used base64 images once or twice for icons (10x10 pixels or so).

Base64 images pros:

  • compact - you have single file. also if file is compressed, base64 image is compressed almost to the size of normal image.
  • page is retrieved in single request.

Base64 images cons:

  • to be realistic, you probably need to use scripting engine (such PHP) on all pages that contains the image.
  • if image is changed, all cached pages must be re-downloaded.
  • because image is inline, you can not use CDN or static content web server.

Normal images pros:

  • if you are use SPDY protocol, at least theoretical, page + images + CSS will load with single request too.
  • you can set expiration on the image, so content will be cached from the browsers.
Share:
55,814
teh_noob
Author by

teh_noob

Welcome to The Internet.

Updated on March 22, 2020

Comments

  • teh_noob
    teh_noob about 4 years

    So I am working on something in php where I have to get my images from a sql database where they will be encoded in base64. The speed of displaying these images is critical so I am trying to figure out if it would be faster turn the database data into an image file and then load it in the browser, or just echo the raw base64 data and use:

    <img src="data:image/jpeg;base64,/9j/4AAQ..." />
    

    Which is supported in FireFox and other Gecko browsers.

    So to recap, would it be faster to transfer an actual image file or the base64 code. Would it require less http request when using ajax to load the images?

    The images would be no more than 100 pixels total.