API
The package contains high-level conversion function :
from psd2svg import psd2svg # File IO. psd2svg('path/to/input.psd', 'path/to/output/') # Stream IO. with open('input.psd', 'rb') as fi: with open('output.svg', 'w') as fo: psd2svg(fi, fo) # psd_tools IO. from psd_tools import PSDImage psd = PSDImage.load('path/to/input.psd') svg = psd2svg(psd) print(svg) # Additionally, individual layers can be directly rendered. layer_svg = psd2svg(psd) print(layer_svg)
The package also has rasterizer module to convert SVG to PIL Image:
from psd2svg.rasterizer import create_rasterizer rasterizer = create_rasterizer() image = rasterizer.rasterize(svg) image.save('path/to/output.png')
The rasterizer requires one of Selenium + ChromeDriver, Apache Batik, or
Inkscape. Make sure to install them beforehand.
Способы подключения SVG на страницу
Для самой базовой имплементации SVG у нас есть следующие варианты:
1. SVG в
See the Pen SVG as img src by Heather Migliorisi (@hmig) on CodePen.
Перед тем, как продолжить, проверьте статистику браузеров посетителей вашего сайта. Если используется версия Safari Desktop 9.1.1 или iOS Version 9.3.2, а также более поздняя версия, то этого кода достаточно.
Однако многие пользователи по прежнему используют более старые версии Safari или IOS, поэтому нам надо добавить , вот так: .
И спасибо разработчикам, пофиксившим этот баг Safari/WebKit.
Этот пример хорош в качестве самого простого способа подключения SVG, но он не дает нам доступа к содержимому SVG с помощью AT (Assistive technology) или CSS/JS. Поэтому, если нам нужно больше контроля над SVG, мы инлайнируем его непосредственно в HTML.
2. Инлайновый SVG
Инлайновый SVG дает более полный контроль и более предсказуемые результаты, чем при использовании с или , так как исходники SVG непосредственно доступны в DOM, а DOM полностью открыт для API вспомогательных технологий.
Возьмем тот же базовый SVG из примера с и попробуем добавить движение глаз. Мы можем сделать это с помощью JavaScript, если мы вложим SVG непосредственно в HTML.
See the Pen Basic SVG — Cat by Heather Migliorisi (@hmig) on CodePen.
Так как в SVG нет никакого видимого текста, описывающего графику, нам надо добавить альтернативный текст:
- внутри , добавив , который должен быть первым потомком родительского элемента — это будет использоваться как подсказка при наведении курсора.
- описание, при необходимости (оно не будет зачитываться).
В соответствии со , нам не надо делать ничего дополнительно, кроме добавления и, возможно, так как они доступны Accessibility API. К сожалению, поддержка в браузерах пока недостаточна (см. Chrome и Firefox).
Чтобы гарантировать доступ AT к и :
Добавьте соответствующий ID к и :
В теге добавьте:
aria-labelledby=»uniqueTitleID uniqueDescID» используйте ID названия и описания; подключение и названия, и описания обеспечивает лучшую поддержку в скринридерах, чем aria-describedby.
Еще один момент:
в теге добавьте role=»img» (таким образом, SVG не будет проходиться браузерами, которые добавляют SVG роль группы).
Итак, добавляем анимацию (моргание глаз):
Обновите название/описание так, чтобы оно точно описывало изображение:
See the Pen Simple Inline Accessible SVG Cat — using title and desc by Heather Migliorisi (@hmig) on CodePen.
3. Вложение SVG с помощью или
Сейчас я стараюсь держаться подальше от использования или . Они неадекватны в плане использования со скринридером.
Вот как это было у меня.
Итак, выбираем метод вложения SVG и добавляем :
Используя нашего моргающего кота из последнего примера, нам надо заменить на .
И с этого момента все становится хуже.
Добавьте элемент в SVG , в котором будет находится содержимое и, возможно, (для NVDA):
Затем добавьте класс, чтобы спрятать текст визуально, оставив содержимое доступным для скринридеров. Мы можем сделать это, задав .
Итак, мы пришли к тому, что (а, по возможности, и ) и содержат одинаковый контент, для поддержки JAWS и NVDA.
Примечания:
- и не работают в Chrome. Chrome видит содержимое запасного варианта (), поэтому вы можете скинуть весь текст туда, скопировав его в третий (или в четвертый) раз.
- JAWS не читает содержимое (кроме отмеченного /)
Я рекомендую (исходя из поддержки браузерами и скринридерами) использовать, где возможно
Как работает анимация в контурах
Рассмотрим подробнее, как работает анимация в контурах.
У вас есть SVG-файл. Он должен иметь элемент stroke. Контур должен быть пунктирным. Зададим нужное свойство через CSS. Длина пунктира должна быть достаточно большой.
Устанавливаем смещение контура через stroke-dashoffset. Подключаем анимацию, которая будет убирать смещение. Если установить достаточно большие значения для двух свойств у контура, то получим сплошной контур, который будет двигаться.
Значение forwards запустит анимацию один раз. Для бесконечной анимации применяем infinite.
Возьмём для опыта котёнка с замечательного сайта ikonka.ru.
В примере величина stroke-dasharray подбиралась на глазок. Чтобы не угадывать нужное значение, можно воспользоваться JavaScript.
Идея How SVG Line Animation Works | CSS-Tricks»>отсюда.
Summary
This plot was created with Gnuplot: |
Gnuplot code
set output 'out.svg' set term svg size 750,500 dynamic font "sans-serif" fname "PT Sans Caption" set key inside bottom right set xlabel 'Year' set ylabel 'Oil production (millions of barrels per day)' #set title 'Canadian oil production' set autoscale xfix set grid set style data lines set key at first 1990, first 4 width 2 height 2 spacing 2\ box linetype rgb "#000000" lw 2 plot \ "data.txt" using (($1>=1950 && $12013)?$11)($21e3) title "Historical" lw 3 linetype rgb "#ff0000", \ "data.txt" using (($1>=2013 && $12030)?$11)($21e3) title "Forecast" lw 3 linetype rgb "#0000ff"
#year #thousands of barrel per day 1947 19,960568 1948 32,48721633 1949 57,53643175 1950 78,44376275 1951 130,1697362 1952 167,0265093 1953 221,2084056 1954 262,7758178 1955 353,9644259 1956 469,0608681 1957 495,9957802 1958 450,9563753 1959 502,7713712 1960 517,8243275 1961 604,2888309 1962 668,6994399 1963 706,7380097 1964 749,7629384 1965 799,2837177 1966 875,3211023 1967 959,9410801 1968 1020,540581 1969 1116,046756 1970 1238,788278 1971 1478,105531 1972 1694,475022 1973 1958,647074 1974 1840,398631 1975 1575,597598 1976 1441,624629 1977 1447,285458 1978 1428,416026 1979 1609,562576 1980 1535,97179 1981 1379,984483 1982 1350,422372 1983 1435,334818 1984 1531,568923 1985 1566,791863 1986 1571,823712 1987 1642,269592 1988 1725,295094 1989 1674,976608 1990 1666,170873 1991 1665,541892 1992 1733,471848 1993 1822,787161 1994 1892,604061 1995 1960,534017 1996 2001,417787 1997 2103,312722 1998 2208,352561 1999 2103,985077 2000 2190,271797 2001 2217,504581 2002 2346,291076 2003 2417,732666 2004 2595,535467 2005 2495,081645 2006 2636,454938 2007 2751,863462 2008 2713,768632 2009 2805,12268 2010 2852,803394 2011 3025,377537 2012 3231,758727 2013 3474,623662 2014 3678,059452 2015 3907,969257 2016 4180,705469 2017 4325,966182 2018 4539,422406 2019 4736,030522 2020 4909,685061 2021 5092,867858 2022 5245,46685 2023 5395,316393 2024 5597,506952 2025 5741,80789 2026 5909,190292 2027 6037,695566 2028 6166,309184 2029 6277,997163 2030 6441,789922
Атрибут stroke-dasharray
Управляет видом пунктирной обводки. Можно задавать в единицах длины или в процентах. Если задано одно значение, второе значение считается равным первому. Например, stroke-dasharray=»1″ нарисует линию из отрезков длиной одну единицу разделенных пробелами такой же ширины.
Значения указываются в порядке dash и gap (пунктир и промежуток); безразмерные числа считаются пикселями. Хотя значения могут быть указаны любыми единицами измерения. Создадим линию:
Применим два значения.
А если три? Если задано странное значение, то оно будет повторяться, чтобы получился повторяющийся узор. Т.е. значение 5, 10, 5 будут описывать следующее: «черточка 5, разрыв 10, черточка 5, разрыв 5, черточка 10, разрыв 5»
Обводка для круга
See the Pen SVG stroke made from beads by yoksel (@yoksel) on CodePen.
Используя обводку и простые фигуры можно получить удивительные вещи:
See the Pen SVG-patterns by yoksel (@yoksel) on CodePen.
Благодарности
Огромное спасибо Амелии Беллами-Ройдс и Леони Уотсон за проверку примеров и выявление проблем. Я бы не смогла написать эту статью без их помощи.
Баги, сообщения о которых были отправлены в ходе работы над статьей:
Microsoft:
- https://connect.microsoft.com/IE/Feedback/Details/2483564
- https://connect.microsoft.com/IE/Feedback/Details/2480772
Mozilla:
- https://bugzilla.mozilla.org/show_bug.cgi?id=1257399
- https://bugzilla.mozilla.org/show_bug.cgi?id=1257600
Баги, исправленные в ходе работы над статьей:
- баг Safari/WebKit, требовавший добавления в тег .
- баг Chrome, требовавший добавления или в SVG для чтения его названия.
File history
Click on a date/time to view the file as it appeared at that time.
Date/Time | Thumbnail | Dimensions | User | Comment | |
---|---|---|---|---|---|
current | 13:11, 12 September 2012 | 628 × 550 (1 KB) | Odder | optimized version by Palosirkka | |
19:43, 20 February 2008 | 628 × 550 (2 KB) | Amada44 | again some path cleanup | ||
19:08, 20 February 2008 | 628 × 550 (2 KB) | Amada44 | more cleanup | ||
21:02, 14 April 2007 | 1,280 × 1,066 (2 KB) | Tene~commonswiki | Cleanup | ||
16:17, 1 February 2006 | 1,280 × 1,066 (2 KB) | Bastique | Had not noticed lack of white on sign in Firefox. IE it’s readily apparent. | ||
18:17, 30 January 2006 | 1,280 × 1,066 (2 KB) | Dbenbenn | cleaned SVG code, scaled up so it fills the image description page, and cropped better. Changes are PD | ||
16:11, 14 January 2006 | 64 × 54 (3 KB) | Joris Gillis~commonswiki | warning sign |
Графика и альтернативный текст
Перед тем как перейти к собственно доступным SVG, разберемся с несколькими основными вопросами о графике, доступности и альтернативном тексте.
2. Какой контекст у графики и окружающего ее текста?
Если графика окружена текстом или содержимым, в котором есть альтернативный текст, то дополнительный альтернативный текст в атрибуте не нужен. Например:
See the Pen SVG as img src for figure with figcaption by Heather Migliorisi (@hmig) on CodePen.
Какой альтернативный текст наиболее оптимален для графики, которой необходим атрибут (см. пример 4 для подробной информации)? В зависимости от содержимого изображения, он может быть разным:
See the Pen SVG as img src for figure with figcaption by Heather Migliorisi (@hmig) on CodePen.
3. Есть ли у графики функция? Если так, то она должна быть донесена до пользователя.
Например, вместо точного описания того, что представлено на иконках…
Пример плохого кода:
…передайте пользователю контекст иконки.
Пример хорошего кода:
Для более полного понимания ознакомьтесь со статьей WebAIM “Alternative Text” и руководством W3C по доступности изображений.
Примеры в статье работают с браузерами, поддерживающими SVG (IE 10+, FF, Chrome и Safari) и : Jaws, NVDA, VoiceOver (VO) и Narrator.
API
Converts the specified SVG into a JPEG using the provided via a headless Chromium instance.
can either be a SVG buffer or string.
If the width and/or height cannot be derived from then they must be provided via their corresponding options.
This method attempts to derive the dimensions from via any / attributes or its calculated
attribute.
This method is resolved with the JPEG output buffer.
An error will occur if both the and options have been provided, does not contain an SVG
element or no and/or options were provided and this information could not be derived from .
Option | Type | Default | Description |
---|---|---|---|
String | N/A | Background color to be used to fill transparent regions within the SVG. White will be used if omitted. | |
String | N/A | Path of the file to be converted into a file URL to use for all relative URLs contained within the SVG. Cannot be used in conjunction with the option. | |
String | Base URL to use for all relative URLs contained within the SVG. Cannot be used in conjunction with the option. | ||
Number/String | N/A | Height of the output to be generated. Derived from SVG input if omitted. | |
Object | N/A | Options that are to be passed directly to when creating the instance. | |
Number | Quality of the output to be generated. | ||
Number | Scale to be applied to the width and height (specified as options or derived). | ||
Number/String | N/A | Width of the output to be generated. Derived from SVG input if omitted. |
The option is not available when calling this method on a instance created using
.
Example
const { convert } = require('convert-svg-to-jpeg'); const express = require('express'); const app = express(); app.post('/convert', async(req, res) => { const jpeg = await convert(req.body); res.set('Content-Type', 'image/jpeg'); res.send(jpeg); }); app.listen(3000);
Converts the SVG file at the specified path into a JPEG using the provided and writes it to the output file.
The output file is derived from unless the option is specified.
If the width and/or height cannot be derived from the input file then they must be provided via their corresponding
options. This method attempts to derive the dimensions from the input file via any / attributes or its
calculated attribute.
This method is resolved with the path of the JPEG output file for reference.
An error will occur if both the and options have been provided, the input file does not contain an
SVG element, no and/or options were provided and this information could not be derived from input file,
or a problem arises while reading the input file or writing the output file.
Has the same options as the standard method but also supports the following additional options:
Option | Type | Default | Description |
---|---|---|---|
String | N/A | Path of the file to which the JPEG output should be written to. Derived from input file path if omitted. |
Example
const { convertFile} = require('convert-svg-to-jpeg'); (async() => { const inputFilePath = '/path/to/my-image.svg'; const outputFilePath = await convertFile(inputFilePath); console.log(outputFilePath); //=> "/path/to/my-image.jpeg" })();
Creates an instance of using the provided.
It is important to note that, after the first time either or are called, a
headless Chromium instance will remain open until is called. This is done automatically when using
the convert methods, however, when using directly, it is the responsibility of the caller. Due to the
fact that creating browser instances is expensive, this level of control allows callers to reuse a browser for multiple
conversions. It’s not recommended to keep an instance around for too long, as it will use up resources.
Example
const { createConverter } = require('convert-svg-to-jpeg'); const fs = require('fs'); const util = require('util'); const readdir = util.promisify(fs.readdir); async function convertSvgFiles(dirPath) { const converter = createConverter(); try { const filePaths = await readdir(dirPath); for (const filePath of filePaths) { await converter.convertFile(filePath); } } finally { await converter.destroy(); } }
Captions
Summaryedit
Can be used to create Category:Locator_maps_of_continents. Every continent is a separate group.
Map adapted from PDF world map at CIA World Fact Book
map does not include portrayal of Antarctica or New Zealand.
Licensingedit
This image is in the public domain because it contains materials that originally came from the United States Central Intelligence Agency’s World Factbook. |
File history
Click on a date/time to view the file as it appeared at that time.
Date/Time | Thumbnail | Dimensions | User | Comment | |
---|---|---|---|---|---|
current | 17:04, 15 November 2006 | 585 × 299 (105 KB) | JesperZedlitz | Map adapted from PDF world map at CIA World Fact Book == Licensing == {{PD-USGov-CIA-WF}} Category:SVG_world_maps |
File usage on other wikis
The following other wikis use this file:
- Usage on en.wikipedia.org
- Usage on et.wikipedia.org
- Maurice Greene
- Sébastien Loeb
- Christian Ziege
- Dietmar Hamann
- Michael Ballack
- Torsten Frings
- David Trezeguet
- Simone Perrotta
- Gianluca Zambrotta
- Eha Rünne
- Tatjana Lebedeva
- Asafa Powell
- Bryan Clay
- Birgit Fischer
- Jeremy Wariner
- Franz Beckenbauer
- Jaan Jaago
- Gustav Vahar
- Karl Veimann
- Georg Baumann
- Eduard Pütsep
- Bershawn Jackson
- Walter Davis (kolmikhüppaja)
- Marit Bjørgen
- Eldar Rønning
- Lina Andersson
- LeBron James
- Mike Powell
- Riitta-Liisa Roponen
- Mats Larsson
- Adam Małysz
- Ole Einar Bjørndalen
- Sonia O’Sullivan
- Pietro Piller Cottrer
- Chad Hedrick
- Jennifer Heil
- Rainer Schönfelder
- Anna Carin Olofsson-Zidek
- Shizuka Arakawa
- Irina Slutskaja
- Justyna Kowalczyk
- Andrea Pirlo
- Zé Roberto
- Fabio Grosso
- Larissa Latõnina
- Patrick Vieira
- Simon Ammann
- Harri Olli
- Charlotte Kalla
View more global usage of this file.
Интерактивные изображения
Еще лучше, в сравнении с диаграммами и графиками, обстоят дела с доступностью интерактивных изображений. Рассмотрим простую хронологическую инфографику. Она разбивается на верхнюю часть с заголовком и раздел хронологии, который в свою очередь разбивается на сегменты, каждый из которых содержит заголовок, изображение и описание.
Добавим этой инфографике немного жизни и анимируем временные сегменты. Вместо того, чтобы показывать всю информацию сразу, мы выведем только время и круг с названием кошачьей активности. При взаимодействии пользователя с временем или названием будет выводиться остальная информация.
1. Настройка файла
Все то же самое, что и в секции предыдущего раздела. Но после описания оптимизации для веба можете смело пропускать все об анимации CSS и переходить непосредственно к доступности.
2. Доступность
Стили удалены из следующих примеров для упрощения кода, но они, разумеется, есть в работающем демо.
Проходимость для скринридеров — чтобы SVG был проходимым во всех браузерах, добавьте к SVG /
Название и описание — в нашем примере мы можем использовать текст в верхней части SVG () в качестве названия и ссылаясь на него с помощью в .
Затем добавим к и привяжем его к с помощью .
Добавление семантических ролей — добавьте семантические роли к группам, содержащим хронологию и ее отдельные сегменты. Вот группа с полным списком: .
Добавьте метку к списку: .
Отдельные временные сегменты будут элементами списка: .
Взаимодействие/доступность с клавиатуры — сразу после каждого элемента с добавьте так, чтобы он охватывал все содержимое группы. На данный момент это единственный способ добавить интерактивность к SVG.
Добавьте туда же , чтобы обеспечить фокусируемость во всех браузерах.
Исправление семантики ссылок — обратите внимание, что ссылки указывают сами на себя. Это не семантичные ссылки, так как они не ведут к чему-либо и могут смутить пользователей скринридеров
Поэтому добавим , чтобы обозначить, что это изображение, а не ссылка.
Доступность текста внутри временных сегментов — добавление роли изображения прекращает проход элементов вспомогательными технологиями, поэтому нам надо добавить с идентификаторами текстовых элементов в том порядке, в котором они читаются.
Добавление скрытого описания для изображений — используйте с классом для скрытия элемента так, что визуально он скрыт, но остается в DOM.
Добавление идентификатора к атрибуту в так, чтобы он стал читаемым.
Добавление стилей для фокуса — настройка стилей для фокуса необходима пользователям, осуществляющим навигацию в браузере с помощью клавиатуры. Мне нравятся эти стили, поэтому я добавила их и для наведенного состояния.
Добавление JavaScript для фокуса окна — в SVG при навигации по ссылкам окно не всегда сдвигается так, чтобы элемент оказался в области видимости. Причина этого в том, что некоторые браузеры (баг-репорт добавлен и, надеюсь, скоро будет исправление) прокручивают элемент целиком, не учитывая, что некоторые дочерние элементы могут оказаться за экраном. Поэтому мы добавим немного JavaScript к прокрутке окна, чтобы обеспечить видимость сфокусированных элементов.
Есть и более эффективные способы, но для нашего быстрого примера хватит и этого:
See the Pen Accessible Interactive SVG by Heather Migliorisi (@hmig) on CodePen.
Видео с демонстрацией работы скринридеров:
- JAWS
- NVDA
- VoiceOver
- Narrator
Getting Started
Installation
To use svg-to-img in your project, run:
npm install svg-to-img -S
Note: When you install svg-to-img, it downloads a recent version of Chromium (~170Mb Mac, ~282Mb Linux, ~280Mb Win) that is guaranteed to work with the library.
Debian
If you’re planning on running svg-to-img on Debian, you will need to manually install the following dependencies:
#!/bin/bash apt-get update apt-get install -yq gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 \ libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 \ libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 \ libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 \ ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget
Usage
Caution: svg-to-img uses async/await which is only supported in Node v7.6.0 or greater.
Example — converting a to :
const svgToImg = require("svg-to-img"); (async () => { const image = await svgToImg.from("").toPng(); console.log(image); })();
Example — converting a to and saving the image as example.jpeg:
const svgToImg = require("svg-to-img"); (async () => { await svgToImg.from("").toJpeg({ path "./example.jpeg" }); })();
Example — resizing a proportionally and converting it to :
const svgToImg = require("svg-to-img"); (async () => { const image = await svgToImg.from("").toWebp({ width 300 }); console.log(image); })();
Example — converting a to base64-encoded png:
const svgToImg = require("svg-to-img"); (async () => { const image = await svgToImg.from("").toPng({ encoding "base64" }); console.log(image); })();
Captions
Licensingedit
I, the copyright holder of this work, hereby publish it under the following license:
|
File history
Click on a date/time to view the file as it appeared at that time.
Date/Time | Thumbnail | Dimensions | User | Comment | |
---|---|---|---|---|---|
current | 01:02, 30 January 2020 | 1,895 × 886 (120 KB) | AlexBurn44 | ++ | |
02:16, 20 December 2019 | 1,920 × 1,080 (241 KB) | AlexBurn44 | — | ||
02:14, 20 December 2019 | 1,920 × 1,080 (241 KB) | AlexBurn44 | ++ | ||
02:11, 20 December 2019 | 1,920 × 1,080 (241 KB) | AlexBurn44 | ++ | ||
11:19, 23 October 2019 | 1,920 × 1,080 (241 KB) | AlexBurn44 | ++ | ||
11:18, 23 October 2019 | 1,920 × 1,080 (248 KB) | AlexBurn44 | ++ | ||
20:49, 8 July 2017 | 1,920 × 1,080 (238 KB) | The BurnPheonix | User created page with UploadWizard |
Metadata
This file contains additional information such as Exif metadata which may have been added by the digital camera, scanner, or software program used to create or digitize it. If the file has been modified from its original state, some details such as the timestamp may not fully reflect those of the original file. The timestamp is only as accurate as the clock in the camera, and it may be completely wrong.
Width | 1895 |
---|---|
Height | 886 |
API Documentation
- SVG markup to be converted.
- returns: a new Svg object.
The method returns a svg instance based on the given argument.
svg.to()
-
Options object which might have the following properties:
- Specify image type, can be either , or . Defaults to .
- The quality of the image, between 0-1. Defaults to . Not applicable to images.
- width of the output image. Defaults to the natural width of the SVG.
- height of the output image. Defaults to the natural height of the SVG.
-
An object which specifies clipping region of the output image. Should have the following fields:
- x-coordinate of top-left corner of clip area
- y-coordinate of top-left corner of clip area
- width of clipping area
- height of clipping area
- Specify encoding, can be either , , or . Returns a if this option is omitted.
- returns: > Promise which resolves to the output image.
svg.toPng()
- Optional options object that can have the same properties as the method except for the type property.
- returns: > Promise which resolves to the image.
This method is simply a shorthand for the method.
svg.toJpeg()
- Optional options object that can have the same properties as the method except for the type property.
- returns: > Promise which resolves to the image.
This method is simply a shorthand for the method.
svg.toWebp()
- Optional options object that can have the same properties as the method except for the type property.
- returns: > Promise which resolves to the image.
This method is simply a shorthand for the method.
Command line version: svgtopng
A command line version, svgtopng allows a little more flexibility, including the option to override several different values in the project.
Usage
Options
- -v: version number
- -h: this help page
- -x: export svg files in the specified projects
- -f: only export svg specified files or folders, for instance: -f svgfile1.svg svgfolder … The default: all svg files are processed
- -s: override the svg files’ width and height: -s 26:32
- -r: resolutions to export: -r 1,2,3 or 2,3, 1 …etc…
- -c: the number of the export command (as viewed in Svg to Png to use when exporting: -c3 … Defaults to the default command defined in Svg to Png
- -o: target folder where png files are exported to (it will be created if need be) … The default is to use the svg folder’s target, or the svg folder if no target specified
Examples
- Export all files in ‘myproject’ where ‘myproject’ is in the current directory
- Export all files in ‘myproject’
- Override the svg’s size
- Export all file in folder ‘my-svg-folder’
- Export the first file found in the project named ’rounded_0000.svg’ and the first file in the project named ‘biglion’ (note, it is possible to have the same filename in different folders
- Export all files in svgproject with 2x and 3x resolutions
- Export all files in svgproject using the export command 1 (that is, rsvg-convert) … By default, the export command defined as the default in Svg to Png is used
- Export all files in ‘my project’ to ‘~/Documents/TestSvgs’
You can use multiple options in any order (the project files must be specified before any options):
`svgtopng «my project» -s40:40 -r1 -c1 -f mysvg.svg -o ~/Documents/TestSvgs
Installing
The easiest way to install svgtopng is to:
- clone or download
- open project ‘Svg to Png.xcodeproj’
- select scheme ‘svgtopng’
- build project
- copy ‘svgtopng’ to /usr/local/bin (you can use Finder’s ‘Go > Go to Folder…’ menu option … the folder is hidden).
- edit ~/.bash_profile in a text editor, and add the line
You can use svgtopng in a shell script, from a Terminal session … or even add it as an export command in Svg to Png
Captions
Licensingedit
|
File history
Click on a date/time to view the file as it appeared at that time.
Date/Time | Thumbnail | Dimensions | User | Comment | |
---|---|---|---|---|---|
current | 17:56, 30 May 2016 | 363 × 512 (3 KB) | Elfi | User created page with UploadWizard |
File usage on other wikis
The following other wikis use this file:
- Usage on cs.wikipedia.org
- Usage on de.wikipedia.org
- Usage on en.wikipedia.org
- Cascading Style Sheets
- User:E nder1
- User:E nder1/CSS
- User:Hardikarathod/sandbox
- User:Prairie Astronomer
- User:Prairie Astronomer/sandbox
- User:Prairie Astronomer/Userboxes
- Usage on fa.wikipedia.org
- Usage on frr.wikipedia.org
- Usage on fr.wikipedia.org
- Feuilles de style en cascade
- Utilisateur:Cobalt~frwiki
- Utilisateur:SpeedyBoo
- Utilisateur:Medium69
- Wikipédia:Boîtes utilisateur logiciels
- Utilisateur:Mallow
- Utilisateur:Zsco
- Utilisateur:Roland Bouat
- Utilisateur:Greatman
- Utilisateur:Xhtml
- Utilisateur:Snarky
- Utilisateur:Ylanglais
- Utilisateur:AchilleT
- Utilisateur:Loscillo
- Utilisateur:Draezhenn
- Modèle:Utilisateur CSS
- Utilisateur:Zéfling
- Utilisateur:Geoffroy.aubry
- Catégorie:Utilisateur CSS
- Utilisateur:Jesmar
- Utilisateur:G.benattar
- Utilisateur:Kaepora Gaebora/Moi
- Utilisateur:Johnmichael
- Utilisateur:Bvs-aca
- Utilisateur:Linuks19
- Utilisateur:Niniryoku
- Utilisateur:Taranzef
- Utilisateur:Terr1enrun/présentation détaillée
- Utilisateur:Pierre-Marie Dhaussy
- Utilisateur:Groov3
- Utilisateur:The third man
- Utilisateur:Dr Brains/Contributions
- Utilisateur:Camikaze
- Utilisateur:Zezounet
- Utilisateur:AviaWiki/Boîtes
- Utilisateur:Mr CyrD
- Utilisateur:Mister parapluie
- Utilisateur:Kai Fr
- Utilisateur:Yann Dìnendal
View more global usage of this file.
Metadata
This file contains additional information such as Exif metadata which may have been added by the digital camera, scanner, or software program used to create or digitize it. If the file has been modified from its original state, some details such as the timestamp may not fully reflect those of the original file. The timestamp is only as accurate as the clock in the camera, and it may be completely wrong.
Width | 102.3716mm |
---|---|
Height | 144.49777mm |
File usage on other wikis
The following other wikis use this file:
- Usage on cs.wikipedia.org
- Usage on de.wikipedia.org
- Usage on en.wikipedia.org
- Cascading Style Sheets
- User:E nder1
- User:E nder1/CSS
- User:Hardikarathod/sandbox
- User:Prairie Astronomer
- User:Prairie Astronomer/sandbox
- User:Prairie Astronomer/Userboxes
- Usage on fa.wikipedia.org
- Usage on frr.wikipedia.org
- Usage on fr.wikipedia.org
- Feuilles de style en cascade
- Utilisateur:Cobalt~frwiki
- Utilisateur:SpeedyBoo
- Utilisateur:Medium69
- Wikipédia:Boîtes utilisateur logiciels
- Utilisateur:Mallow
- Utilisateur:Zsco
- Utilisateur:Roland Bouat
- Utilisateur:Greatman
- Utilisateur:Xhtml
- Utilisateur:Snarky
- Utilisateur:Ylanglais
- Utilisateur:AchilleT
- Utilisateur:Loscillo
- Utilisateur:Draezhenn
- Modèle:Utilisateur CSS
- Utilisateur:Zéfling
- Utilisateur:Geoffroy.aubry
- Catégorie:Utilisateur CSS
- Utilisateur:Jesmar
- Utilisateur:G.benattar
- Utilisateur:Kaepora Gaebora/Moi
- Utilisateur:Johnmichael
- Utilisateur:Bvs-aca
- Utilisateur:Linuks19
- Utilisateur:Niniryoku
- Utilisateur:Taranzef
- Utilisateur:Terr1enrun/présentation détaillée
- Utilisateur:Pierre-Marie Dhaussy
- Utilisateur:Groov3
- Utilisateur:The third man
- Utilisateur:Dr Brains/Contributions
- Utilisateur:Camikaze
- Utilisateur:Zezounet
- Utilisateur:AviaWiki/Boîtes
- Utilisateur:Mr CyrD
- Utilisateur:Mister parapluie
- Utilisateur:Kai Fr
- Utilisateur:Yann Dìnendal
View more global usage of this file.
File usage on other wikis
The following other wikis use this file:
- Usage on ab.wikipedia.org
- Usage on ace.wikipedia.org
- Usage on af.wikipedia.org
- Usage on af.wikibooks.org
- Usage on af.wikiquote.org
- Usage on af.wiktionary.org
- Usage on ak.wikipedia.org
- Usage on als.wikipedia.org
- MediaWiki:Uploadtext/de
- Benutzer Diskussion:Pill/Wiktionary
- Vorlage:Infobox Musikinstrument
- Benutzer:Philippe (WMF)
- Usage on als.wiktionary.org
- Usage on am.wikipedia.org
- Usage on am.wiktionary.org
- Usage on ang.wikipedia.org
- Usage on ang.wikibooks.org
- Usage on ang.wiktionary.org
- Usage on an.wikipedia.org
- Usage on an.wiktionary.org
- Usage on arc.wikipedia.org
- Usage on ar.wikipedia.org
- نقاش المستخدم:May05
- نقاش المستخدم:Abdussa
- نقاش المستخدم:Charlie
- نقاش المستخدم:Jak
- نقاش المستخدم:يونس
- نقاش المستخدم:Salhi5
- نقاش المستخدم:احمد محبي
- نقاش المستخدم:اسامة عبدالله الفرج
- نقاش المستخدم:Mora mami~arwiki
- نقاش المستخدم:Walid rady
- نقاش المستخدم:ONH
- نقاش المستخدم:هادي الكاتب
- نقاش المستخدم:Mazin alyasery
- نقاش المستخدم:Askress2009
- نقاش المستخدم:Kuwait~arwiki
- نقاش المستخدم:MARVEL~arwiki
- نقاش المستخدم:Polgy~arwiki
- نقاش المستخدم:Bo~arwiki
- نقاش المستخدم:JackSakali
- قالب:حقوق الصورة
- قالب:مصدر الصورة
- نقاش المستخدم:Black Scorpion~arwiki
- نقاش المستخدم:Hamied hashimi
- نقاش المستخدم:محمدالنداوي
- نقاش المستخدم:Amjadowais
- نقاش المستخدم:Lord Menias
- نقاش المستخدم:Saudilx
- نقاش المستخدم:Amjad027
- نقاش المستخدم:البحراني
- نقاش المستخدم:محمد2007
View more global usage of this file.
Заключение
Задавайте при необходимости альтернативный текст:
- Если альтернативного текста нет, прячьте SVG от вспомогательных технологий с помощью .
- Если альтернативный текст есть: 1. Добавьте название и/или описание в элемент SVG (или ссылку на них). 2. Используйте роли для добавления семантических значений (типа , ). 3. Прячьте графические и группирующие элементы, которые не следует зачитывать с помощью . 4. Прячьте текстовые элементы, которые не следует зачитывать с помощью и .
Для интерактивных SVG:
- Установите фокус с помощью и .
- Если ссылка не выполняет функции ссылки, добавьте соответствующую семантическую роль.
- Добавьте JavaScript для настройки фокуса окна.
- Задайте CSS для выделения .
Тестируйте с разными скринридерами и браузерами. Тестируйте в различных режимах контрастности. Тестируйте навигацию с клавиатуры.