private static async Task SetApiKey() { while (_activeKeyIndex < ApiKeys.Length) { if (--_remainingRequests >= 0) { Debug.WriteLine($"Existing key used. Remaining compressions count {_remainingRequests}"); return; } Tinify.Key = ApiKeys[_activeKeyIndex++]; if (!await Tinify.Validate().ConfigureAwait(false) || Tinify.CompressionCount == null) { continue; } _remainingRequests = CompressionsLimit - Tinify.CompressionCount.Value; if (--_remainingRequests >= 0) { Debug.WriteLine($"New key set. Remaining compressions count {_remainingRequests}"); return; } } throw new Exception("The limit of Tinify compressions has been reached. Please add more API keys"); }
async Task <bool> SetApiKeyAsync(IConsole console) { try { var apiKey = string.IsNullOrEmpty(ApiKey) ? Environment.GetEnvironmentVariable(Constants.ApiKeyEnvironmentVariable) : ApiKey; if (string.IsNullOrWhiteSpace(apiKey)) { console.Error.WriteLine("Error: No API Key provided"); return(false); } Tinify.Key = apiKey; await Tinify.Validate(); console.WriteLine("TinyPng API Key verified"); return(true); } catch (System.Exception ex) { console.Error.WriteLine("Validation of TinyPng API key failed."); console.Error.WriteLine(ex); return(false); } }
async Task <bool> SetApiKeyAsync(IConsole console) { try { var apiKey = string.IsNullOrEmpty(ApiKey) ? this.readApikey() : ApiKey; if (string.IsNullOrWhiteSpace(apiKey)) { console.Error.WriteLine("Error: No API Key provided"); return(false); } Tinify.Key = apiKey; await Tinify.Validate(); console.WriteLine("TinyPng API Key verified"); // save this.writeApikey(apiKey); return(true); } catch (System.Exception ex) { console.Error.WriteLine("Validation of TinyPng API key failed."); console.Error.WriteLine(ex); return(false); } }
/// <summary> /// Reduce the physical size and byte size of an image /// </summary> /// <param name="buffer">Image to reduce as <see cref="byte[]"/></param> /// <param name="maxWidth">Maximum Width of Image as <see cref="int?"/></param> /// <param name="maxHeight">Maximum Height of Image as <see cref="int?"/></param> /// <returns>Image as <see cref="byte[]</returns> public async Task <byte[]> ResizeImage(byte[] buffer, int?maxWidth, int?maxHeight) { try { // TinyPNG Developer API KEY https://tinypng.com/developers Tinify.Key = ConfigurationAgent["ApplicationSettings:TinyPNG:ApiKey"]; var source = await Tinify.FromBuffer(buffer).ConfigureAwait(false); Source resized; if (maxWidth.HasValue && maxHeight.HasValue) { resized = source.Resize(new { method = "fit", width = maxWidth, height = maxHeight }); } else if (maxWidth.HasValue) { resized = source.Resize(new { method = "scale", width = maxWidth }); } else if (maxHeight.HasValue) { resized = source.Resize(new { method = "scale", height = maxHeight }); } else { return(buffer); } return(await resized.ToBuffer().ConfigureAwait(false)); } catch (AccountException accountEx) { // Verify API key and account limit. var x = await Tinify.Validate().ConfigureAwait(false); var compressionsThisMonth = Tinify.CompressionCount; var properties = new Dictionary <string, string> { { "compressionsThisMonth", compressionsThisMonth.HasValue ? compressionsThisMonth.Value.ToString(CultureInfo.CurrentCulture) : "0" } }; LoggingAgent.TrackException(accountEx, properties); } catch (TinifyAPI.Exception tex) { LoggingAgent.TrackException(tex); } catch (System.Exception ex) { LoggingAgent.TrackException(ex); throw; } // something went wrong, just return input value return(buffer); }
public void WithLimitedKey_Should_ReturnTrue() { Tinify.Key = "valid"; Helper.MockClient(Tinify.Client); Helper.MockHandler.Expect("https://api.tinify.com/shrink").Respond( (HttpStatusCode)429, new StringContent("{\"error\":\"Too may requests\",\"message\":\"Your monthly limit has been exceeded\"}") ); Assert.AreEqual(true, Tinify.Validate().Result); }
public void WithValidKey_Should_ReturnTrue() { Tinify.Key = "valid"; Helper.MockClient(Tinify.Client); Helper.MockHandler.Expect("https://api.tinify.com/shrink").Respond( HttpStatusCode.BadRequest, new StringContent("{\"error\":\"Input missing\",\"message\":\"No input\"}") ); Assert.AreEqual(true, Tinify.Validate().Result); }
public void WithError_Should_ThrowException() { Tinify.Key = "valid"; Helper.MockClient(Tinify.Client); Helper.MockHandler.Expect("https://api.tinify.com/shrink").Respond( HttpStatusCode.Unauthorized, new StringContent("{\"error\":\"Unauthorized\",\"message\":\"Credentials are invalid\"}") ); Assert.ThrowsAsync <AccountException>(async() => { await Tinify.Validate(); }); }
public static async Task <int> Execute(OptimizeOptions options, IConsole console, InvocationContext context = null) { if (options == null) { console.Error.WriteLine("Invalid File TemplateRepositoryPath"); return(ReturnCodes.Error); } var settingsManager = new TinifySettingsManager(new FileSystemRoamingProfileAppEnvironment()); TinifySettings settings = settingsManager.LoadSettings(); try { console.Out.WriteLine("Validating Tinify API Key"); Tinify.Key = settings.Key; bool validKey = await Tinify.Validate().ConfigureAwait(false); if (!validKey) { console.Error.WriteLine("Invalid Tinify API Key"); return(ReturnCodes.Error); } long originalSizeInBytes = options.FilePath.Length; console.Out.WriteLine($"Original size: {originalSizeInBytes / 1024}KB"); Source source = await Tinify.FromFile(options.FilePath.FullName).ConfigureAwait(false); await source.ToFile(options.FilePath.FullName); long newSizeInBytes = new FileInfo(options.FilePath.FullName).Length; double percentChange = (newSizeInBytes - originalSizeInBytes) * 100.0 / originalSizeInBytes; console.Out.WriteLine($"New size: {newSizeInBytes / 1024}KB"); console.Out.WriteLine($"{percentChange:00}% Reduction"); } catch (Exception exception) { console.Error.WriteLine(exception.Message); return(ReturnCodes.Exception); } return(ReturnCodes.Ok); }
public static Task <bool> CheckKey() { string zcf = GetUnusedKeys(); if (zcf != String.Empty) { Tinify.Key = zcf; } else { Console.WriteLine("keys已经使用完成请添加可用的key"); Console.ReadKey(); ; } return(Tinify.Validate()); }
static async Task MainAsync(string[] args, string path) { Program p = new Program(); try { Tinify.Key = ConfigurationManager.AppSettings["TinyKey"]; await Tinify.Validate(); } catch (AccountException e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("API KEY ERROR: " + e.Message); Console.ReadLine(); Environment.Exit(0); } List <FileInfo> files = new List <FileInfo>(); long counter = 0; if (Directory.Exists(path)) { files = p.TraverseTree(path); Console.WriteLine("\n------------------ {0} FILES FOUND --------------------\n", files.Count); foreach (FileInfo f in files) { long length = f.Length; var source = Tinify.FromFile(f.FullName); try { await source.ToFile(f.FullName); counter++; Console.WriteLine("{0} compressed successfully...", f.Name); } catch (ClientException e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("{0} has an unsupported data format...[skipped]", f.Name); Console.ForegroundColor = ConsoleColor.Green; continue; } } } Console.WriteLine("\n Complete! {0} files compressed. You have done {1} compression(s) so far. Press Enter to close...", counter, Tinify.CompressionCount); Console.ReadLine(); Environment.Exit(0); }
public MainPage() { InitializeComponent(); Task.Run(async() => { try { Tinify.Key = "PUT_AN_API_KEY_HERE"; bool validKey = await Tinify.Validate(); Debug.WriteLine($"[TINIFY]: Was conexion valid?: {validKey}"); } catch (System.Exception ex) { Debug.WriteLine(ex); } }); }
public async Task CompressImages(string path) { var log = new List <string>(); var compressions = new List <ImageTransformation>(); Tinify.Key = tbTinyPngKey.Text; var isApiKeyValid = await Tinify.Validate(); if (!isApiKeyValid) { log.Add("API key is invald: " + Tinify.Key); } else { var files = GetFiles(path).Take(5); // var files = GetFiles(path); //uncomment to optimize all files foreach (var img in files) { var sourcePath = img.FilePath; var filename = PathExtensions.GetRelativePath(path, sourcePath); var destinationPath = Path.Combine(DestinationFolderPath, filename); // ensure the folder exists for proper working source.ToFile(); new DirectoryInfo(Path.GetDirectoryName(destinationPath)).Create(); var compression = new ImageTransformation() { Path = destinationPath, OldSize = img.Size, }; var compressionsThisMonth = Tinify.CompressionCount == null ? 0 : Tinify.CompressionCount; if (compressionsThisMonth < 500) { try { // Use the Tinify API client. var source = Tinify.FromFile(sourcePath); await source.ToFile(destinationPath); compression.NewSize = source.GetResult().Result.Size; compressions.Add(compression); } catch (AccountException e) { log.Add(string.Format("Error for image '{0}'. Error message: ", filename, e.Message)); //System.Console.WriteLine("The error message is: " + e.Message); // Verify your API key and account limit. } catch (ClientException e) { log.Add(string.Format("Error for image '{0}'. Error message: ", filename, e.Message)); var mimetype = MimeTypes.getMimeFromFile(sourcePath); log.Add(String.Format("The actual mime type of '{0}' image is '{1}' ", filename, mimetype)); // Check your source image and request options. } catch (ServerException e) { log.Add(string.Format("Error for image '{0}'. Error message: ", filename, e.Message)); // Temporary issue with the Tinify API. } catch (ConnectionException e) { log.Add(string.Format("Error for image '{0}'. Error message: ", filename, e.Message)); // A network connection error occurred. } catch (System.Exception e) { log.Add(string.Format("Error for image '{0}'. Error message: ", filename, e.Message)); // Something else went wrong, unrelated to the Tinify API. } } else { log.Add("Free API usage is near the limit: " + compressionsThisMonth); //break; } } } using (TextWriter writer = new StreamWriter(Server.MapPath("~/errors.xml"))) { var serializer = new XmlSerializer(typeof(List <string>)); serializer.Serialize(writer, log); } using (TextWriter writer = new StreamWriter(Server.MapPath("~/compressions.xml"))) { var serializer = new XmlSerializer(typeof(List <ImageTransformation>)); serializer.Serialize(writer, compressions); } RadGrid1.DataSource = log; RadGrid1.DataBind(); }
/// <summary> /// 压缩 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void BtnCompress_Click(object sender, RoutedEventArgs e) { Tinify.Key = _currentKey; if (cbScale.IsChecked == true)//需要缩放 { _needToScale = true; try { _newWidth = Math.Abs(Convert.ToInt32(tbNewWidth.Text)); } catch { System.Windows.MessageBox.Show("缩放图片宽度数据错误"); return; } } else { _needToScale = false; } msgProgress.Content = "向TinyPNG服务器发送请求..."; try { await Tinify.Validate(); } catch (System.Exception ex) { System.Windows.MessageBox.Show("连接失败" + ex.Message.ToString()); return; } msgProgress.Content = "成功连接至TinyPNG服务器。"; if (cbOverlay.IsChecked == true)//覆盖 { _outputPath = _currentPath; } else { _outputPath = _currentPath + "/CompressedResult"; CreateDirectory(_outputPath); } //开启多线程 //if (cbThread.IsChecked == true) //{ // try // { // _threadCount = Convert.ToInt32(tbThreadCount.Text); // } // catch // { // System.Windows.MessageBox.Show("线程数量输入不合理"); // _threadCount = 1; // return; // } //} //else //{ // _threadCount = 1; //} _threadCount = 1; GetCompressedImg(_outputPath); }