Что такое base64 и зачем он нужен в веб разработке?

Base64 Image Data URL Scheme

Some applications that use URLs also have a need to embed (small) media type data directly inline. This document defines a new URL scheme that would work like ‘immediate addressing’. The URLs are of the form:


The is an Internet media type specification (with optional parameters.) The appearance of «» means that the data is encoded as base64. Without «», the data (as a sequence of octets) is represented using ASCII encoding for octets inside the range of safe URL characters and using the standard hex encoding of URLs for octets outside that range. If is omitted, it defaults to . As a shorthand, «» can be omitted but the charset parameter supplied.

The «» URL scheme is only useful for short values. Note that some applications that use URLs may impose a length limit; for example, URLs embedded within anchors in HTML have a length limit determined by the SGML declaration for HTML . The LITLEN (1024) limits the number of characters which can appear in a single attribute value literal, the ATTSPLEN (2100) limits the sum of all lengths of all attribute value specifications which appear in a tag, and the TAGLEN (2100) limits the overall length of a tag.

Data URL Scheme Syntax

dataurl    := "data:"   "," data
mediatype  := [ type "/" subtype ] *( ";" parameter )
data       := *urlchar
parameter  := attribute "=" value

Как выглядит Data URL?

Data URL — это строка, начинающаяся с данных, за которой следует формат типа MIME. Например, PNG-изображение имеет mime-тип image/png, за которым следует запятая и только потом фактические данные.

Текст обычно передается в текстовой форме, а двоичные данные обычно закодированы в base64.

Ниже представлено, как выглядят Data URL:

<img src=»data:image/png,ABQCAIAAABtUGDWAA…» />

Пример Data URL, закодированного в base64:

data:image/png;base64:

<img src=»data:image/png;base64,iVBORw0KGgoAAAANSUh…» />

Можно использовать закодированную строку base64 в CSS. Скопируйте строку и вставьте в код следующим образом:

.example { background-image url(‘data:image/png;base64,iVBORw0KGgoAAAANSUh…’); }

Когда использовать Конвертер изображений Base64?

Base64 не отображает изображения, и поэтому Google не формирует индекс изображения, так как он не появляется в процессе поиска изображений.

Можно использовать Конвертер изображений Base64 для не столь важных изображений, которые не приносят трафик, например, для иконок социальных сетей. В таких иконках (например, Twitter, Google+, Facebook и др.) изображения такие маленькие, что нет необходимости в формировании индекса. Такие иконки никогда не приносят трафик.

Лучше всего использовать кодирование base64 для миниатюрных изображений. Если использовать его для крупных изображений, вы получите длинный код в HTML. Большинство веб-страниц имеют от 8 до 12 социальных иконок, и нет необходимости в из загрузке. В этом случае Base64 — это наилучший выбор.

Data URI и Base64-кодирование неразрывно связаны друг с другом. Data URL — это схема унифицированного указателя ресурса, который позволяет включать элемент данных в веб-страницу подобно внешним ресурсам. Data URL — это локатор единообразного ресурса, но он фактически удаленно не определяет местонахождение. Вместо этого, данные ресурсов находятся в URL-строке в виде закодированной строки base64. Это не позволяет браузеру делать дополнительные HTTP-запросы для внешних ресурсов и таким образом может увеличить скорость загрузки страницы.

Data URL сокращает количество HTTP-запросов, которые необходимы браузеру для отображения HTML-документа

Сокращение количества запросов браузера является важной частью оптимизации времени загрузки веб-страниц. Поэтому Data URL может иметь положительный эффект на функционирование.

Data URL обеспечивает быструю загрузку при передаче маленьких файлов

Передача данных через TCP начинается медленно, и каждый внешний ресурс устанавливает новое TCP-подключение к серверу. Скорость передачи может быть замедлен трафиком TCP-подключения.

Меньшая нагрузка сети

Data URL использует меньше трафика, когда нагрузка кодирования данных в виде Data URL меньше нагрузки HTTP-запроса. Например, необходимое для изображения в 600 байт кодирование base64 будет иметь 800 байт, поэтому, если HTTP-запрос требует нагрузки больше 200 байт, data URI будет более эффективным.

Быстрые HTTP-запросы

HTTPS-запросы имеют намного больше нагрузки, чем обычные HTTP-запросы. Если веб-сайт обслуживается с помощью HTTPS, обеспечение ресурсов через Data URL поможет значительно улучшить функционирование .

More Info and Resources

The Base 64 Alphabet

     Value Encoding  Value Encoding  Value Encoding  Value Encoding
         0 A            17 R            34 i            51 z
         1 B            18 S            35 j            52 0
         2 C            19 T            36 k            53 1
         3 D            20 U            37 l            54 2
         4 E            21 V            38 m            55 3
         5 F            22 W            39 n            56 4
         6 G            23 X            40 o            57 5
         7 H            24 Y            41 p            58 6
         8 I            25 Z            42 q            59 7
         9 J            26 a            43 r            60 8
        10 K            27 b            44 s            61 9
        11 L            28 c            45 t            62 +
        12 M            29 d            46 u            63 /
        13 N            30 e            47 v
        14 O            31 f            48 w         (pad) =
        15 P            32 g            49 x
        16 Q            33 h            50 y

RFC’s

  • RFC 1866 — Hypertext Markup Language — 2.0
  • RFC 2045 — Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies
  • RFC 2046 — Definition of media types
  • RFC 2077 — Model top-level media type
  • RFC 2396 — Uniform Resource Identifiers (URI): Generic Syntax
  • RFC 2397 — The «data» URL scheme
  • RFC 3023 — Media types based on XML
  • RFC 4648 — The Base16, Base32, and Base64 Data Encodings
  • RFC 6657 — Update to MIME regarding «charset» Parameter Handling in Textual Media Types
  • RFC 5988 — Web Linking

Type image

GIF image; Defined in RFC 2045 and RFC 2046
JPEG JFIF image; Defined in RFC 2045 and RFC 2046
JPEG JFIF image; Associated with Internet Explorer; Listed in ms775147(v=vs.85) — Progressive JPEG, initiated before global browser support for progressive JPEGs (Microsoft and Firefox).
Portable Network Graphics; Registered, Defined in RFC 2083
SVG vector image; Defined in SVG Tiny 1.2 Specification Appendix M
Tag Image File Format (only for Baseline TIFF); Defined in RFC 3302
ICO image; Registered

Misc

  • Image to data URI convertor
  • : Your one-stop HTML5 spot for all things Data URL
  • The data: URI kitchen
  • php: data://
  • Using Data URLs Effectively with Cascading Style Sheets
  • getID3: PHP script that extracts useful information from MP3s & other multimedia file formats:

Draw image on canvas

With the data URI you can create an image and draw it on canvas when the image is loaded.

   var ctx = canvas.getContext("2d");
   var image = new Image();
   image.onload = function () {
      ctx.drawImage(image, dx, dy, dWidth, dHeight);
   }
   image.src = "data:image/svg+xml,%3Csvg/%3E ... %3C/svg%3E";

Help it seems like Firefox can’t draw the image on canvas


If you’re having issues in Firefox please check that your inline SVG has a width and height defined (not in styling but as attributes). Even though it works in all other browsers without they’re needed for Firefox (tested with v. 49.0.2). Lost some time here I’ll never get back!

What it can do

SVGO has a plugin-based architecture, so almost every optimization is a separate plugin.

Today we have:

Plugin Description Default
cleanupAttrs cleanup attributes from newlines, trailing, and repeating spaces
inlineStyles move and merge styles from elements to element attributes
removeDoctype remove doctype declaration
removeXMLProcInst remove XML processing instructions
removeComments remove comments
removeMetadata remove
removeTitle remove
removeDesc remove
removeUselessDefs remove elements of without
removeXMLNS removes attribute (for inline svg)
removeEditorsNSData remove editors namespaces, elements, and attributes
removeEmptyAttrs remove empty attributes
removeHiddenElems remove hidden elements
removeEmptyText remove empty Text elements
removeEmptyContainers remove empty Container elements
removeViewBox remove attribute when possible
cleanupEnableBackground remove or cleanup attribute when possible
minifyStyles minify elements content with CSSO
convertStyleToAttrs convert styles into attributes
convertColors convert colors (from to , from to )
convertPathData convert Path data to relative or absolute (whichever is shorter), convert one segment to another, trim useless delimiters, smart rounding, and much more
convertTransform collapse multiple transforms into one, convert matrices to the short aliases, and much more
removeUnknownsAndDefaults remove unknown elements content and attributes, remove attrs with default values
removeNonInheritableGroupAttrs remove non-inheritable group’s «presentation» attributes
removeUselessStrokeAndFill remove useless and attrs
removeUnusedNS remove unused namespaces declaration
prefixIds prefix IDs and classes with the SVG filename or an arbitrary string
cleanupIDs remove unused and minify used IDs
cleanupNumericValues round numeric values to the fixed precision, remove default units
cleanupListOfValues round numeric values in attributes that take a list of numbers (like or )
moveElemsAttrsToGroup move elements’ attributes to their enclosing group
moveGroupAttrsToElems move some group attributes to the contained elements
collapseGroups collapse useless groups
removeRasterImages remove raster images
mergePaths merge multiple Paths into one
convertShapeToPath convert some basic shapes to
convertEllipseToCircle convert non-eccentric to
sortAttrs sort element attributes for epic readability
sortDefsChildren sort children of in order to improve compression
removeDimensions remove / and add if it’s missing (opposite to removeViewBox, disable it first)
removeAttrs remove attributes by pattern
removeAttributesBySelector removes attributes of elements that match a css selector
removeElementsByAttr remove arbitrary elements by ID or className
addClassesToSVGElement add classnames to an outer element
addAttributesToSVGElement adds attributes to an outer element
removeOffCanvasPaths removes elements that are drawn outside of the viewbox
removeStyleElement remove elements
removeScriptElement remove elements
reusePaths Find duplicated elements and replace them with links

Want to know how it works and how to write your own plugin? Of course you want to. (동작방법)

Image to base64 encoding example

Image input:

Image data URI scheme with base64 encoded data output:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCABWAFIDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD8RkOR7/WpYwdv+19ahVwByOakjk/I19Bc+sJoxgjOB3qzAhIGRyTVeORcjjt3q7aOjAAH5j0rKTtqyJS0uIY/Xp3prwYB649a+v8A/h1bqug/svad8Rda8QWdmusWouoLVeTEGGUV+eCQR0zivky/szZXctu2C8bbTj61z0sVCq2oPYyp1oz+FmZLHxwD+dQSA9M5rovE/gbVPClpZTX9jc2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xX1B4C/wCCiWqaFoSWerx3FziML50D7WYjuQeDXdQoYeb5p6SPzjiLIMXPEe3wTsnuvM9+/al8cWk9hdzXN60pjYlUyFGc+gxXw5+0B8YZ/HFzHY71MNuNvy8cDpV743ftIS/EK6k+ypPFHIct5hHNeRXEzzSFnOWY5J9aWMlDmtT2Ppciy2dGivbbjM+1NLAUM+DTHc4riPpmFFFFAWZGoycU/P8AOiigHuLml3miigRYtpmjfg8EVYec4PTg49aKKpGaSuVpJMt0xxULMScUUVPUtDaR/umiigY3caKKKDQ//9k=

is the data URI scheme header.

is the encoded base64 data.

HTML <img> with base64 data URI

Usage

CLI

  • with files:

    $ svgo test.svg

    or:

    $ svgo *.svg
    $ svgo test.svg -o test.min.svg
    $ svgo test.svg other.svg third.svg
    $ svgo test.svg other.svg third.svg -o test.min.svg -o other.min.svg -o third.min.svg
  • with STDIN / STDOUT:

    $ cat test.svg | svgo -i - -o - > test.min.svg
  • with folder

    $ svgo -f ../path/to/folder/with/svg/files

    or:

    $ svgo -f ../path/to/folder/with/svg/files -o ../path/to/folder/with/svg/output
    $ svgo *.svg -o ../path/to/folder/with/svg/output
  • with strings:

    $ svgo -s '<svg version="1.1">test</svg>' -o test.min.svg

    or even with Data URI base64:

    $ svgo -s 'data:image/svg+xml;base64,...' -o test.min.svg
  • with SVGZ:


    from to :

    $ gunzip -c test.svgz | svgo -i - -o test.min.svg

    from to :

    $ svgo test.svg -o - | gzip -cfq9 > test.svgz

Other Ways to Use SVGO

  • as a Nodejs module – examples
  • as a Grunt task – grunt-svgmin
  • as a Gulp task – gulp-svgmin
  • as a Mimosa module – mimosa-minify-svg
  • as an OSX Folder Action – svgo-osx-folder-action
  • as a webpack loader – image-webpack-loader
  • as a Telegram Bot – svgo_bot
  • as a PostCSS plugin – postcss-svgo
  • as an Inkscape plugin – inkscape-svgo
  • as a Sketch plugin — svgo-compressor
  • as a Rollup plugin — rollup-plugin-svgo

How does a Data URL look?

A Data URL is a string that starts with data: followed by the MIME type format. For example, a PNG image has mime type image/png which is followed by a comma and then by the actual data.

Text is usually transferred in plain text, while binary data is usually base64 encoded.

Here is an example of how such Data URL will look like:

<img src=»data:image/png,ABQCAIAAABtUGDWAA…» />

Here is how a base64 encoded Data URL looks like:

data:image/png;base64:

<img src=»data:image/png;base64,iVBORw0KGgoAAAANSUh…» />

You can use the base64 encoded string in CSS. You can copy the string and put it into your code like this:

.example { background-image url(‘data:image/png;base64,iVBORw0KGgoAAAANSUh…’); }

Force download

Now we want to download the image. In modern browsers there is a download attribute for anchors which tells the browser that it should download the resource the anchor points to rather than navigate to it. We can force it by creating an anchor and trigger a click with a mouse event:

   var event = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true
   });

   var a = document.createElement('a');
   a.setAttribute('download', 'image.jpg');
   a.setAttribute('href', url);
   a.setAttribute('target', '_blank');
   a.dispatchEvent(event);

The download attribute is however not supported in IE or Safari yet why I’m checking for support and if not opening the image in a new window instead.

Download attribute support:

   var a = document.createElement('a');
   var downloadAttrSupport = typeof a.download !== "undefined";

Open in new window:

   var opened = window.open();
   if (opened) {
      opened.document.write(svg);
      opened.document.close();
      opened.focus();
   }

For Edge you can force a download with the msSaveOrOpenBlob() method.

   
   if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
      navigator.msSaveOrOpenBlob(blob, filename);
   }

Image to base64 encoding example

Image input:

Image data URI scheme with base64 encoded data output:


data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCABWAFIDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF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eteXU9LQxKK2j44fP/AB52P/fuineXYfu9jFibAqQNgmq+cVOhyKslkoPPrXQ+AfCtz448VWGlWkE9xcXkyx7IELuVzyQB6DJrno3BK17T+xV408N/DX4mTeIvEt00Ftpts4gjRNzzyv8AKMDp3NcWOnKNJuCu+hw4ypKFKUoK7PuD4X+CvCv7HPwdvr4S+fHpXm3H2m5RZpGlkUII12jjJ2gAe+c818j+Bv2oNfm+KEk2o3PnWeqXJ8+GZsKiscZBzkBc9K+7U/Y4i/4KFfsj2niLwhr81pK0zy2envxDdyxuykSnPDED5R0+Y/Wvl/4k/sE+JPCf2+G68P3unapZr+7tXgJMuD8wD9DjFfKUctfs39ZV5S/A+eyb6viYyeIklN6WfQ8/+Osa+LfEepX+j3FtLpVgrBZC3DqhAJx1ALdK8H8Y6C0mlw6rFD5UNwzIwXpn19q9G0n4IeML7Up0exvtPtpMxyPOCkW3I49+laHxS8HW3gf4dXVhK2/yYwUPZmPce1fU5bgvYUlDse86tKCjToW7aHz7J8jHIHFMMoYEEYFOZgzZz1qMnGB6V3noiZPrRRx70UAIrDHWpFf5s1X3DFOD496ALMcmCParEcwwOpGc9aoBx9KlSfCiixEkfpH/AMESv+CicfwT1a78Aa95UthqFz9v04zHaiSgDdH6ANjI96/QT4mfFu28daZdX9ne+X5qtJsyHGc8gZr+ezw3qcmmahHcxSNHLCQ6MpIKkdxX1B4C/wCCiWqaFoSWerx3FziML50D7WYjuQeDXdQoYeb5p6SPzjiLIMXPEe3wTsnuvM9+/al8cWk9hdzXN60pjYlUyFGc+gxXw5+0B8YZ/HFzHY71MNuNvy8cDpV743ftIS/EK6k+ypPFHIct5hHNeRXEzzSFnOWY5J9aWMlDmtT2Ppciy2dGivbbjM+1NLAUM+DTHc4riPpmFFFFAWZGoycU/P8AOiigHuLml3miigRYtpmjfg8EVYec4PTg49aKKpGaSuVpJMt0xxULMScUUVPUtDaR/umiigY3caKKKDQ//9k=

is the data URI scheme header.

is the encoded base64 data.

HTML <img> with base64 data URI

Who use data URIs?

In order to assess the popularity of a technology, you need to analyze what others are doing (especially the “big guys”). That is why I analyzed the first 20 websites according to the Alexa Top 500 and I specified the list of used media types for each website that embeds data via data URIs. Please note, that since I analyzed only home pages with a parser that doesn’t support JavaScript, I may have missed some websites or media types. In any case, at least 20 of the 20 largest sites use data URIs, so obviously it is not a bad idea.

  • google.com (image/gif, image/jpg, image/png)
  • youtube.com (text/javascript, image/gif, image/png, application/x-mpegurl, image/svg+xml)
  • facebook.com (text/css, application/x-font-woff, font/opentype)
  • baidu.com (image/png, image/jpeg, image/gif, image/svg+xml)
  • wikipedia.org (image/svg+xml, image/png)
  • qq.com (image/png, application/x-silverlight, text/html, text/plain, image/webp)
  • taobao.com (image/png, image/gif, image/svg+xml, image/webp)
  • yahoo.com (image/png, image/svg+xml, image/gif)
  • tmall.com (image/gif, image/jpeg, image/png, image/webp)
  • amazon.com (image/gif, image/png, image/svg+xml)
  • google.co.in (image/gif, image/jpg, image/png)
  • twitter.com (image/gif, image/png)
  • sohu.com (image/png, application/x-font-ttf, application/font-woff, image/svg+xml, image/gif, application/json, image/jpeg, image/webp)
  • live.com (application/json, image/gif, image/png, application/font-woff)
  • jd.com (image/png, image/webp, application/json)
  • instagram.com (image/png)
  • weibo.com (application/font-woff, image/svg+xml)
  • sina.com.cn (image/webp)
  • vk.com (image/svg+xml, font/woff, audio/wav, text/css)
  • reddit.com (image/png)

When to use Base64 Image Maker?

Base64 does not show the images, thus the image will never be indexed by Google because it does not show up in the image search.

You can use the Base64 Image maker for not so important images that do not bring traffic, for example, social icons. Little icons such as Twitter, Google+, Facebook, etc. images are really small and have no need to be indexed. Those little icons never bring traffic.

It is best to use base64 encode only for tiny images. If you try to base64 larger images you will end up with a great deal of code in your HTML and lose out on the performance benefits. Many webpages have 8 or 12 social icons and there is no need to download them. So the Base64 is the best choice in this case!

Data URIs and Base64 encoding go hand-in-hand. Data URLs are a Uniform Resource Identifier scheme that allows you to include data items inline in a web page as if they were being referenced as external resources. Data URLs are a form of Uniform Resource Locators, although they do not in fact remotely locate anything. Instead, the resource data is contained within the URL string itself as a base64-encoded string. This saves the browser from having to make additional HTTP requests for the external resources, and can thus increase page loading speed.

Data URLs reduces the number of HTTP requests that the browser needs to make to display an HTML document. Minimizing the number of browser requests is an important part of optimizing web page loading times. So Data URLs can thus have beneficial effects on performance.

Data URLs can result in faster downloading for transferring small files.

Data transfers via TCP start slowly, and each external resource starts a new TCP connection to the server. The transfer speed may thus be held back by the overhead of TCP communication.

Less bandwidth usage.

Data URLs use less bandwidth whenever the overhead of encoding the data as a Data URL is smaller than the overhead of an HTTP request. For example, the required base64 encoding for an image 600 bytes long would be 800 bytes, so if an HTTP request required more than 200 bytes of overhead, the data URI would be more efficient.

Faster HTTPS.

HTTPS requests have much greater overhead than ordinary HTTP requests due to SSL encryption. If your website is served over HTTPS, providing resources via Data URLs can improve performance significantly.

What tools does Smush.it use to smush images?

We have found many good tools for reducing image size. Often times these tools are specific to particular image formats and work much better in certain circumstances than others. To «smush» really means to try many different image reduction algorithms and figure out which one gives the best result.

These are the algorithms currently in use:

  1. ImageMagick: to identify the image type and to convert GIF files to PNG files.
  2. pngcrush: to strip unneeded chunks from PNGs. We are also experimenting with other PNG reduction tools such as pngout, optipng, pngrewrite. Hopefully these tools will provide improved optimization of PNG files.
  3. jpegtran: to strip all metadata from JPEGs (currently disabled) and try progressive JPEGs.
  4. gifsicle: to optimize GIF animations by stripping repeating pixels in different frames.

С этим читают