What is the effect of encoding an image in base64?

后端 未结 6 950
鱼传尺愫
鱼传尺愫 2020-11-22 07:21

If I convert an image (jpg or png) to base64, then will it be bigger, or will it have the same size? How much greater will it be?

Is it recommended to use base64 enc

6条回答
  •  误落风尘
    2020-11-22 07:41

    The answer is: It depends.

    Although base64-images are larger, there a few conditions where base64 is the better choice.

    Size of base64-images

    Base64 uses 64 different characters and this is 2^6. So base64 stores 6bit per 8bit character. So the proportion is 6/8 from unconverted data to base64 data. This is no exact calculation, but a rough estimate.

    Example:

    An 48kb image needs around 64kb as base64 converted image.

    Calculation: (48 / 6) * 8 = 64

    Simple CLI calculator on Linux systems:

    $ cat /dev/urandom|head -c 48000|base64|wc -c
    64843
    

    Or using an image:

    $ cat my.png|base64|wc -c
    

    Base64-images and websites

    This question is much more difficult to answer. Generally speaking, as larger the image as less sense using base64. But consider the following points:

    • A lot of embedded images in an HTML-File or CSS-File can have similar strings. For PNGs you often find repeated "A" chars. Using gzip (sometimes called "deflate"), there might be even a win on size. But it depends on image content.
    • Request overhead of HTTP1.1: Especially with a lot of cookies you can easily have a few kilobytes overhead per request. Embedding base64 images might save bandwith.
    • Do not base64 encode SVG images, because gzip is more effective on XML than on base64.
    • Programming: On dynamically generated images it is easier to deliver them in one request as to coordinate two dependent requests.
    • Deeplinks: If you want to prevent downloading the image, it is a little bit trickier to extract an image from an HTML page.

提交回复
热议问题