Processing Ajax...

Title

Message

Confirm

Confirm

Confirm

Confirm

Are you sure you want to delete this item?

Confirm

Are you sure you want to delete this item?

Optimizing/shrink size for selected files images via https://tinypng.com

Description
Optimize/shrink size for all selected files (available for webp, png, jpeg and jpg fromat). Required entry Your unical API key. More info here: https://tinypng.com/developers
Language
C#.net
Minimum Version
Created By
KarolPiechoczek
Contributors
-
Date Created
Apr 12, 2022
Date Last Modified
Apr 12, 2022

Scripted Function (Macro) Code

using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;

// The 'windowHandle' parameter will contain the window handle for the:
//   - Active window when run by hotkey
//   - Trigger target when run by a Trigger rule
//   - TitleBar Button owner when run by a TitleBar Button
//   - Jump List owner when run from a Taskbar Jump List
//   - Currently focused window if none of these match
public static class DisplayFusionFunction
{
	public static void Run(IntPtr windowHandle)
	{
		string[] imageExtensions = { ".webp", ".png", ".jpeg", ".jpg" };
        BFS.Clipboard.Copy();

        foreach (string file in Clipboard.GetFileDropList())
        {
            string fileExtension = Path.GetExtension(file.ToLower());
			
            if (Array.IndexOf(imageExtensions, fileExtension) != -1)
            {
				WebRequest request = WebRequest.Create("https://api.tinify.com/shrink");
				//Entry API KEY without []
		        request.Headers.Add("Authorization", "Basic [ENTRY HERE YOUR API KEY]");
		        request.Method = "POST";
                string fileName = Path.GetFileNameWithoutExtension(file);
                string dirFile = Path.GetDirectoryName(file);
                byte[] data = File.ReadAllBytes(file);
                request.ContentLength = data.Length;

                Stream stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();

                stream = request.GetResponse().GetResponseStream();
                StreamReader sr = new StreamReader(stream);

                WebClient webClient = new WebClient();
                webClient.DownloadFile(Regex.Match(sr.ReadToEnd(), "\"url\":\"(.*)\"}}").Groups[1].Value, $@"{dirFile}\{fileName}_optimized{fileExtension}");

                sr.Close();
                stream.Close();
				
            }
        }
	}
}