Compress Images using Tinify API C#

In this article, We will learn the Tinyfy API to compress the image from the Local path as well as from the URL in C#.

Follow the below steps to get your API key :

  1. Open this link: Tinyfy Developer API.
  2. Enter your name and Email address
  3. Click on Get your API key.
  4. Then Check you will get Tinify Email
  5. On Email, Click on Visit your dashboard
  6. On API Dashboard, Click on Add API Key
  7. In this way, you will get your API key.

 

Note:

  1. The first 500 image compressions each month are free. You will only be billed if you compress more than 500 images in a month.
  2. If your image is already compressed and you will try to compress it again then Tinyfy did not compress it and also they didn’t count in API.

 

Now we have the API key. Follow the below steps to compress your images :

  • Install the latest Tinify NuGet from Manage Nuget Packages.
  • Add namespace using TinifyAPI;
  • Compress Image from local path :
public static async System.Threading.Tasks.Task Main(string[] args)
{

    try
    {
        Tinify.Key = "abcdefghijklmnopqrstuvwxyz"; // ------- Change your Tinyfy key here
        await Tinify.Validate();

        var destinationDirectory = @"D:/Images/Compressed/";

        if (!Directory.Exists(destinationDirectory))
        {
            Directory.CreateDirectory(destinationDirectory);
        }

        var fromImagePath = @"D:/Images/Data/Ghanshyam.jpg";

        string fileName = Path.GetFileName(fromImagePath);

        Tinify.FromFile(fromImagePath).ToFile(destinationDirectory + fileName).Wait();
    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message.ToString());
    }
}
  • Compress Image from URL :
public static async System.Threading.Tasks.Task Main(string[] args)
{

    try
    {
        Tinify.Key = "abcdefghijklmnopqrstuvwxyz"; // ------- Change your Tinyfy key here
        await Tinify.Validate();

        var destinationDirectory = @"D:/Images/Compressed/";

        if (!Directory.Exists(destinationDirectory))
        {
            Directory.CreateDirectory(destinationDirectory);
        }

        var imgUrl = @"https://www.thecodehubs.com/wp-content/uploads/2020/07/ghanshyam-godhani.jpeg";
        string fileName = Path.GetFileName(imgUrl);

        Tinify.FromUrl(imgUrl).ToFile(destinationDirectory + fileName).Wait();
    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message.ToString());
    }
}
  • Now you can check your destination directory. The compressed images are there.

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories