Apple png

Популярные статьи

  • 131.5K
  • 8 мин.

Яндекс.Вордстат: инструкция по применению
Яндекс.Вордстат – очень полезный ресурс для подбора ключевых запросов. С его помощью можно разработать семантическое ядро для сайта, подобрать анкоры для ссылок, спрогнозировать трафик на сайт и подготовить рекламную кампанию в Яндекс.Директ. В статье мы в мельчайших подробностях рассмотрим, что из себя представляет сервис и какие возможности дает.

  • 22 июля 2019
  • Продвижение

  • 61.3K
  • 10 мин.

SEO-анализ сайта самостоятельно: проверка оптимизации сайта
SEO-аудит сайта своими силами: расскажем и покажем в примерах, как провести его, чем воспользоваться и на какие параметры обращать внимание

  • 11 мая 2018
  • Продвижение

  • 17K
  • 17 мин.

План продвижения: как вывести свой бизнес в сеть и не запутаться?
С – Стратег! Составляем план по захвату мира продвижению своего бизнеса в сети.

  • 14 марта 2018
  • Продвижение

  • 31.1K
  • 3 мин.

Что такое карта релевантности и как составить ее правильно
Продвижение сайта по всем правилам начинается с составления карты релевантности – основного проектного документа. Этот документ составляется перед началом всех работ. Включает в себя слова из разработанного семантического ядра с указанием разной частотности, теги title и description, заголовки H1. О том, как правильно составить карту релевантности, читайте в нашей статье.

  • 18 апреля 2018
  • Продвижение

Как сгенерировать apple-touch-icon

Мобильные устройства могут иметь разные размеры экранов, а значит и сами иконки могут быть разных размеров. Вот например тут в ряду «Web clip icon (recommended for web apps and websites)» можно посмотреть какие иконки нужны для ios-устройств:

developer.apple.com/library/ios/documentation/userexperience/conceptual/mobilehig/IconMatrix.html

Я попытался выяснить какие именно размеры иконок стоит сгенерировать, но увидел что мнения различных блогеров слишком сильно разбегаются. Потому проанализировал логи и остановился на размерах 57×57, 76×76, 114х114, 120×120, 152×152. Если же в логах замечу что будут запрашиваться еще какие-то разрешения, то и для них создам иконку.

Для генерации иконок можно использовать один из множества сервисов «apple-touch-icon generator». Мне понравился вот этот: gieson.com/Library/projects/utilities/icon_slayer :

  • Находим подходящую иконку в хорошем качестве
  • Загружаем на сайт через кнопку Load Image
  • Указываем эффекты (градиент, блики)
  • Указываем (по желанию) дополнительные разрешения: ставим галочку возле custom и через пробел печатаем необходимые разрешения
  • Жмем кнопку Export Icons

На моем примере у меня имена файлов должны быть следующие:

  • apple-touch-icon-152×152-precomposed.png
  • apple-touch-icon-152×152.png
  • apple-touch-icon-120×120-precomposed.png
  • apple-touch-icon-120×120.png
  • apple-touch-icon-76×76-precomposed.png
  • apple-touch-icon-76×76.png
  • apple-touch-icon-precomposed.png
  • apple-touch-icon.png

Чаще всего рекомендуют  под именами apple-touch-icon-precomposed.png и apple-touch-icon.png хранить иконки с разрешением 57×57 пикселей.

API document

Documentation comment is written in KDoc.

Sample code

val extractor = TouchIconExtractor()                    // initialize
extractor.userAgent = "user agent string"               // option: set User-Agent
extractor.headers = mapOf("Cookie" to "hoge=fuga")      // option: set additional HTTP header
extractor.downloadLimit = 10_000                        // option: set download limit (default 64kB).
                                                        // 
//...
GlobalScope.launch(Dispatchers.Main) {
    val job = async(Dispatchers.IO) {
        extractor.fromPage(siteUrl, true)               // Do not call from the Main thread
    }
    //...
}

If in RxJava

//...
Single.fromCallable { extractor.fromPage(url, true) }   // Do not call from the Main thread
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe({
            //...
        }, {})

By default, this use HttpUrlConnection for HTTP access.
If you want to use OkHttp, use touchicon-http-okhttp module.

val extractor = TouchIconExtractor(
    httpClient = OkHttpAdapterFactory.create(OkHttpClient())
)

And, this use a simple in-house parser for HTML parsing.
If you want to use Jsoup, use touchicon-html-jsoup module.

val extractor = TouchIconExtractor(
    htmlParser = JsoupHtmlParserAdapterFactory.create()
)

HTTP Session

You may want to use communication in the same session as other communication.
You need to use the same cookie in WebView and HTTP session of this library.
For example, to use the same session as WebView in an Android application,

For the default HTTP client using HttpUrlConnection, implement CookieHanlder.

object WebViewCookieHandler  CookieHandler {
    private val cookieManager = CookieManager.getInstance()

    override fun saveCookie(url String, value String) {
        cookieManager.setCookie(url, value)
    }

    override fun loadCookie(url String) String? = cookieManager.getCookie(url)
}
TouchIconExtractor(
    httpClient = SimpleHttpClientAdapterFactory.create(WebViewCookieHandler)
)

For OkHttp, set CookieJar in OkHttpClient as you know.

object WebViewCookieJar  CookieJar {
    private val cookieManager = CookieManager.getInstance()

    override fun saveFromResponse(url HttpUrl, cookies ListCookie>) {
        val urlString = url.toString()
        cookies.forEach {
            cookieManager.setCookie(urlString, it.toString())
        }
    }

    override fun loadForRequest(url HttpUrl) ListCookie> =
        cookieManager.getCookie(url.toString()).let { cookie ->
            if (cookie.isNullOrEmpty()) {
                emptyList()
            } else {
                cookie.split(";")
                    .filter { it.isNotBlank() }
                    .mapNotNull { Cookie.parse(url, it) }
            }
        }
}
TouchIconExtractor(
    httpClient = OkHttpAdapterFactory.create(
        OkHttpClient.Builder()
            .cookieJar(WebViewCookieJar)
            .build()
    )
)

Техническая сторона

При создании Web Clips от устройства на сервер будут отправляться запросы в следующем порядке:

  1. В первую очередь к apple-touch-icon-precomposed.png.
  2. Если он не найден (от сервера получен ответ 404), то устройство сделает новый запрос к к apple-touch-icon.png.
  3. Если и этот способ не увенчается успехом, то устройство сделает скриншот верхней части вашего сайта, и он будет использоваться в качестве Web Clips.

Apple-touch-icon-precomposed.png и к apple-touch-icon.png, в чем различия?

Apple-touch-icon.png позволяет создать изображения, не запариваясь с фирменным оформлением Apple (закругленные рамки, блики). Ваше устройство все сделает самостоятельно.

С помощью apple-touch-icon-precomposed.png вы можете проявить некую творческую жилу и сделать все вручную, однако к этому формату есть свои требования – будьте внимательны.

Размеры для apple-touch-icon

В 2007 году было достаточно размера 57×57, так как было только одно устройство, на котором можно было сделать Web Clips.

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

Если устройство не найдет иконку нужного размера, то оно будет использовать самую близкую по большему размеру иконку.

Необязательно создавать иконки для всех разрешений экранов, достаточно будет сделать иконку размером 180×180, так как другие устройства могут уменьшить размер под свои требования.

Однако не стоит забывать о том, что не только устройства Apple используют Apple Touch Icon, поэтому можно объявить и другие размеры. Указывать размеры нужно с помощью атрибута – sizes.

Например:

Таблица размеров

Модель устройства Размер apple-touch-icon
IPhone – first generation, iPhone 2G, iPhone 3G, iPhone 3GS 57×57
iPhone 4, iPhone 4s, iPhone 5, iPhone 5c, iPhone 5s, iPhone se, iPhone 6, iPhone 6s, iPhone 7, iPhone8 120×120
iPhone X, iPhone 8 Plus, iPhone 7 Plus, iPhone 6s Plus, iPhone 6 Plus 180×180
iPad mini 76×76
iPad, iPad mini 2 152×152
iPad Pro 167×167

На сегодняшний день Apple рекомендует дает следующие по размерам иконок

Модель устройства Размер apple-touch-icon
iPhone 120×120 или 180×180
iPad Pro 167×167
iPad, iPad mini 152×152

Можно сделать вывод что устройства первого поколения, и ipad mini уже неактуальны, поэтому для них необязательно прописывать Apple-touch-icon соответствующего размера.

Что такое apple-touch-icon или Web Clips

Пользователи IOS и android могут на свой рабочий стол добавлять ярлыки-иконки для сайтов, они называются Web Clips. Файлы apple-touch-icon.png и apple-touch-icon-precomposed.png как раз и предназначены для этих иконок. То есть если вы у себя на телефоне захотите добавить на главный ярлык для моего сайта, то иконка этого ярлыка будет браться из этих файлов. Если же файла нет, то android возьмет иконку из файла favicon.ico, а IOS просто сделает иконку в виде скриншота видимой на данный момент части сайта.

На android устройствах такие ярлыки добавляются так: в браузере открываете нужный сайт — кнопка меню — Добавить закладку — в поле «Добавить в» выбираем «Главный экран» и жмем ОК. Попробуйте добавить мой сайт =)

У меня apple-touch-icon выглядит вот так:

А на телефоне вот так:

Android обращается к файлу apple-touch-icon только в тот, момент, когда Вы пытаетесь добавить сайт в закладки на главный экран. А вот apple-устройства пытаются обратиться при каждом посещении страницы. При отсутствии файлов apple-touch-icon.png это влечет генерацию 404-й ошибки. Если ваш сайт более-менее посещаем, то такая ошибка будет генерироваться достаточно часто, чтобы увидеть это в отчетах о нагрузке сервера. Ведь генерация 404-й страницы создает большую нагрузку для сервера хостинга, чем просто процесс отдачи изображения.

Какой выход? Конечно скопировать в нужное место заранее подготовленные иконки, тем более это будет плюс для Вашего сайта, такие иконки на рабочем столе мобильных устройств выглядят куда более привлекательней.

Command line usage

Don’t append a file extension to , it will be set automatically.

You have to set to one of the following values:

Value Output
Apple ICNS format, creates
Microsoft ICO format, creates (contained icons as BMP)
Microsoft ICO format, creates (contained icons as PNG)
Microsoft ICO format, creates (for Windows executables, see technical notes)
Create both ICNS and ICO format (ICO with BMP)
Create both ICNS and ICO format (ICO with PNG)
Create both ICNS and ICO format (ICO for Windows executables, see technical notes)

You can optionally set the interpolation algorithm to one of the following parameters:

Parameter Interpolation algorithm
Nearest Neighbor, fastest, mediocre to OK quality
Bilinear, fast, quality OK
Bicubic, slower, good to very good quality
Bezier, quite slow, high quality
Hermite, quite slow, high quality
Bicubic alternative, fast, good to very good quality (not thoroughly tested)

If no interpolation is set Bicubic () is used as the default.

With info messages are printed to the console during processing.

Example:

This will create the files and where contains icons in PNG format. During processing info messages will be printed to the console.

Technical notes

Apple ICNS

The module is one of the few which creates a complete list of icons from 16×16 up to 512×512@2 resolutions. Many other modules omit the 16×16 and 32×32 resolution or use compression modes which are not supported on older Apple operating systems. The generated ICNS files have been tested on OS X/macOS versions from 10.10 up to 10.14 on both retina and non-retina displays. It’s well possible that the generated files would also work on much older versions.

Microsoft ICO

png2icons creates ICO files with the sizes 16, 24, 32, 48, 64, 72, 96, 128 and 256 pixels (width and height). Icons can be stored as Windows bitmaps or PNGs, additionally there is a special variant where a mix of Windows bitmaps and PNGs is used. Storing as Windows bitmaps is best for compatibility reasons but the file size is quite large.

PNG in most cases produces much smaller file sizes but the generated ICO file can cause display problems in Windows version older than Windows 10. In general the files show up without problems in Windows Explorer at any size and at any resolution. This is true for Windows versions down to Windows 7 (older not tested), but the file properties dialog of older Windows versions may show a scrambled view of the embedded icon. Windows 10 does not have this problem.

If the ICO file should be used as the embedded icon in a Windows executable the command line switch (or , see below) can be used. If used, png2icons will write all icons smaller than 64×64 pixels in Windows bitmap format to the output file and the rest in PNG format. This helps to reduce the icon storage size in the executable and seems to work well in all Windows versions. It has been tested in Windows 7 up to Windows 10 at all kinds of screen resolutions (normal and HiDPI) and also at all different magnification levels.

System Icons (iOS 12 and Earlier)

In iOS 13 or later, prefer using SF Symbols to represent tasks and types of content in your app. If your app is running in iOS 12 or earlier, follow the guidance below.

The system provides built-in icons that represent common tasks and types of content in a variety of use cases.

In apps running iOS 12 and earlier, it’s a good idea to use these built-in icons as much as possible because they’re familiar to people.

Use system icons as intended. Every system-provided image has a specific, well-known meaning. To avoid confusing users, it’s essential that each image be used in accordance with its meaning and recommended usage.

Provide alternative text labels for icons. Alternative text labels aren’t visible onscreen, but they let VoiceOver audibly describe what’s onscreen, making navigation easier for people with visual impairments.

Design a custom icon if you can’t find a system-provided one that meets your needs. It’s better to design your own than to misuse a system-provided image. See Custom Icons.

Navigation Bar and Toolbar Icons

Use the following icons in navigation bars and toolbars. For developer guidance, see UIBarButtonSystemItem.

TIP You can use text instead of icons to represent items in a navigation bar or toolbar. For example, Calendar uses “Today,” “Calendars,” and “Inbox” in the toolbar. You can also use a fixed space element to provide padding between navigation and toolbar icons.

Icon Name Meaning API
Action (Share) Shows a modal view containing share extensions, action extensions, and tasks, such as Copy, Favorite, or Find, that are useful in the current context. action
Add Creates a new item. add
Bookmarks Shows app-specific bookmarks. bookmarks
Camera Takes a photo or video, or shows the Photo Library. camera
Cancel Cancel Closes the current view or ends edit mode without saving changes. cancel
Compose Opens a new view in edit mode. compose
Done Done Saves the state and closes the current view, or exits edit mode. done
Edit Edit Enters edit mode in the current context. edit
Fast Forward Fast-forwards through media playback or slides. fastForward
Organize Moves an item to a new destination, such as a folder. organize
Pause Pauses media playback or slides. Always store the current location when pausing, so playback can resume later. pause
Play Begins or resumes media playback or slides. play
Redo Redo Redoes the last action that was undone. redo
Refresh Refreshes content. Use this icon sparingly, as your app should refresh content automatically whenever possible. refresh
Reply Sends or routes an item to another person or location. reply
Rewind Moves backwards through media playback or slides. rewind
Save Save Saves the current state. save
Search Displays a search field. search
Stop Stops media playback or slides. stop
Trash Deletes the current or selected item. trash
Undo Undo Undoes the last action. undo

Tab Bar Icons

Use the following icons in tab bars. For developer guidance, see UITabBarSystemItem.

Icon Name Meaning API
Bookmarks Shows app-specific bookmarks. bookmarks
Contacts Shows the person’s contacts. contacts
Downloads Shows active or recent downloads. downloads
Favorites Shows the person’s favorite items. favorites
Featured Shows content featured by the app. featured
History Shows recent actions or activity. history
More Shows additional tab bar items. more
Most Recent Shows content or items recently accessed within a specific period of time. mostRecent
Most Viewed Shows the most popular items. mostViewed
Search Enters a search mode. search
Top Rated Shows the highest-rated items. topRated

Home Screen Quick Action Icons

Use the following icons in home screen quick action menus. For developer guidance, see UIApplicationShortcutIconType.

Markup:

link rel="shortcut icon" href="./path/to/icons/favicon.png">

link rel="apple-touch-icon" href="./path/to/icons/apple-touch-icon-60x60.png" />
link rel="apple-touch-icon" sizes="120x120" href="./path/to/icons/apple-touch-icon-120x120.png" />
link rel="apple-touch-icon" sizes="152x152" href="./path/to/icons/apple-touch-icon-152x152.png" />
link rel="apple-touch-icon" sizes="167x167" href="./path/to/icons/apple-touch-icon-167x167.png" />
link rel="apple-touch-icon" sizes="180x180" href="./path/to/icons/apple-touch-icon-180x180.png" />
meta name="apple-mobile-web-app-title" content="App Title">
meta name="apple-mobile-web-app-capable" content="yes">
meta name="apple-mobile-web-app-status-bar-style" content="black">

link rel="manifest" href="./path/to/manifest.json">
meta name="theme-color" content="#009ad3">
/* Manifest.json– see Android Guidelines above for configuration options */
{
  "short_name" "App Title",
  "name" "A bit longer of an App Title",
  "start_url" "./path/to/index.html",
  "icons" [
    {
      "src" "./path/to/icons/pwa-icon-192x192.png",
      "sizes" "192x192",
      "type" "image/png"
    },
    {
      "src" "./path/to/icons/pwa-icon-256x256.png",
      "sizes" "256x256",
      "type" "image/png"
    },
    {
      "src" "./path/to/icons/pwa-icon-384x384.png",
      "sizes" "384x384",
      "type" "image/png"
    },
    {
      "src" "./path/to/icons/pwa-icon-512x512.png",
      "sizes" "512x512",
      "type" "image/png"
    }
  ],
  "background_color" "#f5f5f5",
  "theme_color" "#009ad3",
  "display" "standalone",
  "orientation" "portrait"
}

Image Size and Resolution

The coordinate system iOS uses to place content onscreen is based on measurements in points, which map to pixels in the display. A standard-resolution display has a 1:1 pixel density (or @1x), where one pixel is equal to one point. High-resolution displays have a higher pixel density, offering a scale factor of 2.0 or 3.0 (referred to as @2x and @3x). As a result, high-resolution displays demand images with more pixels.

For example, suppose you have a standard resolution (@1x) image that’s 100px × 100px. The @2x version of this image would be 200px × 200px, and the @3x version would be 300px × 300px.

Supply high-resolution images for all artwork in your app, for all devices your app supports. Depending on the device, you accomplish this by multiplying the number of pixels in each image by a specific scale factor.

Device Scale Factor
12.9″ iPad Pro @2x
11″ iPad Pro @2x
10.5″ iPad Pro @2x
9.7″ iPad @2x
7.9″ iPad mini 4 @2x
iPhone XS Max @3x
iPhone XS @3x
iPhone XR @2x
iPhone X @3x
iPhone 8 Plus @3x
iPhone 8 @2x
iPhone 7 Plus @3x
iPhone 7 @2x
iPhone 6s Plus @3x
iPhone 6s @2x
iPhone SE @2x

Designing High-Resolution Artwork

Use an 8px-by-8px grid. A grid keeps lines sharp and ensures that content is as crisp as possible at all sizes, requiring less retouching and sharpening. Snap the image boundaries to the grid to minimize half pixels and blurry details that can occur when scaling down.

Produce artwork in the appropriate format. In general, use de-interlaced PNG files for bitmap/raster artwork. PNG supports transparency and, because it’s lossless, compression artifacts don’t blur important details or alter colors. It’s a good choice for intricate artwork that requires effects like shading, textures, and highlights. Use JPEG for photos. Its compression algorithm usually produces smaller sizes than lossless formats and artifacts are harder to discern in photos. Photo-realistic app icons, however, look best as PNGs. Use PDF for glyphs and other flat, vector artwork that requires high-resolution scaling.

Use the 8-bit color palette for PNG graphics that don’t require full 24-bit color. Using an 8-bit color palette reduces file size without reducing image quality. This palette is not appropriate for photos.

Optimize JPEG files to find a balance between size and quality. Most JPEG files can be compressed without noticeable degradation of the resulting image. Even a small amount of compression can save significant disk space. Experiment with compression settings on each image to find the optimal value that yields an acceptable result.

The right answer was…

152×152. 180×180, thanks to iOS 8 (updated on September 26th, 2014).

Apple defines 4 icon sizes, from 60×60 up to 152×152. What the specifications forget to mention is that these sizes are for iOS 7. To support iOS 6 and prior, you need 4 other dimensions.

iPhone iPad
non-Retina Retina non-Retina Retina
iOS 6 and prior 57×57 114×114 72×72 144×144
iOS 7 60×60 120×120 76×76 152×152

The specifications do not explicitly define the size of the picture, but  . An iPad with a Retina screen running iOS 7 will use it as is, while the other devices will scale it as needed (unless they find a more suitable icon).

How many web sites follow the 152×152 recommendation? 33. A good 4%. Oh. Among them, Apple.com.

Nearly as many sites have a 60×60 icon, which is the other size you might pick after reading the Apple specs. Some others resolutions are more popular, like 114×114 (79 sites) and 144×144 (72 sites). But the winner is clearly 57×57 with 281 sites. This resolution is outdated, but it is still the reference. Google for “apple touch icon size”: at the time of writing, the first result is from StackOverflow and the first answer documents 57×57.

An with an iOS 6 size is the sign that it has not been updated for a while. Yet, it does not prove that the Apple touch icon won’t work on modern devices. Take Bing.com, one of the 57×57 supporters: it also defines . You shiny iPad will use this picture.

made with ChartBoot

This leaves us with 68% of with a resolution recommended (or used to be recommended) by Apple. And 32% of… something else.

API usage

The module exports four functions:

creates the Apple ICNS format, creates the Microsoft ICO format.

Parameters identical for both functions:

  • is a buffer containing the raw content of a PNG file, obtained, for example, with .

  • sets the algorithm to be used when scaling the input images for the various icon sizes. It can be one of the following constants:

    RESIZE_NEAREST_NEIGHBOR = ;
    RESIZE_BILINEAR = 1;
    RESIZE_BICUBIC = 2;
    RESIZE_BEZIER = 3;
    RESIZE_HERMITE = 4;
    RESIZE_BICUBIC2 = 5;
  • controls the reduction of colors in the compressed output if PNG is used for the icons . A value of retains all colors from (lossless), a value greater than reduces the colors to the given number (per color channel, so is the maximum value). This can lead to much smaller files. Please note: is ignored if is set to () but it is always used if is .

If the boolean parameter for is set to this function will use PNG for each icon in the created ICO file, otherwise Windows bitmaps will be used. Please note that PNG in ICO files may lead to problems in Windows versions older than Vista.

If the optional parameter for is set to png2icons will create a mix of PNG and BMP icons in the generated output. The icon sizes 16, 24, 32 and 48 will be in BMP format and all others in PNG format. This helps to reduce the ICO file size. Using BMP for the smaller icon sizes prevents display problems in the file properties dialog of Windows versions older than Windows 10. This parameter should be used, if an ICO file for embedding in Windows executables must be created (for example for Electron apps).

With you can supply your own logging function. The logging function () must accept the same parameters like , so you could use that in simple cases, e. g. . No logging function is set by default.

: png2icons tries to cache as much image data as possible to speed up processing. If, for example, the same input image is used to create multiple different output formats it reuses already scaled images. frees all internally cached image data .

The return value is in case of an error, otherwise a buffer which contains the binary data of the generated ICNS/ICO file is returned. You could use, for example, to save it as a file.

Example:

var png2icons = require("png2icons");
var fs = require("fs");

var input = fs.readFileSync("sample.png");

// Apple ICNS with bilinear interpolation and no color reduction.
// Log infos via console.log.
png2icons.setLogger(console.log);
var output = png2icons.createICNS(input, png2icons.BILINEAR, );
if (output) {
    fs.writeFileSync("icon.icns", output);
}

// Microsoft ICO using PNG icons with Bezier interpolation and
// reduction to 20 colors.
// Log infos via console.log (logging function already set before).
output = png2icons.createICO(input, png2icons.BEZIER, 20, true);
fs.writeFileSync("icon_png.ico", output);

// Microsoft ICO using BMP icons with Hermite interpolation,
// (numOfColors is ignored). Turn off any logging again.
png2icons.setLogger(null);
output = png2icons.createICO(input, png2icons.HERMITE, , false);
fs.writeFileSync("icon_bmp.ico", output);

// Microsoft ICO using PNG and BMP icons with alternative bicubic
// interpolation, (numOfColors applies!). Suitable for embedding
// the icon file in Windows executables. Logging is already off.
output = png2icons.createICO(input, png2icons.BICUBIC2, , false, true);
fs.writeFileSync("icon_winexe.ico", output);

Changelog

2.0.1

  • Fixed image caching bug which used the first given input forever on all subsequent API calls.
  • Added exported function .

2.0.0

  • Added sizes and to ICNS.
  • Added special ICO format for Windows executables.
  • Noticeably faster rescaling due to inlining interpolate functions.
  • Much faster ICNS generation due to caching of icon chunks with the same size.
  • Added much faster alternative bicubic rescaling (should work although not thoroughly tested).
  • Prevent color palette in small PNGs (caused scrambled display of small icons under some conditions).
  • Fixed Windows DIB creation for ICO (caused scrambled display of small icons under some conditions).
  • Fixed wrong offsets/sizes for PNGs in ICO.
  • Fixed non-quadratic images in ICNS.
  • Removed dependcy from pako.
  • Add missing TypeScript definition files.
  • Use ES2015 (TypeScript).

What does the hint check?

The hint checks if a single declaration exists in
the , and:

  • it has
  • the declared image is accessible (e.g.: doesn’t result in a ),
    a , and its size is
  • it does not include the attribute

Examples that trigger the hint

No was specified:

span class="hljs-meta-keyword">html>
html lang="en">
    head>
        meta charset="utf-8">
        title>exampletitle>
        ...

    head>
    body>...body>
html>

The is not specified in :

span class="hljs-meta-keyword">html>
html lang="en">
    head>
        meta charset="utf-8">
        title>exampletitle>
        ...

    head>
    body>
        link rel="apple-touch-icon" href="apple-touch-icon.png">
        ...
    body>
html>

The has a attribute different than
:

link rel="apple-touch-icon-precomposed" sizes="180x180" href="apple-touch-icon-precomposed.png">

The has a attribute:

link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">

Multiple s are specified:

link rel="apple-touch-icon" sizes="57x57" href="/static/images/touch-icons/apple-touch-icon-57x57.png">
link rel="apple-touch-icon" sizes="60x60" href="/static/images/touch-icons/apple-touch-icon-60x60.png">
link rel="apple-touch-icon" sizes="72x72" href="/static/images/touch-icons/apple-touch-icon-72x72.png">
link rel="apple-touch-icon" sizes="76x76" href="/static/images/touch-icons/apple-touch-icon-76x76.png">
link rel="apple-touch-icon" sizes="114x114" href="/static/images/touch-icons/apple-touch-icon-114x114.png">
link rel="apple-touch-icon" sizes="120x120" href="/static/images/touch-icons/apple-touch-icon-120x120.png">
link rel="apple-touch-icon" sizes="144x144" href="/static/images/touch-icons/apple-touch-icon-144x144.png">
link rel="apple-touch-icon" sizes="152x152" href="/static/images/touch-icons/apple-touch-icon-152x152.png">
link rel="apple-touch-icon" sizes="180x180" href="/static/images/touch-icons/apple-touch-icon-180x180.png">

The is not accessible:

link rel="apple-touch-icon" href="apple-touch-icon.png">

Response for :

HTTP/... 404 Not Found
...
HTTP/... 500 Internal Server Error
...

The is not a file:

link rel="apple-touch-icon" href="apple-touch-icon.png">
$ file apple-touch-icon.png

apple-touch-icon.png: JPEG image data, ...

The is not :

link rel="apple-touch-icon" href="apple-touch-icon.png">
$ file apple-touch-icon.png

apple-touch-icon.png: PNG image data, 180 x 180, ...

Examples that pass the hint

span class="hljs-meta-keyword">html>
html lang="en">
    head>
        meta charset="utf-8">
        title>exampletitle>
        ...
        link rel="apple-touch-icon" href="/apple-touch-icon.png">
        ...

    head>
    body>...body>
html>

Methodology

The picture is famous but not required to enable the Apple touch icon. There are actually four ways to display this icon:

  • HTML declaration. For example,
  • Dimension-specific pictures, such as
  • Precomposed touch icons (eg. )

As a consequence, when a web site as no or this picture is somewhat wrong, it may still support the Apple touch icon successfully. For example, by providing alternative pictures declared in the HTML code.

To collect data, some portions of the favicon checker were reused. The script parsed the Alexa top web sites listing and requested each site using an iPad Mini user agent to make sure it gets the mobile version of the site. Then, it tried to download and get its dimensions. All failures were ignored. For example, when the file is not present, some sites do not return a plain 404 error but an error page. The script failed at parsing such “picture”, yet this case was not distinguished from genuine corrupted pictures.

The 129×129 dimension, used by 49 sites, is a bit special. Apparently, it has been the dimension of the of Apple for a while, making it somehow “official”. Yet, I chose to consider it as non-official since there is apparently no reason for such resolution.

Oh, and in case you wonder, yes, I cleared my browser history at the end of this study. Thank you for reminding me.

Why is this important?

Since , Safari for iOS has supported a way for developers
to specify an image that will be used to represent the web site/app
on the home screen. The image is known as the touch icon.

Note: As of , Safari for iOS which provides a standard, cross-browser way of
defining, among other, the icons browsers can use in various contexts
(home screen, application menu, etc.). However, Safari ignores the icons
defined in the web app manifest and still uses the non-standard
.

Over time as Apple released different size displays for their devices,
the requirements for the size of the touch icon have changed quite a
bit:

  • – iPhone with @1x display and iPod Touch
  • – iPad and iPad mini with @1x display running iOS ≤ 6
  • – iPad and iPad mini with @1x display running iOS ≥ 7
  • – iPhone with @2x display running iOS ≤ 6
  • – iPhone with @2x and @3x display running iOS ≥ 7
  • – iPad and iPad mini with @2x display running iOS ≤ 6
  • – iPad and iPad mini with @2x display running iOS 7
  • – iPad and iPad mini with @2x display running iOS 8+

Declaring one PNG image, e.g.:

link rel="apple-touch-icon" href="apple-touch-icon.png">

in the of the page is enough, and including all the different
sizes is not recommended as:

  • It will increase the size of the pages with very little to no
    real benefit (most users will probably not add the site to their
    home screens).

  • Most sizes will probably never be used as iOS devices get upgraded
    quickly, so most iOS users will be on the latest 2 versions
    of iOS and using newer devices.

  • The image, if needed, will be automatically downscaled
    by Safari, and the result of the scaling is generally ok.

The only downside to using one icon is that some users will load
a larger image, while a much smaller file would have worked just
as well. But the chance of that happening decreases with every day
as users upgrade their devices and their iOS version.

Other notes:

  • Not declaring the touch icon in the page and having it in the
    root of the site is not recommended as Apple usually changes
    what is requested by default.

  • In older versions of Safari for iOS, the could be used to prevent iOS from adding different visual
    effects to the touch icon (i.e. rounded corners, drop shadow,
    reflective shine). Starting with iOS 7 no special effects are applied
    to touch icons, so there is no need to use the
    keyword anymore.

  • Safari for iOS ignored the attribute, so the order
    in which the icons were declared mattered. When using
    one image there is no need to use the attribute.

Specifying a Webpage Icon for Web Clip

You may want users to be able to add your web application or webpage link to the Home screen. These links, represented by an icon, are called Web Clips. Follow these simple steps to specify an icon to represent your web application or webpage on iOS.

  • To specify an icon for the entire website (every page on the website), place an icon file in PNG format in the root document folder called

  • To specify an icon for a single webpage or replace the website icon with a webpage-specific icon, add a link element to the webpage, as in:

    In the above example, replace with your icon filename.

  • To specify multiple icons for different device resolutions—for example, support both iPhone and iPad devices—add a attribute to each link element as follows:

    The icon that is the most appropriate size for the device is used. See the “Graphics” chapter of iOS Human Interface Guidelines for current icon sizes and recommendations.

If there is no icon that matches the recommended size for the device, the smallest icon larger than the recommended size is used. If there are no icons larger than the recommended size, the largest icon is used.

If no icons are specified using a link element, the website root directory is searched for icons with the prefix. For example, if the appropriate icon size for the device is 58 x 58, the system searches for filenames in the following order:

  1. apple-touch-icon-80×80.png

  2. apple-touch-icon.png

Conclusion

Among the pictures that follow the dimensions of Apple specifications, 85% of them stick to the old versions of iOS. Only 15% follow iOS 7, released 6 months ago. Apparently, webmasters are not in a hurry to update them.

made with ChartBoot

The overall results are positive, with only 32% of picture with undocumented dimensions. Even if these dimensions are sometimes surprising, most of them are processed correctly by iOS. Yet some sites should definitely update their icons.

made with ChartBoot

Maybe the most striking figure is the amount of different sizes encountered during this study: 60 different resolutions were found, from the popular 57×57 to the unique 110×110 of the NCAA. This number reveals how fragmented the information is. 57×57 is still broadly advertised. 114×114 has its fans. 129×129 was popular for a while…

When creating an Apple touch icon, you should use an up-to-date favicon generator (and now let’s see if auto-promotion is efficient). You probably don’t bother checking Apple specifications every so often. Fortunately, some people do it for you. To make sure your favicon stays relevant, you can follow us (, or ) to be notified when the generated pictures and code are updated.

Favicon update is still unpractical. You can expect more in the next few weeks… stay tuned!

Ссылка на основную публикацию