Css url base64 svg

Using an Data URI SVG as a CSS background image

See how the working fiddle has double quotes just inside the url() and then all the SVG content uses single quotes? You need to do the same. Otherwise the parser doesn’t know where the url content ends.

Alternatively you could make the url use single quotes and keep your SVG content the same.

Also works directly on an IMG src by replacing just 4 characters in the SVG string: IMG.src=’data:image/svg+xml;utf8,’+SVG.replace(/»/g, «‘»).replace(//g, «%3e»).replace(/#/g, «%23»);

Sadly, not every browser support «clear» svg syntax in data uri (ex: Chrome) you have to escape it with encodeURIComponent. But it’s no more human readable, with a minimal character set escaped you can «more or less» read it and modify it inplace. You can use a simple line of code as @danny commented above. However, escaping double quotes is not necessary if you encapsulate the result in a simple quoted url(‘data. ‘) .

Here is the transformer (es6): const svg2css = svg=> «url(‘data:image/svg+xml;utf8,»+svg.replace(/\n/g, «»).replace(//g, «%3e»).replace(/#/g, «%23») + «‘)»

You can also use a base64 encoding for a cleaner format, even if it increase the actual SVG file size. See also css-tricks.com post.

background: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIy NCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij4KICAgIDxwYXRoIGQ9 Ik0wIDBoMjR2MjRoLTI0eiIgZmlsbD0ibm9uZSIvPgogICAgPHBhdGggZD0iTTEw LjA5IDE1LjU5bDEuNDEgMS40MSA1LTUtNS01LTEuNDEgMS40MSAyLjU4IDIuNTlo LTkuNjd2Mmg5LjY3bC0yLjU4IDIuNTl6bTguOTEtMTIuNTloLTE0Yy0xLjExIDAt MiAuOS0yIDJ2NGgydi00aDE0djE0aC0xNHYtNGgtMnY0YzAgMS4xLjg5IDIgMiAy aDE0YzEuMSAwIDItLjkgMi0ydi0xNGMwLTEuMS0uOS0yLTItMnoiLz4KPC9zdmc+ Cg=='); 

You can use this bash command (tested on MacOS X) to easily generate the CSS background property:

echo "background: url('data:image/svg+xml;base64,"$(openssl base64 < Downloads/material-design-icons-1.0.0/action/svg/ic_exit_to_app_24px.svg)"');" 

Источник

Css url base64 svg

В этой рубрике Вы найдете уроки, которые относятся к теме создания сайта, но не попали ни в один раздел.

Как выбрать хороший хостинг для своего сайта?

Выбрать хороший хостинг для своего сайта достаточно сложная задача. Особенно сейчас, когда на рынке услуг хостинга действует несколько сотен игроков с очень привлекательными предложениями. Хорошим вариантом является лидер рейтинга Хостинг Ниндзя — Макхост.

Читайте также:  Javascript working with strings

Создан: 15 Апреля 2020 Просмотров: 10584 Комментариев: 0

Как разместить свой сайт на хостинге? Правильно выбранный хороший хостинг - это будущее Ваших сайтов

Проект готов, Все проверено на локальном сервере OpenServer и можно переносить сайт на хостинг. Вот только какую компанию выбрать? Предлагаю рассмотреть хостинг fornex.com. Отличное место для твоего проекта с перспективами бурного роста.

Создан: 23 Ноября 2018 Просмотров: 18138 Комментариев: 0

Разработка веб-сайтов с помощью онлайн платформы Wrike

Создание вебсайта - процесс трудоёмкий, требующий слаженного взаимодействия между заказчиком и исполнителем, а также между всеми членами коллектива, вовлечёнными в проект. И в этом очень хорошее подспорье окажет онлайн платформа Wrike.

20 ресурсов для прототипирования

Топ 10 бесплатных хостингов

Быстрая заметка: массовый UPDATE в MySQL

Ни для кого не секрет как в MySQL реализовать массовый INSERT, а вот с UPDATE-ом могут возникнуть сложности. Чтобы не прибегать к манипуляциям события ON_DUPLICATE можно воспользоваться специальной конструкцией CASE … WHEN … THEN.

Создан: 28 Апреля 2017 Просмотров: 10459 Комментариев: 0

Распознавание текста из изображений через командную строку

Для человека не составляет особого труда посмотреть на изображение и прочитать представленный текст. Для машины данный процесс не так прост. Однако с помощью imgclip вы сможете быстро выполнить данную операцию.

Источник

Как вставить svg картинку на свой сайт

Рассмотрим способы вставки SVG изображений: через тег img, инлайново, base64, теги object и embed; а также как вставить SVG картинку через CSS.

SVG через свойство background

Вставка SVG в HTML

SVG через тег img

Inline SVG в HTML

SVG data URI / base64

Закодированное SVG изображение будет начинаться с:

data: image/svg+xml; utf8; base64,

SVG через тег object

SVG через тег embed

Вставка SVG в CSS через свойство background

SVG через свойство background

Inline SVG CSS background

Свойство background будет начинаться с

Также необходимо кодировать символы, например, с помощью этого инструмента.

SVG data URI / base64

data: image/svg+xml; utf8; base64,

Источник

Читайте также:  Java interface with abstract methods

How do I use an tag when all I have is a base64 string for the image?

I would like to show an SVG image. I want to use CSS to modify the SVG directly, so I need to use an tag. However, I don't have the SVG source - all I have is the SVG encoded as a base64 string. In my HTML page, with an image tag, it looks something like this:

How can I create an svg tag those shows the same image using the same base64 string? Every thread and piece of documentation I've found so far seems to assume that I'm either using the tag in my SVG or including my raw SVG inside my tags, neither of which apply in my situation. I want to do something like this:

  data:image/svg+xml;base64,lotsofunreadablestuff.  

You've lost a lot of information because the vector graphics description of the image has been converted to a bitmap already. Converting the other way is not likely to be feasible.

Have you tried a Base64 converter, ie: askapache.com/online-tools/base64-image-converter . and a web search on "base64 image to svg" will give more links

Upon further review, this page [ codepen.io/tigt/post/optimizing-svgs-in-data-uris ] explains that sometimes SVG ascii text is encoded into BASE 64 just to avoid having to HTML escape the XML characters in the SVG.

height= xlink:href=" data:image/svg+xml;base64,lotsofunreadablestuff. "/> but you won't be able to style it with CSS unless you embed the CSS into lotsofunreadablestuff itself as the image is a separate document.

1 Answer 1

You can only apply CSS to SVGs within the same document. That means you'll either have to inline the SVG into your HTML, or embed your CSS into the SVG code itself.

Now, in order to inline an SVG, it depends on what you have.

For this answer I'm going to use the following data URL, which translates into (what is supposed to be) a camera icon:

data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgdmlld0JveD0iMCAtMTAgMTAwIDg1IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogICAgPGRlZnM+CiAgICAgICAgPGNsaXBQYXRoIGlkPSJjbGlwIj4KICAgICAgICAgICAgPHBhdGggZD0iTTAsMCBMMTAwLDAgTDEwMCw3NSBMMCw3NSBMMCwwCiAgICAgICAgICAgICAgICAgICAgIE01MCwxNSBBMjAsMjAgMCAxLDAgNTAsNjAgQTIwLDIwIDAgMSwwIDUwLDE1CiAgICAgICAgICAgICAgICAgICAgIE01MCwyNSBBMTIuNSwxMi41IDAgMSwxIDUwLDUwIEExMi41LDEyLjUgMCAxLDEgNTAsMjUiLz4KICAgICAgICA8L2NsaXBQYXRoPgogICAgPC9kZWZzPgogICAgPHJlY3QgeD0iMzAiIHk9Ii0xMCIgd2lkdGg9IjQwIiBoZWlnaHQ9IjIwIiByeD0iMTAiIHJ5PSIxMCIvPgogICAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEwMCIgaGVpZ2h0PSI3NSIgcng9IjE1IiByeT0iMTUiIGNsaXAtcGF0aD0idXJsKCNjbGlwKSIvPgo8L3N2Zz4K 

1. Static data

If you have a hardcoded data URL that you want to use, you can simply decode it using any base64 decoder out there. Just paste the blob after base64, into the decoder and it should give your the raw XML back, which you can then embed into your HTML.

If you use the data URL from above, look up the first Google result for "base64 decode" and paste the part after base64, in there, you get:

Читайте также:  Java type not supported exception

You should strip the tag before inlining it into HTML to be 100% standard-compliant, but that's all you have to do, the rest should work just fine if pasted into your HTML.

2. Dynamic data

If the data URL is not fixed however, you need your application to do the decoding and inlining.

Again there are two ways to do this:

2.1 Server-side

I would consider server-side inlining the cleanest way to deal with dynamic data.
In theory any programming language can do this, and as long as it's got a base64 decoder and an XML parser, it shouldn't be too complicated.
Since you didn't say what (if any) server-side language you're using, I'm going to use PHP as an example, and I'm making use of the DOM extension, which is enabled and available by default.

First you'll want to get the XML from your data URL. You can (ab)use file_get_contents for that:

$xml = file_get_contents($dataURL); 

Next you'll want to parse that XML into a DOM document:

$dom = new DOMDocument(); $dom->loadXML($xml); 

And then you'll want to export just the root node (without the saveXML with the root node as first argument, i.e.:

$svg = $dom->saveXML($dom->documentElement); 

This of course has the disadvantage of needing to have a server-side application run in the first place (other than the web server).

2.2 Client-side

If you need or want to do this in the browser, there is really only one option: JavaScript.

Similar to PHP's file_get_contents , you can (ab)use JavaScript's XMLHttpRequest to "load" the data from the URL:

var xhr = new XMLHttpRequest(); xhr.open('GET', dataURL); xhr.addEventListener('load', function(ev) < var xml = ev.target.response; // All following code here >); xhr.send(null); 

Equivalent to PHP's DOM library, JavaScript has DOMParser , which you can use to parse the entire string into a DOM document:

var dom = new DOMParser(); var svg = dom.parseFromString(xml, 'image/svg+xml'); 

And finally you can append the root element (i.e. svg.rootElement ) anywhere you like in your DOM tree, e.g.

document.body.appendChild(svg.rootElement); 
var dataURL = 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgdmlld0JveD0iMCAtMTAgMTAwIDg1IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogICAgPGRlZnM+CiAgICAgICAgPGNsaXBQYXRoIGlkPSJjbGlwIj4KICAgICAgICAgICAgPHBhdGggZD0iTTAsMCBMMTAwLDAgTDEwMCw3NSBMMCw3NSBMMCwwCiAgICAgICAgICAgICAgICAgICAgIE01MCwxNSBBMjAsMjAgMCAxLDAgNTAsNjAgQTIwLDIwIDAgMSwwIDUwLDE1CiAgICAgICAgICAgICAgICAgICAgIE01MCwyNSBBMTIuNSwxMi41IDAgMSwxIDUwLDUwIEExMi41LDEyLjUgMCAxLDEgNTAsMjUiLz4KICAgICAgICA8L2NsaXBQYXRoPgogICAgPC9kZWZzPgogICAgPHJlY3QgeD0iMzAiIHk9Ii0xMCIgd2lkdGg9IjQwIiBoZWlnaHQ9IjIwIiByeD0iMTAiIHJ5PSIxMCIvPgogICAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEwMCIgaGVpZ2h0PSI3NSIgcng9IjE1IiByeT0iMTUiIGNsaXAtcGF0aD0idXJsKCNjbGlwKSIvPgo8L3N2Zz4K'; var xhr = new XMLHttpRequest(); xhr.open('GET', dataURL); xhr.addEventListener('load', function(ev) < var xml = ev.target.response; var dom = new DOMParser(); var svg = dom.parseFromString(xml, 'image/svg+xml'); document.body.appendChild(svg.rootElement); >); xhr.send(null);

Источник

Оцените статью