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 :
- Open this link: Tinyfy Developer API.
- Enter your name and Email address
- Click on Get your API key.
- Then Check you will get Tinify Email
- On Email, Click on Visit your dashboard
- On API Dashboard, Click on Add API Key
- In this way, you will get your API key.
Note:
- The first 500 image compressions each month are free. You will only be billed if you compress more than 500 images in a month.
- 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.