Developer api

Содержание:

Saving to Amazon S3

Example S3 request

You can store a compressed image to S3 by using the URL that was
returned in the header. A JSON body with the bucket
information and a header have to be
included in the request that instructs the file to be stored on S3.

For example, to save the compressed image to a file named
in a bucked named :

Request options

You need to provide the following options in order to save an image on
Amazon S3:

Specify to store to Amazon S3.
The path at which you want to store the image including the bucket
name. The path must be supplied in the following format:
.

The following settings are optional:

(experimental)
You can add a header to control browser caching of the
stored image, with for example: . The full list
of directives can be found in the MDN
web docs.

The user that corresponds to your AWS access key ID must have the
and permissions on the paths of the objects you
intend to create.

Preserving metadata

You can request that specific metadata is copied from the uploaded image
to the compressed version. Preserving information, the GPS
and the date are currently supported. Preserving
metadata adds to the compressed file size, so you should only preserve
metadata that is important to keep.

Preserving metadata will not count as an extra compression. However, in
the background the image will be created again with the additional
metadata.

To preserve specific metadata, call the method on an image
source:

You can provide the following options to preserve specific metadata. No
metadata will be added if the requested metadata is not present in the
uploaded image.

Preserves any copyright information. This includes the EXIF copyright
tag (JPEG), the XMP rights tag (PNG) as well as a Photoshop copyright
flag or URL. Uses up to 90 additional bytes, plus the length of the
copyright data.
Preserves any creation date or time. This is the moment the image or
photo was originally created. This includes the EXIF original date time
tag (JPEG) or the XMP creation time (PNG). Uses around 70 additional bytes.
(JPEG only)
Preserves any GPS location data that describes where the image or photo
was taken. This includes the EXIF GPS latitude and GPS longitude tags
(JPEG). Uses around 130 additional bytes.

Saving to Google Cloud Storage

Before you can store an image in GCS you will need to generate an access
token with a service account.

We still need to create a piece of example code for this language
that generates an access code. In case you have a working example
ready, please share your code!

Once you have generated the access token you can then save the optimised
image directly to GCS by calling the method on an image source:

You need to provide the following options in order to save an image on
Google Cloud Storage:

Specify to store to Google Cloud Storage.
The access token for authenticating to Google’s Cloud Platform. Find out
how to generate these tokens with the example above.
The path at which you want to store the image including the bucket
name. The path must be supplied in the following format:
.

The following settings are optional:

(experimental)
You can add a header to control browser caching of the
stored image, with for example: . The full list
of directives can be found in the MDN
web docs.

Description

Make your website faster by optimizing your JPEG, PNG, and WebP images. This plugin automatically optimizes all your images by integrating with the popular image compression services TinyJPG and TinyPNG.

Features

  • Automatically optimize new images on upload.
  • Advanced background optimization to speed up your workflow.
  • Optimize individual images already in your media library.
  • Easy bulk optimization of your existing media library.
  • Automatically resize huge image uploads by setting a maximum width and/or height for more reasonable browser display.
  • Display JPEG images more quickly with progressive JPEG encoding.
  • Chose to preserve copyright metadata, creation date and GPS location in your original images.
  • Supports compression of animated PNG.
  • Select which thumbnail sizes of an image may be optimized.
  • Multisite support with a single API key.
  • WPML compatible.
  • WooCommerce compatible (see below).
  • WP Retina 2x compatible.
  • See your usage on the settings page and during bulk optimization.
  • Color profiles are automatically translated to standard RGB color.
  • Convert CMYK to RGB to save more space and add compatibility.
  • Dashboard widget with your total savings.
  • Optimize and resize uploads with the WordPress mobile app.
  • No file size limits.

How does it work?

After you upload an image to your WordPress site, each resized image is uploaded to the TinyJPG or TinyPNG service. Your image is analyzed to apply the best possible optimization. Based on the content of your image an optimal strategy is chosen. The result is sent back to your WordPress site and will replace the original image with one smaller in size. On average JPEG images are compressed by 40-60% and PNG images by 50-80% without visible loss in quality. Your website will load faster for your visitors, and you’ll save storage space and bandwidth!

Getting started

Install this plugin and follow the instructions to set up your account. With a regular WordPress installation you can optimize roughly 100 images each month for free. The exact total depends on the number of thumbnail sizes that are in use in your WordPress installation. You can change which of the generated thumbnail sizes should be optimized on the Settings > TinyPNG – JPEG, PNG & WebP image compression page. Once installed you can also switch to a paid account which removes the limits and allows you to optimize as many images as you like.

Optimizing all your images

You can bulk optimize your existing JPEG, PNG, and WebP images all at once by going to Media > Bulk Optimization. Clicking on the big button will start optimizing all unoptimized images in your media library.

Multisite support

The plugin is fully multisite compatible and you can set the API key for all sites by defining the key in your wp-config.php file. View the installation instructions for more information.

WooCommerce compatibility

This plugin is fully compatible with WooCommerce. However, we have discovered that WooCommerce may be trying to regenerate image attachment metadata over and over again on each page visit. If you are using WooCommerce please follow the tips from the support section. This may make your WooCommerce shop even faster than it was before.

Не грузите полный размер

Нет смысла загружать на сайт картинку полного размера, чтобы потом её уменьшать. Так вы уменьшаете её только визуально, а вес остаётся огромным. Гораздо правильней будет подготовить картинку с нужным размером у себя на компьютере и только потом загрузить её на сайт.

Изображение должно иметь такой размер, с каким оно будет выводиться на странице. Если вам в статье нужна фотография размером 200х200 пикселей, то вариант загрузить её на сайт размером 2000х2000 пикселей и просто уменьшить — не самый оптимальный. Лучше сразу грузите её на сервер размером 200х200 пикселей.

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

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

Я захожу на страницу статьи, кликаю по тексту правой кнопкой мыши и выбираю «Исследовать элемент». У пользователей MacOS этот пункт меню называется «Показать программный код страницы». Теперь у нас появляется вот такая вставка с кодом:

Чтобы узнать параметры определённого элемента на сайте, мы должны выбрать вот этот инструмент выделения в левом углу страницы.

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

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

DevelopmentBack to top

  • C# wrapper for the Tinify API. You can also pass along credentials and info to upload the compressed file directly to Amazon S3.

  • CLI client for images compressing using TinyPNG API. Supports multi-threading, distributed as one binary file, and can be executed from docker-image.

  • TinyPNG CLI that uses the API to compress images using the command line interface. Supports compressing and resizing individual files as well as (multiple) folders.

  • This is a .NET wrapper which supports .NET Core and full .NET Framework. Non-blocking async turtles all the way down with Byte[], Stream and File API’s available.

  • Made it specially for Google Display Ads, you can preview, compress, and download multiple banners in just one place.

  • Helps UX designers and developers to compress multiple images in just one click.

  • GitHub Action to compress and resize images with the Tinify API.

  • Golang client for the Tinify API, used for TinyPNG and TinyJPG. Tinify compresses or resize your images intelligently.

  • Gulp plugin to compress PNG and JPEG images using TinyPNG API.

  • Tinify API support for the Laravel PHP framework.

  • Provides CmdLets to tinify images using PowerShell Desktop or Core in different flavours like image in-place updates or bulk updates with resizing.

  • Python module and command line tool to shrink PNG files. Now also works with JPEG files.

  • A simple script in Python for Batch compress images.

  • R package to compress PNG/JPG file sizes from within R scripts/Rmarkdown documents.

  • Rust Crate to compress PNG/JPG images with the Tinify API.

  • A shell script to compress a batch of images using the tinify API.

  • TinyPNG For Unity brings the memory savings of TinyPNG to the Unity Editor. Easily compress .png and .jpg textures and significantly reduce image size.

  • Facade of Tinify API for Yii2 Framework. This extension allows you to resize and compress images without loss of quality.

  • Yii2 Client libraryBy BechTech

    Yii2 integration to optimize PNG and JPEG images without loosing quality. You can also resize images during the image compression process.

Preserving metadata

You can request that specific metadata is copied from the uploaded image
to the compressed version. Preserving information, the GPS
and the date are currently supported. Preserving
metadata adds to the compressed file size, so you should only preserve
metadata that is important to keep.

Preserving metadata will not count as an extra compression. However, in
the background the image will be created again with the additional
metadata.

To preserve specific metadata, call the method on an image
source:

You can provide the following options to preserve specific metadata. No
metadata will be added if the requested metadata is not present in the
uploaded image.

Preserves any copyright information. This includes the EXIF copyright
tag (JPEG), the XMP rights tag (PNG) as well as a Photoshop copyright
flag or URL. Uses up to 90 additional bytes, plus the length of the
copyright data.
Preserves any creation date or time. This is the moment the image or
photo was originally created. This includes the EXIF original date time
tag (JPEG) or the XMP creation time (PNG). Uses around 70 additional bytes.
(JPEG only)
Preserves any GPS location data that describes where the image or photo
was taken. This includes the EXIF GPS latitude and GPS longitude tags
(JPEG). Uses around 130 additional bytes.

DesktopBack to top

  • Comprehensive blog post with code example describing how to use Automator on macOS to compress images on desktop without using your browser.

  • The Tiny Image Processor is a Desktop App, allowing you to (batch) resize images and use your API key to up and download images from the TinyPNG servers.

  • iOS 12 Shortcuts script to compress (and resize) images with TinyPNG or TinyJPG on your iPhone or iPad. The script by default saves to iCloud, but it can also be modified easily to save to the camera roll for example.

  • An easy to use plugin for various JetBrains IDEs. Optimize any image directly from your IDE without the need to open your browser or manually download the image to save it locally.

  • An easy to use macOS GUI to compress your images without the need to open your browser or manually download the images. All you need to do is drag and drop.

  • Bamboo is a GUI to use your API key to compress PNG and JPG images on your computer. It works by uploading your image to TinyPNG and then downloading the compressed output for you.

  • A simple and easy to use MacOS GUI to compress your images . Support concurrent processing, colorizing, retry on failure or reveal in finder. All you need to do is open directory or images and press start .

  • tinyPNG.AppBy BetweenElements

    This app provides a GUI front end for TinyPNG for your local computer so you can optimize images without opening up a browser. Also includes option to overwrite your original images.

Как сжать файл PNG в RIOT

RIOT (Radical Image Optimization Tool) — бесплатное приложение для оптимизации изображений. В программе поддерживаются графические форматы: «PNG», «JPEG», «GIF».

Пройдите следующие шаги:

  1. Перетащите файл в окно программы RIOT или используйте кнопку «Open…» для добавления изображения.

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

  1. Нажмите на кнопку «PNG» для перехода к настройкам этого формата.
  2. В поле «Color reduction» (Уменьшение цвета) выберите подходящую опцию:
  • True Color — истинный цвет.
  • Optimal 256 Colors Palette — Оптимальная палитра из 256 цветов.
  • Optimal 128 Colors Palette — Оптимальная палитра из 128 цветов.
  • Optimal 16 Colors Palette — Оптимальная палитра из 16 цветов.
  • Dithered Monochrome — Смешанный монохромный.

В процессе выбора подходящих параметров смотрите на внешний вид оптимизированного изображения и на его итоговый размер.

  1. В поле «Compression» (Сжатие) укажите степень сжатия изображения:
  • minimum (fastest) — минимум (самый быстрый);
  • low — низкий;
  • medium (default) — средний (по умолчанию);
  • high — высокий;
  • maximum (very slow) — максимум (очень медленно).

Во вкладке «Image adjustments» вы можете изменить уровни яркости, контрастности и гаммы.

  1. Нажмите на кнопку «Save», чтобы сохранить сжатое изображение в формате PNG на компьютер.

Как уменьшить вес фотографии JPEG в RIOT

RIOT (Radical Image Optimization Tool) — бесплатная программа, предназначенная для оптимизации изображений некоторых графических форматов. Приложение поддерживает сохранение обработанной картинки в форматах «JPEG», «PNG», «GIF».

Откройте изображение в программе RIOT. Для этого используйте кнопку «Open» или просто перетащите фото в окно приложения.

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

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

Передвигая ползунок по шкале «Quality:», вы изменяете качество оригинальной фотографии до необходимого состояния. Рядом со шкалой отображается процент сжатия.  В процессе установки процента сжатия ориентируйтесь на качество оптимизированного изображения.

В большинстве случаев, этого будет достаточно для получения оптимизированного изображения с подходящими параметрами.

Пользователь может изменить параметры RIOT, заданные по умолчанию. В опции «Chroma subsampling:» можно выбрать режим сжатия. В параметре «Encoding» выбирается режим кодирования «Standard optimized» или «Progressive».

В нижней части окна программы находятся вкладки «Metadata», откуда можно удалить метаданные изображения, и «Image adjustments», в которой выполняется регулировка яркости, контрастности и гаммы.

Имейте, в виду, что все эти изменения оказывают влияние на итоговый размер изображения.

После завершения всех настроек, в окне программы RIOT нажмите на кнопку «Save» для сохранения уменьшенного изображения на свой компьютер.

Error handling

The Tinify API uses HTTP status codes to indicate success or failure. Any
HTTP errors are converted into exceptions, which are thrown by the client
library.

There are four distinct types of errors. The exception message will contain
a more detailed description of the error condition.

There was a problem with your API key or with your API account. Your
request could not be authorized. If your compression limit is reached,
you can wait until the next calendar month or upgrade your subscription. After verifying your
API key and your account status, you can retry the request.
The request could not be completed because of a problem with the
submitted data. The exception message will contain more information.
You should not retry the request.
The request could not be completed because of a temporary problem with
the Tinify API. It is safe to retry the request after a few minutes.
If you see this error repeatedly for a longer period of time, please
contact us.
The request could not be sent because there was an issue connecting to
the Tinify API. You should verify your network connection. It is safe to
retry the request.

You can handle each type of error separately:

If you are writing code that uses an API key configured by your users, you
may want to validate the API key before attempting to compress images.
The validation makes a dummy request to check the network connection and
verify the API key. An error is thrown if the dummy request fails.

Saving to Amazon S3

To save an image to S3, call the method on an image source:

You need to provide the following options in order to save an image on
Amazon S3:

Specify to store to Amazon S3.
The path at which you want to store the image including the bucket
name. The path must be supplied in the following format:
.

The following settings are optional:

(experimental)
You can add a header to control browser caching of the
stored image, with for example: . The full list
of directives can be found in the MDN
web docs.

The user that corresponds to your AWS access key ID must have the
and permissions on the paths of the objects you
intend to create.

Error handling

The Tinify API uses HTTP status codes to indicate success or failure. Any
HTTP errors are converted into exceptions, which are thrown by the client
library.

There are four distinct types of errors. The exception message will contain
a more detailed description of the error condition.

There was a problem with your API key or with your API account. Your
request could not be authorized. If your compression limit is reached,
you can wait until the next calendar month or upgrade your subscription. After verifying your
API key and your account status, you can retry the request.
The request could not be completed because of a problem with the
submitted data. The exception message will contain more information.
You should not retry the request.
The request could not be completed because of a temporary problem with
the Tinify API. It is safe to retry the request after a few minutes.
If you see this error repeatedly for a longer period of time, please
contact us.
The request could not be sent because there was an issue connecting to
the Tinify API. You should verify your network connection. It is safe to
retry the request.

You can handle each type of error separately:

If you are writing code that uses an API key configured by your users, you
may want to validate the API key before attempting to compress images.
The validation makes a dummy request to check the network connection and
verify the API key. An error is thrown if the dummy request fails.

Сжатие фото в JPG

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

Так что самое важное при сжатие JPG — это правильный баланс между большим количеством настроек и вариантов, поэтому в каждом онлайн-сервисе он обычно свой, что и дает возможность сравнить их между собой и выбрать тот, в котором оптимальное сочетание уменьшения размера JPG и сохранения его качества, чтобы фотка не превращалась в размытое пятно с многочисленными артефактами. Я проанализировал несколько наиболее популярных сервисов по сжатию JPG и вот к каким результатами пришел

Я проанализировал несколько наиболее популярных сервисов по сжатию JPG и вот к каким результатами пришел.

Затем последовательно сжимал в разных сервисах и оценивал размер и качество картинки (субъективно, конечно). Я не ставил цель провести какой-то глобальный эксперимент, просто поделился конкретными фактами.

Оригинальная картинка JPG — 865 Кб(исходник)

После сжатия в JPG — 92 Кб(минимальные потери качества)

После сжатия в WEBP — 89 Кб(без потери качества)

Более подробные результаты со сжатию JPG в таблице:

Номер Ссылка на сервис по сжатию фото онлайн Фото Размер, Кб Качество картинки после сжатия от 1 до 10
1 https://imagify.io/ сжатый jpg 64 2
2 https://www.websiteplanet.com/ru/webtools/imagecompressor/ сжатый jpg 89 1
3 https://www.iloveimg.com/ru сжатый jpg 92 7
4 https://tinypng.com/ сжатый jpg 105 6
5 https://www.hipdf.com/ru/image-compressor сжатый jpg 128 5
6 https://compressor.io/compress сжатый jpg 133 3
7 https://imagecompressor.com/ru/ сжатый jpg 148 9
8 https://compressjpeg.com/ru/ сжатый jpg 171 8
9 https://hnet.com/compress-jpeg/ сжатый jpg 179 8
Исходник в Jpeg исходник jpg 865 10
Если всё же использовать формат Webp через https://www.online-convert.com/ru сжатый webp 89 10

Наилучшее качество при максимальном сжатии JPG — https://www.iloveimg.com/ru
Лидер если нужно сжать фото с небольшими потерями качества.

Наилучшее сжатие JPG без потери качества — https://imagecompressor.com/
Лидер если нужно сжать фото без потери качества.

Я традиционно уже несколько лет пользовался привычным tinypng.com если мне нужно был быстро сжать несколько файлов, но теперь, пожалуй, попробую iloveimg.com, реально качество чуть повыше, а размер при этом поменьше.

А что если сжать картинку из JPG в Webp?

Ну и не мог пройти стороной набирающий популярность формат Webp — он оставил JPG далеко позади, потому что в нем я смог получить отличное фото, практически без всяких потерь качества (я не смог отличить его от оригинала) и при минимальном размере — в 10 (!) раз меньше несжатого JPG.

Resizing images

Use the API to create resized versions of your uploaded images. By letting
the API handle resizing you avoid having to write such code yourself and
you will only have to upload your image once. The resized images will be
optimally compressed with a nice and crisp appearance.

You can also take advantage of intelligent cropping to create thumbnails
that focus on the most visually important areas of your image.

Resizing counts as one additional compression. For example, if you upload
a single image and retrieve the optimized version plus 2 resized versions
this will count as 3 compressions in total.

To resize an image, call the method on an image source:

The describes the way your image will be resized. The following
methods are available:

Scales the image down proportionally. You must provide either a target
or a target , but not both. The scaled image will have
exactly the provided width or height.

Scales the image down proportionally so that it fits within the given
dimensions. You must provide both a and a . The scaled
image will not exceed either of these dimensions.

Scales the image proportionally and crops it if necessary so that
the result has exactly the given dimensions. You must provide both a
and a . Which parts of the image are cropped away is
determined automatically. An intelligent algorithm determines the
most important areas of your image.

A more advanced implementation of cover that also detects cut out
images with plain backgrounds. The image is scaled down to the
and you provide. If an image is detected with a
free standing object it will add more background space where
necessary or crop the unimportant parts. This feature is new and
we’d love to hear your feedback!

If the target dimensions are larger than the original dimensions, the image
will not be scaled up. Scaling up is prevented in order to protect the
quality of your images.

Saving to Google Cloud Storage

Before you can store an image in GCS you will need to generate an access
token with a service account.

We still need to create a piece of example code for this language
that generates an access code. In case you have a working example
ready, please share your code!

Once you have generated the access token you can then save the optimised
image directly to GCS by calling the method on an image source:

You need to provide the following options in order to save an image on
Google Cloud Storage:

Specify to store to Google Cloud Storage.
The access token for authenticating to Google’s Cloud Platform. Find out
how to generate these tokens with the example above.
The path at which you want to store the image including the bucket
name. The path must be supplied in the following format:
.

The following settings are optional:

(experimental)
You can add a header to control browser caching of the
stored image, with for example: . The full list
of directives can be found in the MDN
web docs.
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *