Api reference

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.

Зачем оптимизировать изображения

В нынешний век мобильных технологий оптимизация картинок в форматах PNG и JPG,JPEG стала снова актуальна, как это было актуальным в те времена, когда интернет только входил в нашу жизнь и был повсеместно медленным и диалапным. Мобильный интернет, конечно, не совсем корректно сравнивать с диалапом, но местами, где связь плохая, там и скорость доступа довольно маленькая. Да и в те времена пользователю было некуда деваться, и приходилось ждать загрузки страницы. Сейчас же интернет вырос, выбор сайтов большой. Пользователь стал капризным и нетерпеливым, и среднее время ожидания загрузки страницы сильно уменьшилось

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

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

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.

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.

Error handling

The Tinify API uses HTTP status codes to indicate success or failure. Any HTTP errors are converted into error objects, which are passed as the first argument to callback functions.

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.

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.

Description

Make your website faster by optimizing your JPEG and PNG 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.
  • WP Offload S3 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 > Compress JPEG & PNG images 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 and PNG 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.

Базовая оптимизация изображений

Тут подразумевается обрезка ненужных полей, уменьшение глубины цвета, удаление комментариев и сохранение изображения в подходящем формате. Для этого можете воспользоваться Adobe Photoshop, или, если у вас его нет, MS Paint или GIMP. Даже элементарная обрезка изображения неплохо снизит его вес.

Как уменьшить изображение в MS Paint

Покажу на примере MS Paint, как уменьшить изображение до нужных размеров. Возьмём для примера лого NGINX и его изображение nginx.png размером 2000×417 пикселей, которое нужно обрезать по ширине до 1024, т.к. это ширина вёрстки страницы, и делать больше нет смысла.

  1. Открываем Paint (Пуск-Выполнить-Вводим «mspaint»)

  2. Загружаем nginx.png, находим «Изменить размер», открывается окошко с процентами и пикселями, в нём переходим на пиксели и задаём нужный размер, в нашем случае вбиваем в ширину 1024

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

How to use promise API

const{compress}=require('compress-images/promise');constINPUT_path_to_your_images='src/img/**/*.{jpg,JPG,jpeg,JPEG,png}';constOUTPUT_path='build/img/';constprocessImages=async()=>{constresult=awaitcompress({            source INPUT_path_to_your_images,            destination OUTPUT_path,            enginesSetup{                jpg{ engine'mozjpeg', command'-quality','60'},                png{ engine'pngquant', command'--quality=20-50','-o'},}});const{statistics,errors}= result;};processImages();

Using

const{compress}=require('compress-images/promise');constINPUT_path_to_your_images='src/img/**/*.{jpg,JPG,jpeg,JPEG,png}';constOUTPUT_path='build/img/';constprocessImages=async(onProgress)=>{constresult=awaitcompress({            source INPUT_path_to_your_images,            destination OUTPUT_path,            onProgress,            enginesSetup{                jpg{ engine'mozjpeg', command'-quality','60'},                png{ engine'pngquant', command'--quality=20-50','-o'},}});const{statistics,errors}= result;};processImages((error,statistic,completed)=>{if(error){console.log('Error happen while processing file');console.log(error);return;}console.log('Sucefully processed file');console.log(statistic)});

Getting started

Once you retrieve your key, you can immediately start shrinking images. Official client libraries are available for Ruby, PHP, Node.js, Python, Java and .NET. You can also use the WordPress plugin to compress your JPEG and PNG images. And in case you own a Magento store you can simply install the extensions for Magento 1 CE, Magento 1 EE or Magento 2 CE to optimize your product images.

The community has also created a large number of third-party add-ons using the Developer API.

You can also create your own integration with any HTTP(S) client. The server will compress your image and respond with a URL where you can grab the result.

curl --user api:YOUR_API_KEY \
      --data-binary @unoptimized.png -i https://api.tinify.com/shrink

Как настроить сжатие 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 отдельно, которые располагаются в .

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

API

(, , , , , , , , )

  • input (type:string): Path to source image or images; Example: 1. ; 2. ; 3. ; 4. ;

  • output (type:string): Path to compress images; Example: 1. ;

  • option (type:plainObject): Options module`s «compress-images»;

    • compress_force (type:boolean): Force compress images already compressed images or ;
    • statistic (type:boolean): show image compression statistics or ;
    • pathLog (type:string): Path to log file. Default is ;
    • autoupdate (type:boolean): Auto-update module «compress_images» to the latest version or ; Example: 1. ;
  • enginejpg (type:plainObject): Engine for compressing jpeg and options compress. Key to be ;

    • engine (type:string): Engine for compressing jpeg. Possible values: ,, , , , , ;
    • command (type:boolean|array): Options for compression. Can be or commands array.
  • enginepng (type:plainObject): Engine for compressing png and options for compression. Key to be ;

    • engine (type:string): Engine for compressing png. Possible values: ,, , , , ;
    • command (type:boolean|array): Options for compression. Can be or commands array.
  • enginesvg (type:plainObject): Engine for compressing svg and options for compression. Key to be ;

    • engine (type:string): Engine for compressing svg. Possible values: ;
    • command (type:string): Options for compression. Can be or commands type string.
  • enginegif (type:plainObject): Engine for compressing gif and options for compression. Key to be ;

    • engine (type:string): Engine for compressing gif. Possible values: , , ;
    • command (type:boolean|array): Options for compression. Can be or commands type array.
  • callback (err, completed, statistic): returns:

    • err (type:json object|null)
      • engine — The name of the algorithm engine
      • input — The path to the input image
      • output — The path to the output image
    • completed (type:boolean)
      • — result completed.
      • — result not completed.
    • statistic (type:json object)

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.

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.

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.

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.

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.

Compressing images

You can upload any JPEG or PNG image to the Tinify API to compress it. We will automatically detect the type of image and optimise with the TinyPNG or TinyJPG engine accordingly. Compression will start as soon as you upload a file or provide the URL to the image.

Example upload from file

You can upload a local file. The post data contains the image binary.

For example, if you have a file named in the current directory:

Example upload from URL

You can also provide a URL to your image instead of having to upload it. The API accepts a JSON body with the image URL as a location.

For example, if you have as your source:

Example download request

The compressed image can be retrieved by using the URL in the header from the previous step.

For example, you can save the compressed image to a file named and open it:

Installation

From your WordPress dashboard

  1. Visit Plugins > Add New.
  2. Search for ‘tinypng’ and press the ‘Install Now’ button for the plugin named ‘Compress JPEG & PNG images’ by ‘TinyPNG’.
  3. Activate the plugin from your Plugins page.
  4. Go to the Settings > Compress JPEG & PNG images page and register a new account.
  5. Or enter the API key you got from https://tinypng.com/developers.
  6. Go to Media > Bulk Optimization and optimize all your images!

From WordPress.org

  1. Download the plugin named ‘Compress JPEG & PNG images’ by ‘TinyPNG’.
  2. Upload the directory to your directory, using your favorite method (ftp, sftp, scp, etc…)
  3. Activate the plugin from your Plugins page.
  4. Go to the Settings > Compress JPEG & PNG images page and register a new account.
  5. Or enter the API key you got from https://tinypng.com/developers.
  6. Go to Media > Bulk Optimization and optimize all your images!

Optional configuration

The API key can also be configured in your wp-config.php file. To do this you can add the following PHP code that sets the API key.


С этим читают