public static async Task <byte[]> Fit(byte[] image, int width, int height) { try { IncrementPending(); await SemaphoreSlim.WaitAsync().ConfigureAwait(false); Task <Source> resized; try { await SetApiKey().ConfigureAwait(false); var source = Tinify.FromBuffer(image); resized = source.Resize(new { method = "fit", width, height }); } finally { SemaphoreSlim.Release(); } Debug.WriteLine("Sending compression request"); var result = await resized.ToBuffer().ConfigureAwait(false); return(result); } catch (Exception e) { Debug.WriteLine(e.Message); throw; } finally { DecrementPending(); } }
/// <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 static async Task <string> TinifyModulAsync(string base64String, string type) { try { var stringbase64 = ""; var data64 = Regex.Split(base64String, ";base64,"); if (data64.Length > 1) { stringbase64 = data64[1]; } else { stringbase64 = data64[0]; } byte[] bytes = System.Convert.FromBase64String(stringbase64); Tinify.Key = "3bfrr65Nl2QYQTk8lGHGQ8w8ZGJ358ND"; var source = Tinify.FromBuffer(bytes); string Key = type + "/" + CommonFunction.GetTimestamp(DateTime.UtcNow) + "_" + CommonFunction.RandomNumber(0, 99999999); await source.Store(new { service = "s3", aws_access_key_id = "AKIAJZMY3NCCEJQXACJA", aws_secret_access_key = "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", region = "ap-southeast-1", path = bucketname + "/" + Key, }); return(Key); } catch (AccountException e) { return(""); // Verify your API key and account limit. } catch (ClientException e) { return(""); // Check your source image and request options. } catch (ServerException e) { return(""); // Temporary issue with the Tinify API. } catch (ConnectionException e) { return(""); // A network connection error occurred. } catch (System.Exception e) { return(""); // Something else went wrong, unrelated to the Tinify API. } }
public async Task <byte[]> CompressImage(byte[] uncomressedBytes) { var uncompressedFilesize = GetFileSize(uncomressedBytes); Console.WriteLine($"TINYPNG Uncompressed Filesize: {uncompressedFilesize}"); var compressedImage = await Tinify.FromBuffer(uncomressedBytes).ToBuffer(); var compressedFilesize = GetFileSize(compressedImage); Console.WriteLine($"TINYPNG Compressed Filesize: {compressedFilesize}"); return(compressedImage); }
private async void compress(PictureBox picSrc, PictureBox picDest, Label lblSize) { PlayAnimation(); var source = Tinify.FromBuffer(ImgToByte(picSource.Image)); source = source.Preserve("copyright"); var result = await source.ToBuffer(); picDest.Image = ByteToImg(result); computeSize(picDest, lblSize); StopAnimation(); MessageBox.Show(Tinify.CompressionCount.Value.ToString()); }
public static async Task <byte[]> CompressFile(byte[] buffer, int w = 500, int h = 500) { try { return(await Tinify.FromBuffer(buffer).Resize(new { method = "fit", width = w, height = h }).ToBuffer()); } catch (TinifyAPI.Exception ex) { return(new byte[] { }); } }
public static async Task <byte[]> CompressBase64(byte[] buffer, int w = 500, int h = 500) { try { Tinify.Key = "hdrdBNqcCwkPQqVYml22fqsqtGf71xdC"; return(await Tinify.FromBuffer(buffer).Resize(new { method = "fit", width = w, height = h }).ToBuffer()); } catch (TinifyAPI.Exception ex) { return(new byte[] { }); } }
private async void CompresserBtn_Click(object sender, EventArgs e) { if (resimYol.Count != 0 && (!string.IsNullOrWhiteSpace(metroTextBox1.Text))) { try { progressPanel1.Show(); ToplamDurumProgressBar.Show(); kayitYeri = KlasorOlustur(); indirilenDosyaListBox.Items.Clear(); int i = 0; int boyut = 100 / resimYol.Count; foreach (var resim in resimYol) { ToplamDurumProgressBar.Percentage = boyut * i; Image img = Image.FromFile(resim.Value); var resultData = await Tinify.FromBuffer(Util.ImgToByte(img)).ToBuffer(); Image responseImage = Util.ByteToImage(resultData); responseImage.Save(kayitYeri + "\\" + resim.Key); indirilenDosyaListBox.Items.Add(resim.Key); i++; ToplamDurumProgressBar.Percentage = boyut * i; } } catch (Exception t) { MessageBox.Show(t.Message); ToplamDurumProgressBar.Hide(); } finally { ToplamDurumProgressBar.Percentage = 100; progressPanel1.Hide(); resimYol.Clear(); dosyaListBox.Items.Clear(); } } else { MessageBox.Show("Klasör Seçili değil veya API Key alanı boş!"); } }
public async Task <Stream> OptimiseAsync(Stream stream, string fileName) { if (!CanOptimise(fileName)) { return(stream); } var tinyPngSettings = (await _siteService.GetSiteSettingsAsync()).As <TinyPngSettings>(); if (!tinyPngSettings.HasApiKey) { _logger.LogWarning("Unable to compress images with TinyPNG without API key."); return(stream); } Tinify.Key = tinyPngSettings.ApiKey; using var memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); return(new MemoryStream(await Tinify.FromBuffer(memoryStream.ToArray()).ToBuffer())); }
public override Stream Process(FileProcessorInput fileInput) { using (var timeoutCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutDurationInSeconds))) { try { if (fileInput == null) { throw new ArgumentException("fileInput cannot be null"); } byte[] imageBytes = this.GetByteArray(fileInput.FileStream); var sourceData = Tinify.FromBuffer(imageBytes); if (this.preserveMetadata) { sourceData.Preserve(this.MetadataKeys); } var resultData = sourceData.ToBuffer().ContinueWith(t => t.GetAwaiter().GetResult(), timeoutCancellationTokenSource.Token).Result; Stream stream = new MemoryStream(resultData); return(stream); } catch (TaskCanceledException) { Log.Write("Image optimization has timed out. Default image stream was returned.", ConfigurationPolicy.ErrorLog); return(fileInput.FileStream); } catch (Exception ex) { Log.Write(ex, ConfigurationPolicy.ErrorLog); return(fileInput.FileStream); } } }
/// <summary> /// 处理新上传的图片资源 /// </summary> /// <param name="idList"></param> public async Task DealNewResourceAsync(List <long> idList) { if (idList.Count < 1) { return; } var resourceList = _dataAccess.GetDailyStoryResourceModelsById(idList); if (resourceList.Count < 1) { return; } var dictServer = new SysDicService(); var inUserService = new InuseKeyInfoService(); var dictList = dictServer.GetAllDict("FtpConfig"); if (dictList == null || dictList.Count < 1) { return; } var ftpUrl = dictList.FirstOrDefault(f => f.Lable == "FtpUrl")?.Value; var ftpUserName = dictList.FirstOrDefault(f => f.Lable == "FtpUserName")?.Value; var ftpPassword = dictList.FirstOrDefault(f => f.Lable == "FtpPassword")?.Value; var ftpViewPre = dictList.FirstOrDefault(f => f.Lable == "FtpViewPre")?.Value; var tinifyCodeList = dictServer.GetAllDict("TinifyKey")?.OrderBy(f => f.Sort).ToList(); if (tinifyCodeList == null || tinifyCodeList.Count < 1) { return; } var newTime = DateTime.Now; var tiniCodeUseLimit = 500; var inUseModel = inUserService.GetModels("TinifyKey", null, newTime.Year, newTime.Month)?.FirstOrDefault(f => f.UseCount < tiniCodeUseLimit); if (inUseModel == null || tinifyCodeList.All(f => f.Value != inUseModel.KeyInfo)) { inUseModel = new InusekeyinfoModel { CreateTime = newTime, IsDel = FlagEnum.HadZore, KeyInfo = tinifyCodeList[0].Value, KeyType = "TinifyKey", UseCount = 0, UseDate = newTime }; inUserService.SaveModel(inUseModel); if (inUseModel.Id < 1) { Console.WriteLine("保存失败"); return; } } foreach (var model in tinifyCodeList) { if (model.Value == inUseModel.KeyInfo) { model.IsDel = FlagEnum.HadOne.GetHashCode(); } } Tinify.Key = inUseModel.KeyInfo; var ftpServer = new FtpUpLoadFiles(ftpUrl, ftpUserName, ftpPassword); var allowExtensions = new List <string> { ".jpeg", ".png", ".jpg" }; foreach (var f in resourceList) { //压缩图片 if (string.IsNullOrEmpty(f.Url)) { continue; } var tempPath = HostingEnvironment.MapPath(f.Url); if (string.IsNullOrEmpty(tempPath)) { continue; } var fileExtension = Path.GetExtension(tempPath)?.ToLower(); if (fileExtension == null) { continue; } var sourceData = File.ReadAllBytes(tempPath); byte[] resultData = null; //判断文件扩展名是否能够进行压缩 var couldCompress = allowExtensions.Select(x => x.ToLower()).Contains(fileExtension); if (couldCompress) { try { resultData = await Tinify.FromBuffer(sourceData).ToBuffer(); } catch (Exception e) { Console.WriteLine(e); continue; } //该code已经用完了 if (Tinify.CompressionCount >= tiniCodeUseLimit) { //变更原有的状态 inUseModel.IsDel = FlagEnum.HadOne; inUseModel.UseCount = (int)Tinify.CompressionCount; inUserService.SaveModel(inUseModel); //重新生成 var tempKey = tinifyCodeList.FirstOrDefault(r => r.IsDel == FlagEnum.HadZore.GetHashCode()); if (tempKey == null) { continue; } tempKey.IsDel = FlagEnum.HadOne.GetHashCode(); inUseModel = new InusekeyinfoModel { CreateTime = newTime, IsDel = FlagEnum.HadZore, KeyInfo = tempKey.Value, KeyType = "TinifyKey", UseCount = 0, UseDate = newTime }; inUserService.SaveModel(inUseModel); } else { inUseModel.UseCount = (int)(Tinify.CompressionCount ?? 0); inUserService.SaveModel(inUseModel); } } //上传 var indexOfName = f.Url.LastIndexOf("/", StringComparison.Ordinal); if (indexOfName < 0) { continue; } var fileName = f.Url.Substring(indexOfName); var transferFinish = ftpServer.UploadFile("", couldCompress ? resultData : sourceData, fileName); if (transferFinish) { //上传完成 f.FullUrl = ftpViewPre + fileName; SaveModel(f); } } }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { GenreChoices = _context.Genre.Select(s => new SelectListItem { Value = s.GenreID.ToString(), Text = s.Name }).ToList(); return(Page()); } if (FileUpload == null) { ModelState.AddModelError("Validation.FileUpload.FileIsBlank", "Please choose a file to upload"); GenreChoices = _context.Genre.Select(s => new SelectListItem { Value = s.GenreID.ToString(), Text = s.Name }).ToList(); return(Page()); } //Validate the Genres foreach (var genre in Genres) { if (!await _context.Genre.AnyAsync(a => a.GenreID.ToString() == genre)) { ModelState.AddModelError("Validation.Genre.IsInvalid", "An unknown Genre was provided"); } } var showpieceID = Guid.NewGuid(); var fileName = showpieceID.ToString() + ".png"; Showpiece.Slug = mtgdm.Helpers.Slugify.ToUrlSlug(Showpiece.Title); if (await _context.Showpiece.AnyAsync(a => a.Slug.Equals(Showpiece.Slug, StringComparison.OrdinalIgnoreCase) && a.ShowpieceID != Showpiece.ShowpieceID)) { ModelState.AddModelError("Validation.Title.IsUsed", $"The title '{Showpiece.Title}' has already been taken"); return(Page()); } try { using var input = new MemoryStream(); FileUpload.CopyTo(input); input.Position = 0; var bucket = _config["AWS.S3.Bucket.Content"]; var region = _config["AWS.S3.Region"]; Tinify.Key = _config["Tinify.APIKey"]; var source = Tinify.FromBuffer(input.ToArray()); //Headers aren't passing to cloudfront: https://github.com/cagataygurturk/image-resizer-service/issues/7 var head = new Dictionary <string, string>() { { "Cache-Control", "max-age=31536000" } }; await source.Store(new { service = "s3", aws_access_key_id = _config["AWS.S3.AccessKeyId"], aws_secret_access_key = _config["AWS.S3.SecretKey"], region = region, path = bucket + fileName, headers = head }); } catch (AccountException e) { // Verify your API key and account limit. ModelState.AddModelError("", e.Message); return(Page()); } catch (ClientException e) { switch (e.Status) { case 415: ModelState.AddModelError("", "File type is not supported"); return(Page()); default: ModelState.AddModelError("", e.Message); return(Page()); } } catch (ServerException e) { // Temporary issue with the Tinify API. ModelState.AddModelError("", e.Message); return(Page()); } catch (ConnectionException e) { // A network connection error occurred. ModelState.AddModelError("", e.Message); return(Page()); } catch (System.Exception e) { // Something else went wrong, unrelated to the Tinify API. ModelState.AddModelError("", e.Message); return(Page()); } if (Showpiece.Synopsis == null) { Showpiece.Synopsis = ""; } Showpiece.ShowpieceID = showpieceID; Showpiece.Created = DateTime.Now; Showpiece.Published = true; Showpiece.URL = String.Concat(_config["AWS.CloudFront.URL.Resize"], "content/", fileName); Showpiece.UserID = Guid.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); var genres = Genres.Select(s => new ShowpieceToGenre() { ShowpieceToGenreID = Guid.NewGuid(), ShowpieceID = showpieceID, GenreID = Guid.Parse(s) }); await _context.ShowpieceToGenre.AddRangeAsync(genres); await _context.Showpiece.AddAsync(Showpiece); await _context.SaveChangesAsync(); return(new RedirectToPageResult("/Showpiece/View", new { name = Showpiece.Slug })); }