Developer api
Содержание:
- How does it work?
- Resizing Images
- Error handling
- Программы и офлайн сервисы для оптимизации картинок
- Resizing images
- Saving to Google Cloud Storage
- Базовая оптимизация изображений
- Preserving metadata
- DevelopmentBack to top
- Saving to Amazon S3
- SEO оптимизация изображений
- DesktopBack to top
- Changelog
- Как настроить сжатие png и jpg, jpeg на автомате
- Основные характеристики
- Saving to Google Cloud Storage
- Resizing images
- Main differences from gulp-tinypng-compress
- Resizing images
- Reviews
- Saving to Google Cloud Storage
- Preserving metadata
How does it work?
Excellent question! When you upload a PNG (Portable Network Graphics) file, similar colors in your image are combined. This technique is called “quantization”. By reducing the number of colors, 24-bit PNG files can be converted to much smaller 8-bit indexed color images. All unnecessary metadata is stripped too. The result: better PNG files with 100% support for transparency. Have your cake and eat it too!
In the above image the file size is reduced by more than 70%. I have excellent eyesight but can’t spot the difference either! Use the optimized image to save bandwidth and loading time and your website visitors will thank you.
Resizing Images
using var png = new TinyPngClient("yourSecretApiKey");
var compressImageTask = png.Compress("pathToFile or byte array or stream");
var resizedImageTask = compressImageTask.Resize(width, height);
await resizedImageTask.SaveImageToDisk("pathToSaveImage");
// altogether now....
await png.Compress("pathToFile")
.Resize(width, height)
.SaveImageToDisk("pathToSaveImage");
Resize Operations
There are certain combinations when specifying resize options which aren’t compatible with
TinyPNG. We also include strongly typed resize operations,
depending on the type of resize you want to do.
using var png = new TinyPngClient("yourSecretApiKey");
var compressTask = png.Compress("pathToFile or byte array or stream");
await compressTask.Resize(new ScaleWidthResizeOperation(width));
await compressTask.Resize(new ScaleHeightResizeOperation(height));
await compressTask.Resize(new FitResizeOperation(width, height));
await compressTask.Resize(new CoverResizeOperation(width, height));
The same , , and path API’s are available from the result of the method.
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.
Программы и офлайн сервисы для оптимизации картинок
Безусловно, иногда приходится работать вне зоны действия Интернета. Тогда нужно использовать офлайн программы для редактирования изображений.
PNGGauntlet. Программа, занимающая мало места на компьютере. С её помощью удаётся оптимизировать картинки в формате PNG. Кроме того, конвертируются графические файлы JPG, GIF, BMP, TIFF в PNG.

Ashampoo Photo Commander Free. Простая и бесплатная прога с доступом оптимизации и корректирования изображения. Всего за 1 минуту удастся создать красивый коллаж или календарь.

Photoshop. Инструмент, установленный на компьютерах многих пользователей. Позволяет уменьшить вес иллюстраций, установить нужный формат, изменить размер. Одним словом, в Фотошопе с картинкой можно делать практически всё.

Illustrator. Векторный графический редактор, разработанный Adobe Systems ещё в 1987 году. В этой программе можно создавать логотипы, значки, изменять цветовую палитру. Изображения остаются чёткими в любом масштабе, так как разработка осуществляется по векторному формату.

Sketch. Ещё один векторный редактор, но разработанный другой компанией — Bohemian Coding. Предоставляет пользователю целый набор инструментов для рисования. В плане оптимизации здесь удастся быстро уникализировать фото, создавая рамки, коллажи и эскизы.

Riot. Мощный инструмент для оптимизации размера картинок. Поддерживает большое количество форматов. Программа располагает кучей полезных опций: сжатие фото до заданного объёма, редактирование метаданных, коррекция цвета, изменение высоты и ширины иллюстрации и многое другое.

Paint.Net. Полноценный аналог MS Paint, который штатно встраивается во все компьютеры. В отличие от примитивного инструмента, в этом графическом редакторе от Microsoft удастся профессионально работать. Целиком бесплатная утилита, но требует установки Microsoft Net Framework 2.0.

OptiPNG. Компьютерная программа, позволяющая уменьшать файлы PNG и другие форматы путём компрессии. Фишка — именно эту прогу рекомендует инструментарий Google Page Speed.

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.
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.
Базовая оптимизация изображений
Тут подразумевается обрезка ненужных полей, уменьшение глубины цвета, удаление комментариев и сохранение изображения в подходящем формате. Для этого можете воспользоваться Adobe Photoshop, или, если у вас его нет, MS Paint или GIMP.
Даже элементарная обрезка изображения неплохо снизит его вес.
Как уменьшить изображение в MS Paint
Покажу на примере MS Paint, как уменьшить изображение до нужных размеров.
Возьмём для примера лого NGINX и его изображение nginx.png размером 2000×417 пикселей, которое нужно обрезать по ширине до 1024, т.к. это ширина вёрстки страницы, и делать больше нет смысла.
-
Открываем Paint (Пуск-Выполнить-Вводим «mspaint»)
-
Загружаем nginx.png, находим «Изменить размер», открывается окошко с процентами и пикселями, в нём переходим на пиксели и задаём нужный размер, в нашем случае вбиваем в ширину 1024
На выходе получаем картинку, которая прошла минимальную базовую оптимизацию. Пора переходить к сжатию её веса.
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.
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.
-
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.
-
CLI client for images compressing using TinyPNG API. Supports multi-threading, distributed as one binary file, and can be executed from docker-image.
-
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.
-
A simple script in Python for Batch compress images.
-
Python module and command line tool to shrink PNG files. Now also works with JPEG files.
-
R package to compress PNG/JPG file sizes from within R scripts/Rmarkdown documents.
-
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.
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.
SEO оптимизация изображений
После того, как вы оптимизировали размер и объем изображения и выбрали подходящий формат, назовите готовый файл так, чтобы было понятно, что изображено на картинке. Не называйте файл Untitled.jpeg, Без-названия.png или 01.webp.
Закачайте картинку на сайт и добавьте атрибуты Alt и Description. Эти теги говорят поисковым системам что изображено на картинках. Заполните как минимум поле Alt.
Добавьте атрибут Alt и Описание
Описания к картинкам индексируются поисковыми системами и вы можете получить больше переходов на свой сайт из раздела Картинки поисковых систем.
Трафик из раздела Картинки поисковых систем
Также эти теги помогают пользователям с нарушениями зрения, так как их программы чтения с экрана могут читать им теги Alt и Title.
Заключение
Оптимизировать изображения для публикации на сайте можно разными способами.
Фотошоп самый гибкий инструмент для уменьшения размера изображений, с помощью настроек вы можете выбрать приемлемый уровень оптимизации, но некоторое неудобство в том, что каждую картинку нужно оптимизировать вручную.
В этом способе вы можете оптимизировать изображения в Фотошопе и до-оптимизировать их на сайте с помощью плагина.
Хороший результат у плагинов TinyPNG и ShortPixel. EWWW Image Optimizer хороший плагин, но его сложнее настроить.
Оптимизированные картинки значительно ускоряют скорость сайта. Качество изображений немного уменьшится, но большинство ваших посетителей этого не заметят.
Еще одна вещь, которую вы можете сделать для ускорения загрузки страниц — подключить сайт к сети CDN. После подключения страницы сайта будут доставляться посетителю из ближайшего сервера.
Как подключить Вордпресс к CDN Cloudflare
- Где брать бесплатные картинки в хорошем качестве для публикации на сайте без нарушения авторских прав
- SEO для Вордпресс. Подробная инструкция
- 12 советов для SEO оптимизации Блога
Надеюсь, статья была полезна. Оставляйте комментарии.
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.
-
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.
-
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.
-
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.
-
macOS AppBy Hoc Tran
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 .
Changelog
3.2.1
- Fixed bug that caused the original version of images that started with a special character to not be compressed.
- Updated WordPress compatibility.
3.2.0
- Support for WP Retina 2x Pro.
- More capability checks for extra security.
- Less resource intensive AJAX requests.
- Fixed CSS issues from Analytify plugin.
- Removed legacy Enhanced Media Library compatibility.
3.1.0
- Remaining free compressions shown in settings page.
- Easier way to upgrade a free account.
- WPML and WPML Media compatibility in collaboration with the authors of WPML. Make sure to upgrade WPML to version 4.1.
- Added a notice to the Bulk Optimization page for free accounts with not enough available free compressions.
- Added a new hook after compression of an image useful for CDN cache flushing.
3.0.1
- Fixed bug that caused an error when registering a new account.
- No longer use create_function, which is deprecated in PHP 7.2. The plugin no longer supports PHP 5.2.
- Rephrased incompatible plugins notice to avoid confusion.
3.0.0
- Compress new images in the background to speed up your workflow.
- Turbo-charged Bulk Optimization page with simultaneous image compression.
- Improved memory usage for installations with extreme media libraries.
- Detection of incompatible plugins.
- Fallback to fopen whenever the curl_exec function is disabled.
- Additional notices for WP Offload S3 users.
- Several minor fixes and tweaks.
2.2.5
- Fixed bug in the Bulk Optimization page that sometimes caused it to stop.
- Fixed a problem that would prevent dashboard widget from loading.
- Tweaked styling of the dashboard widget for the latest version of WordPress.
- Fixed a warning in the media library when certain plugins are used.
2.2.4
- Fixed bug with drop-down menu in the Media Library.
- Compression limit notice now links directly to your API dashboard.
- Tweaked styling of the dashboard widget.
2.2.2
- Improved robustness in case an unexpected network error occurs.
- Fixed false positive warning with Sucuri scanner.
- Fixed compression issue for fopen users.
2.2.1
- Fixed an error that was introduced in v2.2.0 where all custom image sizes did not show up.
- Added support for image sizes with unspecified height or width.
2.1.0
- Compression of retina images generated by WP Retina 2x.
- Solved a bug which caused the API key to be cleared on the settings page.
- Fixed an error that occurred with some PHP 7 installations.
- Fixed an fopen error when preserving metadata.
2.0.2
- Faster Bulk Optimization page with reduced memory usage (thanks to @esmus).
- Fixed XML-RPC error (thanks @ironmanixs, @gingerdog, @quicoto and @isaumya).
2.0.0
- Completely new Bulk Optimization page.
- Better detection of image sizes with duplicate filenames.
- Simplified account activation and API key creation.
- Fix to the bottom drop-down menu in the Media Library.
- Use the latest PHP client library for connecting to TinyJPG and TinyPNG.
- Added fallback to fopen for older systems running PHP 5.2.
1.7.1
- Preserve GPS locations and creation dates in the original JPEG images.
- Option to preserve copyright information in your original PNG images.
- Improved detection of unsupported file types.
1.7.0
- Option to preserve copyright information in your original JPEG images.
- Added proxy support for cURL.
- Support for translate.wordpress.org plugin translations.
1.6.0
- Improved compression status in the Media Library with new details window.
- Show total compression savings on the Media Settings page.
- Moved Compress All Images from the Tools to the Media menu.
1.5.0
- Resize original images by specifying a maximum width and/or height.
- Support for the mobile WordPress app (thanks to David Goodwin).
1.4.0
- Indication of the number of images you can compress for free each month.
- Link to the Media Settings page from the plugin listing.
- Clarification that original images will be overwritten when compressed.
1.3.0
- Added option to bulk compress your whole media library in one go.
- Better indication of image sizes that have been compressed.
- Detection of image sizes modified after compression by other plugins.
1.2.0
- Show if you entered a valid API key.
- Display connection status and number of compressions this month.
- Show a notice to administrators when the free compression limit is reached.
- The plugin now works when php’s parse_ini_file is disabled on your host.
- Avoid warnings when no image thumbnail sizes have been selected.
1.1.0
- The API key can now be set with the TINY_API_KEY constant in wp-config.php. This will work for normal and multisite WordPress installations.
- Enable or disable compression of the original uploaded image.
- Improved display of original sizes and compressed sizes showing the total compression size in the Media Library list view.
Как настроить сжатие png и jpg, jpeg на автомате
Если вы дочитали до этого раздела, но всё ещё недовольны предложенными вариантами, предлагаю вам самим собрать портативный комбайн — сервис по сжатию картинок, фото, изображений, который будет работать как надо вам прямо на вашем рабочем столе.
Итак, для этого нам потребуется правильно собрать архитектуру папок. Допустим, у вас есть папка со своей иерархией вложенных в неё папок с PNG и JPG, которые вам нужно обработать.
Создаём папку , в неё закинем папку со всеми вложенными папками и файлами.
Открываем Far Manager, в нём открываем optimus, создаём там файл и записываем туда
@ECHO OFF CLS SetLocal EnableExtensions EnableDelayedExpansion set home_path=%~dp0 :: Название папки, в которой лежат необработанные изображения set folder=images echo Обработка *.JPG файлов через jpegtran :: Создаём папку, в которой будут храниться сжатые jpg. В нашем случае, это jpeg_images xcopy /y /t /c /i "%folder%" "jpg_%folder%" :: Для каждого .jpg проводим оптимизацию с помощью jpegtran. Выходной .jpg будет записан в jpeg_images for /r %folder% %%a in (*.jpg) do ( set fn=%%a& jpegtran -copy none -optimize -progressive -outfile %home_path%jpg_!fn:%~dp0=! %home_path%!fn:%~dp0=! ) echo Обработка *.JPG файлов через jpegtran завершена :: Указываем, что теперь прогон нужно осуществлять в новой папке jpeg_images set folder = jpg_%folder% echo Обработка *.JPG файлов через jpegoptim for /r %folder% %%a in (*.jpg) do ( set fn=%%a& jpegoptim %%~a --strip-all ) echo Обработка *.JPG файлов через jpegoptim завершена echo Обработка *.PNG файлов через optipng xcopy /y /t /c /i "%folder%" "png_%folder%" for /r %folder% %%a in (*.png) do ( set fn=%%a& optipng -o7 %%~a -out %home_path%png_!fn:%~dp0=! ) echo Обработка *.PNG файлов через optipng завершена set folder=png_%folder% echo Обработка *.PNG файлов через pngout for /r %folder% %%a in (*.png) do ( set fn=%%a& pngout %%~a ) echo Обработка *.PNG файлов через pngout завершена pause
Код закомментирован в важных частях. По сути, ничего сложного, разберётесь, если вам это нужно.
Теперь сохраняем и запускаем его.
Сжатие проходит с разделением файлов отдельно JPG, которые теперь располагаются в , и PNG отдельно, которые располагаются в .
Если нужно изменять качество или другие параметры, смотрите описание утилит выше и изменяйте код под свои нужды.
Основные характеристики
- программа может открывать большое количество разных типов изображений, таких как: jpg, jpeg, jpe, jif, png, gif, bmp, tif, tiff, psd, ico, tga, targa, mng, jng, j2k, j2c, jp2, pcd, pcx, wpa, wbmp, wbm, xbm, xpm, dds, g3, koa, iff, lbm, pbm, pgm, ppm, ras, cut, sgi, pct, pict, pic
- с помощью RIOT можно оптимизировать и впоследствии сохранить исходное изображение в форматах JPEG, GIF и PNG, причем для этого не придется обладать специфическими знаниями, интерфейс программы настолько прост что разобраться сможет любой
- окно программы разделено на два окна: исходное изображение и сжатое, многие настройки применяются в режиме реального времени, без дополнительного нажатия клавиш — автоматический просмотр результатов
- можно выставить определенный размер файла, для сжимаемого изображения
- одной приятной особенностью является, то что на экране сразу отображается размер итогового файла и исходного
- в программе можно работать как с одним файлом, так и с несколькими одновременно
- есть возможность работы с прозрачностью
- можно поменять метаданные изображения (комментарии, IPTC, Adobe XMP, EXIF профайл, ICC профайл), не поддерживаемые метаданные будут удалены
возможна передача метаданных между изображениями (но это в том случае если конечный файл поддерживает такие типы метаданных) - из стандартных инструментов доступны: поворот, масштабирование, и есть возможность отразить изображение как горизонтально так и вертикально
- можно так же сменить яркость, контрастность, гамму, и инвертировать
- в реальном времени есть возможность уменьшить количество цветов PNG и GIF, для того что бы размер файла стал меньше
- возможно изменение размера изображения с помощью известных фильтров таких как: Lanczos3, Catmull Rom, Bicubic, и др.
- в дополнениях можно найти поддержку внешних оптимизаторов изображения PNG (optiPNG, PNGOut)
- разработчики утверждают что результаты сжатия вполне можно сравнить с коммерческими продуктами, и даже намного лучше них
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.
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.
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.
Main differences from gulp-tinypng-compress
- Added new option (keepMetadata) to preserve metadata. Currently only copyright and creation date is supported.
- Added new option (keepOriginal) to override the original image instead of creating a new compressed file in the output path.
- Updated minimatch plugin to current version to avoid deprecated warnings.
- Fixed Problem with Bad Gateway errors receiving from the api. On error the plugin tries on default 10 times a reattempt and simply skips the image if the server is still not reachable (Thanks to @kevinranks)
compressing the next images. - On error the signature file is still being written for all successfully compressed files.
- Added check for empty or broken images to be skipped and not send
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.
Example resize request
You can resize an image by using the URL that was returned in the
header after compressing. A JSON request body has to be
provided together with a header.
For example, to save the resized and compressed image to a file named
:
Request options
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.
Reviews
http-equiv=»Content-Type» content=»text/html;charset=UTF-8″>lass=»plugin-reviews»>
So many site builders tend to overlook image compression — one of the most important aspects of site speed (and SEO). This plugin not only takes care of that problem but also completely automates it. Simply set it to compress images as you upload them and get (in my case at least) an average of 60-70% file size reduction — and that’s lossless reduction.
I tried others but found this plugin cuts about twice as much file size as the others I tried. I used to always worry about compressing images before uploading, and wondering if I had already compressed them or not. Now I never even have to think about it.
Thanks, TinyPNG!
Plugin works well. I was able to easily optimize my images. Great tool!
Great tool.
Sent for the API key which didn’t arrive and no option to have it sent again adding to that the support on here won’t let you make any new topics its become too much of a pain to get working.
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.
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.







