Tinify.Unofficial 1.0.3-prerelease.18

Suggested Alternatives

TinyPNG

This is a prerelease version of Tinify.Unofficial.
There is a newer version of this package available.
See the version list below for details.
dotnet add package Tinify.Unofficial --version 1.0.3-prerelease.18                
NuGet\Install-Package Tinify.Unofficial -Version 1.0.3-prerelease.18                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Tinify.Unofficial" Version="1.0.3-prerelease.18" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Tinify.Unofficial --version 1.0.3-prerelease.18                
#r "nuget: Tinify.Unofficial, 1.0.3-prerelease.18"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Tinify.Unofficial as a Cake Addin
#addin nuget:?package=Tinify.Unofficial&version=1.0.3-prerelease.18&prerelease

// Install Tinify.Unofficial as a Cake Tool
#tool nuget:?package=Tinify.Unofficial&version=1.0.3-prerelease.18&prerelease                

GitHub Workflow Status GitHub last commit Nuget

Unofficial fork of the Tinify API Client for .NET

Official Tinify GitHub repo

.NET client for the Tinify API, used for TinyPNG and TinyJPG. Tinify compresses your images intelligently. Read more at http://tinify.com.

Installation

Install the API client:

Install-Package Tinify.Unofficial

💥 Minor Breaking Change between v1.0.2 and v1.0.3

The Shrink methods on the TinifyClient were renamed:

  • ShrinkFromFile  => ShrinkFromFileAsync
  • ShrinkFromBuffer => ShrinkFromBufferAsync
  • ShrinkFromUrl  => ShrinkFromUrlAsync

Usage

Initialize the TinifyClient

Simply construct a new instance of TinifyClient with your API key

Example
using Tinify.Unofficial;
var client = new TinifyClient("YOUR_API_KEY");

The client constructor also allows for the specifying of an HttpMessageHandler which allows you to manage any kind of custom or specialized handling needed: specifying a proxy, special SSL handling, etc. The TinifyClient does not assume ownership of this handler, you are responsible for managing its lifetime.

If no handler is specified then the default SocketsHttpHandler with a PooledConnectionLifetime setting of 5 minutes is used. (Note: this also applies to the .netstandard 2.1 target see StandardSocketsHttpHandler)

Example
public class MyProxy : IWebProxy
{
    private readonly Uri _uri;
    public ICredentials Credentials { get; set; }

    public MyProxy(string url)
    {
        Uri.TryCreate(url, UriKind.Absolute, out _uri));
        var user = _uri.UserInfo.Split(':');
        Credentials = new NetworkCredential(user[0], user[1]);
    }

    public Uri GetProxy(Uri destination) => _uri;

    public bool IsBypassed(Uri host) => host.IsLoopback;
}

var client = new TinifyClient("YOUR_API_KEY",
    new HttpClientHandler()
    {
        Proxy = new MyProxy(@"http://user:pass@localhost:8080"),
        UserProxy = true,
    });

Compress image using one of the ShrinkFrom methods

  • ShrinkFromFileAsync
  • ShrinkFromBufferAsync
  • ShrinkFromUrlAsync
Example
var client = new TinifyClient("YOUR_API_KEY");
await using var optimizedImage = await client.ShrinkFromFileAsync("unoptimized.png");
await optimizedImage.ToFileAsync("optimized.png");

This will upload the image to the Tinify image service and will return an OptimizedImage

Check current compression count

You can check your current compression count by accessing the static CompressionCount property of the TinifyClient class. This count is updated each time a response from the Tinify endpoint returns a compression count.

Example
var currentCompressionCount = TinifyClient.CompressionCount;

Other Tinify Transform Operations

To perform other transform operations (resize, convert, etc) simply call the TransformImage method on the optimized image. The TransformImage operation takes a single TransformOperations argument. The TransformOperations object must be constructed with at least one operation. Each of the Tinify operations are by the different operations that can be specified in the TransformOperations constructor.

Tinify API Operation Tinify.Unofficial.Operation
resize ResizeOperation
convert ConvertOperation
preserve PreserveOperation
store CloudStoreOperation*

*note: CloudStoreOperation is an abstract class and has concrete implementations as AwsCloudStoreOperation and GoogleCloudStoreOperation

Example
await using var optimizedImage = await client.ShrinkFromFile("unoptimized.jpg");

var resizeOptions = new ResizeOperation(ResizeType.Fit, 50, 20);
var preserveOptions = new PreserveOperation(PreserveOptions.Copyright | PreserveOptions.Creation);
var transformOperations = new TransformOperations(resize: resizeOptions, preserve: preserveOptions);
await using var result = await optimizedImage.TransformImage(transformOperations);

await result.ToFileAsync("optimized_and_transformed.jpg");

Note:
Because both OptimizedImage and ImageResult objects maintain an internal buffer of the image data, which has been rented from the ArrayPool, you should be sure to Dispose of them so that the buffer is returned to the pool. Both objects implement IDisposable and IAsyncDisposable so that they can be easily wrapped in using blocks or statements.

Saving the optimized or transformed image

You can save both OptimizedImage and ImageResult objects to a file, to a stream, to a buffer or pass in a preallocated buffer and copy the data directly to the buffer

Example
await using var optimizedImage = await client.ShrinkFromFile("unoptimized.jpg");
await using var transformedImage =
    await optimizedImage.TransformImage(new TransformOperations(
        resize: new ResizeOperation(ResizeType.Fit, 50, 20)
    ));
                                    
var optimizedBuffer = await optimizedImage.ToBufferAsync();

// Note the ImageResult object already holds an internal buffer
// with the image data and so will just return a copy synchronously
var transformedBuffer = transformedImage.ToBuffer();

using var msOptimized = new MemoryStream();
await optimizedImage.ToStreamAsync(msOptimized);

using var msTransformed = new MemoryStream();
await transformedImage.ToStreamAsync(msTransformed);

var bufferOptimized = new byte[optimizedImage.ImageSize.Value];
await optimizedImage.CopyToBufferAsync(bufferOptimized);

// Note the ImageResult object already holds an internal buffer
// with the image data and so will just copy the data synchronously
var bufferTransformed = new byte[transformedImage.DataLength];
transformedImage.CopyToBuffer(bufferTransformed);

Running tests

dotnet restore
dotnet test test/Tinify.Unofficial.Tests

Integration tests

dotnet restore
TINIFY_KEY=$YOUR_API_KEY dotnet test test/Tinify.Unofficial.Tests.Integration

Or add a .env file to the /test/Tinify.Unofficial.Tests.Integration directory in the format

TINIFY_KEY=<YOUR_API_KEY>

License

This software is licensed under the MIT License. View the license.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

## 1.0.1
* Forked official Tinify repo at version 1.5.3
* MultiTargets .Net Standard 2.1 and .Net 6.0
* Modernized code and added memory and performance enhancements
* Added support for the Tinify convert operation

## 1.0.2
* More internal cleanup
* Documentation cleanup

## 1.0.3
* Minor breaking change, renamed `ShrinkFrom...` methods to `ShrinkFrom...Async`
to be consistent with other asynchronous method signatures
* Updated documentation with more explanation and usage examples
* Added new `ShrinkFromStreamAsync` method