Compress Image and Save to Amazon S3 using Tinify API C#

In this article, We will learn how to Compress Image and Save to Amazon S3 using Tinify API C#.

You can get the idea about tinify API, key and the nuget package briefly from my previous article  : compress images using tinify API C#.

Add the following C# code to Compress image and upload it to Amazon S3.

1). Compress Image from local path and upload to S3:

public static string _tinyPngKey = ""; // Your Tinify API key
public static string _awsAccessKey = ""; // Your AWS Access key
public static string _awsSecretKey = ""; // Your AWS Secret key
public static string _bucketName = ""; // Your S3 Bucket Name

public static async System.Threading.Tasks.Task Main(string[] args)
{
    try
    {
        var imagePath = "D:/Personal/HD_Images/ghanshyam-godhani.jpeg";

        Tinify.Key = _tinyPngKey;
        await Tinify.Validate();

        var fileName = Path.GetFileName(imagePath);

        var source = Tinify.FromFile(imagePath).Result;
        await source.Store(new
        {
            service = "s3",
            aws_access_key_id = _awsAccessKey,
            aws_secret_access_key = _awsSecretKey,
            region = "eu-west-3",
            path = _bucketName + "/" + fileName
        });
    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message.ToString());
    }
}

 

2). Compress Image from URL and upload to S3:

public static string _tinyPngKey = ""; // Your Tinify API key
public static string _awsAccessKey = ""; // Your AWS Access key
public static string _awsSecretKey = ""; // Your AWS Secret key
public static string _bucketName = ""; // Your S3 Bucket Name

public static async System.Threading.Tasks.Task Main(string[] args)
{
    try
    {
        var imgUrl = @"http://staging.thecodehubs.com/wp-content/uploads/2020/07/ghanshyam-godhani.jpeg";

        Tinify.Key = _tinyPngKey;
        await Tinify.Validate();

        var fileName = Path.GetFileName(imgUrl);

        var source = Tinify.FromUrl(imgUrl).Result;
        await source.Store(new
        {
            service = "s3",
            aws_access_key_id = _awsAccessKey,
            aws_secret_access_key = _awsSecretKey,
            region = "eu-west-3",
            path = _bucketName + "/" + fileName
        });
    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message.ToString());
    }
}

 

Now you can check your bucket on Amazon S3. The compressed images are there.

Submit a Comment

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

Subscribe

Select Categories