public static byte[] ResizeAndCompressImage(byte[] imageFileBytes, bool isResize, int maxWidthPx, int maxHeightPx, bool isCompress) { var newImageFileBytes = imageFileBytes; if (isResize) { newImageFileBytes = ImageResizeHelper.Resize(imageFileBytes, maxWidthPx, maxHeightPx); } if (!isCompress) { return(newImageFileBytes); } using var streamToCompress = new MemoryStream(newImageFileBytes); var compressResult = ImageCompressor.Compress(streamToCompress); newImageFileBytes = compressResult.ResultFileStream.ToArray(); return(newImageFileBytes); }
public void CompressTestCase() { // Test On Linux ------------------------- var input2Path = "/Users/top/Downloads/Test File 2.png"; var input3Path = "/Users/top/Downloads/Test File 3.JPG"; var input4Path = "/Users/top/Downloads/Test File 4.JPG"; var input5Path = "/Users/top/Downloads/Test File 5.gif"; ImageCompressor.Compress(input3Path, "/Users/top/Downloads/Test File 3 Compressed.JPG"); // ImageCompressor.Compress(input4Path, "/Users/top/Downloads/Test File 4 Compressed.JPG"); ImageCompressor.Compress(input2Path, "/Users/top/Downloads/Test File 2 Compressed.png"); ImageCompressor.Compress(input5Path, "/Users/top/Downloads/Test File 5 Compressed.gif"); // Test On Windows ------------------------- // var input2Path = "D:\\Test File 2.png"; // var input3Path = "D:\\Test File 3.JPG"; // var input4Path = "D:\\Test File 4.JPG"; // var input5Path = "D:\\Test File 5.gif"; // // ImageCompressor.Compress(input2Path, "D:\\Test File 2 Compressed.png"); // ImageCompressor.Compress(input3Path, "D:\\Test File 3 Compressed.JPG"); // ImageCompressor.Compress(input5Path, "D:\\Test File 5 Compressed.gif"); }
public OptimizeBlobsImages() { var parseStatus = int.TryParse(ConfigurationManager.AppSettings["QualityLevel"], out int compressionLevel); _imageCompressor = new ImageCompressor(parseStatus ? compressionLevel : 75); IsStoppable = true; }
private void btnCompress_Click(object sender, EventArgs e) { string path = txtPath.Text; ImageCompressor imgCompressor = new ImageCompressor(); imgCompressor.CompressImage(path, 50); }
public async override void Invoke(CancellationToken cancellationToken) { ImageCompressor compressor = new ImageCompressor(); bool isDataUri = Attribute.Value.StartsWith("data:image/", StringComparison.Ordinal); if (isDataUri) { string dataUri = await compressor.CompressDataUriAsync(Attribute.Value); if (dataUri.Length < Attribute.Value.Length) { using (WebEssentialsPackage.UndoContext(this.DisplayText)) using (ITextEdit edit = TextBuffer.CreateEdit()) { Span span = Span.FromBounds(Attribute.ValueRangeUnquoted.Start, Attribute.ValueRangeUnquoted.End); edit.Replace(span, dataUri); edit.Apply(); } } } else { var fileName = ImageQuickInfo.GetFullUrl(Attribute.Value, TextBuffer); if (string.IsNullOrEmpty(fileName) || !ImageCompressor.IsFileSupported(fileName) || !File.Exists(fileName)) { return; } await compressor.CompressFilesAsync(fileName); } }
public string Index() { ImageCompressor imageCompressor = new ImageCompressor(); var result = imageCompressor.CompressFile(@"C:\Users\abhimanyu\Desktop\upload\imagename.jpg", true); return(result.ToString()); }
public IEnumerable <ISmartTagAction> GetSmartTagActions(ParseItem item, int position, ITrackingSpan itemTrackingSpan, ITextView view) { UrlItem url = (UrlItem)item; if (!url.IsValid || url.UrlString == null || string.IsNullOrEmpty(url.UrlString.Text)) { yield break; } string text = url.UrlString.Text.Trim('"', '\''); string testSupportFileName = text; if (url.IsDataUri()) { string mime = FileHelpers.GetMimeTypeFromBase64(text); testSupportFileName = "file." + FileHelpers.GetExtension(mime); } if (!ImageCompressor.IsFileSupported(testSupportFileName)) { yield break; } yield return(new OptimizeImageSmartTagAction(itemTrackingSpan, url)); }
public async override void Invoke() { ITextBuffer textBuffer = this.HtmlSmartTag.TextBuffer; ElementNode element = this.HtmlSmartTag.Element; AttributeNode src = element.GetAttribute("src", true); ImageCompressor compressor = new ImageCompressor(); bool isDataUri = src.Value.StartsWith("data:image/", StringComparison.Ordinal); if (isDataUri) { string dataUri = await compressor.CompressDataUriAsync(src.Value); if (dataUri.Length < src.Value.Length) { using (WebEssentialsPackage.UndoContext("Optimize image")) { Span span = Span.FromBounds(src.ValueRangeUnquoted.Start, src.ValueRangeUnquoted.End); textBuffer.Replace(span, dataUri); } } } else { var fileName = ImageQuickInfo.GetFullUrl(src.Value, textBuffer); if (string.IsNullOrEmpty(fileName) || !ImageCompressor.IsFileSupported(fileName) || !File.Exists(fileName)) { return; } await compressor.CompressFilesAsync(fileName); } }
private BitmapImage CreateBitmapImageFromPath(string path, bool shouldCompress = false) { if (path != null && !File.Exists(path.Replace("file:///", ""))) { path = DoujinScrubber.GetDefaultCoverPath(Directory); } else if (path != null && shouldCompress) { path = ImageCompressor.CompressImage(path, 40); } if (path == null) { return(null); } BitmapImage newCoverImage = new BitmapImage(); newCoverImage.BeginInit(); newCoverImage.UriSource = new Uri(path, UriKind.Absolute); newCoverImage.CacheOption = BitmapCacheOption.None; newCoverImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache; newCoverImage.DecodePixelWidth = 140; newCoverImage.EndInit(); newCoverImage.Freeze(); return(newCoverImage); }
public async ValueTask <(bool succeed, Error error, ImageResult result)> CreateIamgeResourceAsync(byte[] base64Image) { var unq_name = $"{Guid.NewGuid().ToString()}-{DateTime.UtcNow.ToUnix()}"; var end = new ImageResult(); try { var error = default(string); (end.OriginImagePath, error) = await CreateImageByCompressPercentAsync(base64Image, unq_name, origin, 0.5); if (string.IsNullOrEmpty(end.OriginImagePath)) { return(false, Error.Create(Errors.CompressFileFailed, error), null); } (end.ThumbnailPath, error) = await CreateImageByCompressPercentAsync(base64Image, unq_name, thumbnail, 0.1, true); if (string.IsNullOrEmpty(end.ThumbnailPath)) { return(false, Error.Create(Errors.CompressFileFailed, error), null); } (end.Width, end.Height) = ImageCompressor.BinarySize(base64Image); } catch (Exception e) { return(false, Error.Create(Errors.CreateFileFailed, e.Message), null); } return(true, Error.Empty, end); }
public void UncompressedSizeReturnsCorrectImageSize() { var ic = new ImageCompressor("PapaWestray.jpg"); Assert.AreEqual(3264, ic.UncompressedSize.Width); Assert.AreEqual(2448, ic.UncompressedSize.Height); }
public async override void Invoke() { ITextBuffer textBuffer = this.HtmlSmartTag.TextBuffer; ElementNode element = this.HtmlSmartTag.Element; AttributeNode src = element.GetAttribute("src", true); ImageCompressor compressor = new ImageCompressor(); bool isDataUri = src.Value.StartsWith("data:image/", StringComparison.Ordinal); if (isDataUri) { string dataUri = await compressor.CompressDataUri(src.Value); if (dataUri.Length < src.Value.Length) { using (EditorExtensionsPackage.UndoContext("Optimize image")) { Span span = Span.FromBounds(src.ValueRangeUnquoted.Start, src.ValueRangeUnquoted.End); textBuffer.Replace(span, dataUri); } } } else { var fileName = ImageQuickInfo.GetFullUrl(src.Value, textBuffer); if (string.IsNullOrEmpty(fileName) || !ImageCompressor.IsFileSupported(fileName) || !File.Exists(fileName)) return; await compressor.CompressFiles(fileName); } }
public void CannotCreateIfInvalidFilename() { Assert.ThrowsException <ArgumentException>(() => { var ic = new ImageCompressor("DoesNotExist.jpg"); Assert.IsInstanceOfType(ic, typeof(ImageCompressor)); }); }
public void CompressorUnitTest() { var imageCompressJpegResult = ImageCompressor.Compress("<file name>.jpg", "<outlet file name>.jpg"); var imageCompressGifResult = ImageCompressor.Compress("<file name>.gif", "<outlet file name>.gif"); var imageCompressPngResult = ImageCompressor.Compress("<file name>.png", "<outlet file name>.png"); }
private void picsorBackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { _directory = openFileDialog .FileName.Substring(0, openFileDialog.FileName.LastIndexOf('\\')) + "\\PicsorConverted"; if (!Directory.Exists(_directory)) { Directory.CreateDirectory(_directory); } foreach (var file in openFileDialog.FileNames) { ImageCompressor imageCompressor = new ImageCompressor(new Bitmap(file)); // Type of resizing Bitmap resized = null; if (resizingSelection.Current.Text == "Size") { resized = imageCompressor.GetResizeUsingMaxDimensions(pbMaxWidth.Value, pbMaxHeight.Value); } else if (pbPercent.Value != 100) { resized = imageCompressor.GetResizedUsingPercentage(pbPercent.Value / 100f); } // Define forced codec ImageCodecInfo codec = null; if (formatSelection.Current.Text == "JPG") { codec = imageCompressor.GetCodec(ImageFormat.Jpeg); } else if (formatSelection.Current.Text == "PNG") { codec = imageCompressor.GetCodec(ImageFormat.Png); } // Update output filename for forced codec string outputFilename = file.Substring(file.LastIndexOf('\\') + 1); if (codec != null) { outputFilename += $".{formatSelection.Current.Text}"; } // Or keep current codec else { codec = imageCompressor.GetCurrentCodec(); } // Encode and save imageCompressor.EncodeAndSave( codec, _directory + "\\" + outputFilename, pbQuality.Value, resized); } }
public DownloadController( OSSDbContext dbContext, ImageCompressor imageCompressor, IConfiguration configuration) { _dbContext = dbContext; _imageCompressor = imageCompressor; _configuration = configuration; }
public DownloadController( FolderLocator folderLocator, ProbeDbContext dbContext, IConfiguration configuration, ImageCompressor imageCompressor) { _folderLocator = folderLocator; _dbContext = dbContext; _configuration = configuration; _imageCompressor = imageCompressor; }
public DownloadController( FolderLocator folderLocator, ProbeDbContext dbContext, ImageCompressor imageCompressor, TokenEnsurer tokenEnsurer, IStorageProvider storageProvider) { _folderLocator = folderLocator; _dbContext = dbContext; _imageCompressor = imageCompressor; _tokenEnsurer = tokenEnsurer; _storageProvider = storageProvider; }
public void AppendImageToPdf(byte[] image, bool compressFirst = true) { if (compressFirst) { ImageCompressor.CompressImage(ref image); } var img = iTextSharp.text.Image.GetInstance(image); img.ScalePercent(24f); document.NewPage(); document.Add(img); }
public DownloadController( FolderSplitter folderLocator, ImageCompressor imageCompressor, TokenEnsurer tokenEnsurer, IStorageProvider storageProvider, FolderRepo folderRepo, FileRepo fileRepo, SiteRepo siteRepo, ProbeLocator probeLocator) { _folderSplitter = folderLocator; _imageCompressor = imageCompressor; _tokenEnsurer = tokenEnsurer; _storageProvider = storageProvider; _folderRepo = folderRepo; _fileRepo = fileRepo; _siteRepo = siteRepo; this.probeLocator = probeLocator; }
public void SavesAsSmallerJpgCorrectly() { string tmpFolder = Path.GetTempPath(); string tmpOutputPath = Path.Combine(tmpFolder, "PapaWestray.jpg"); try { var ic = new ImageCompressor("PapaWestray.jpg"); string result = ic.SaveAs(tmpOutputPath, "JPG", 100000L, new Size(1024, 768), 66); Assert.IsTrue(File.Exists(tmpOutputPath)); Assert.AreEqual(String.Empty, result); } finally { if (File.Exists(tmpOutputPath)) { File.Delete(tmpOutputPath); } } }
private async ValueTask <(string result, string error)> CreateImageByCompressPercentAsync(byte[] base64Image, string unq_name, string prefix, double percent = 1, bool cut = false) { var name = $"/resources/{prefix}/{unq_name}.png"; var bts = base64Image; var error = default(string); if (percent < 1) { (bts, error) = cut ? ImageCompressor.BinaryCutCompress(bts, percent, 320, 1600) : ImageCompressor.BinaryCompress(bts, percent, 800); } if (!string.IsNullOrEmpty(error)) { return(null, error); } using (var logFile = File.Create(this.env.WebRootPath + name)) using (var logWriter = new BufferedStream(logFile)) { await logWriter.WriteAsync(bts, 0, bts.Length); return(name, null); }; }
public async override void Invoke() { if (string.IsNullOrEmpty(_url.UrlString.Text)) { return; } ImageCompressor compressor = new ImageCompressor(); string url = _url.UrlString.Text.Trim('"', '\''); if (_url.IsDataUri()) { string dataUri = await compressor.CompressDataUriAsync(url); if (dataUri.Length < url.Length) { using (EditorExtensionsPackage.UndoContext("Optimize image")) { Span span = Span.FromBounds(_url.UrlString.Start, _url.UrlString.AfterEnd); _span.TextBuffer.Replace(span, "'" + dataUri + "'"); } } } else { string selection = Uri.UnescapeDataString(url); string fileName = ProjectHelpers.ToAbsoluteFilePath(selection, _span.TextBuffer.GetFileName()); if (string.IsNullOrEmpty(fileName) || !ImageCompressor.IsFileSupported(fileName) || !File.Exists(fileName)) { return; } await compressor.CompressFilesAsync(fileName); } }
public void IsImageDetectsAValidImage() { Assert.IsTrue(ImageCompressor.IsImage("PapaWestray.jpg")); }
protected void Page_Load(object sender, EventArgs e) { currentDate = DateTime.Now.ToString("dd/MMM/yyyy"); DBContext = new SQLContext(); try { HttpCookie DivineQRFile = Request.Cookies["DivineQRFile"]; filename = DivineQRFile["Filename"].ToString(); } catch (Exception exq) { Response.Redirect("ScanQR.html"); } try { srcfile = Path.Combine(Request.MapPath("~/upload"), filename); dstfile = Path.Combine(Request.MapPath("~/upload/proc"), filename); Ic = new ImageCompressor(srcfile, dstfile); } catch (Exception eXc) { } var QCreader = new BarcodeReader(); var QCresult = QCreader.Decode(new Bitmap(dstfile)); userID = QCresult.Text; if (QCresult != null) { SqlCommand cmd = new SqlCommand("select count(*) from Tbl_User_Details where Var_Udtl_Uid='" + QCresult.Text + "'", DBContext._SqlConnection); SqlDataReader dr = cmd.ExecuteReader(); int i = 0; while (dr.Read()) { i = dr.GetInt32(0); } dr.Close(); if (i == 1) { SqlCommand cmd1 = new SqlCommand("select Var_Udtl_Name,Var_Udtl_DoorNo," + "Var_Udtl_ApartmentName,Var_Udtl_AreaName,Flt_Udtl_reqMor" + ",Flt_Udtl_reqEve from Tbl_User_Details where Var_Udtl_Uid='" + QCresult.Text + "'", DBContext._SqlConnection); SqlDataReader dr1 = cmd1.ExecuteReader(); while (dr1.Read()) { MyServerControlDiv.Controls.Add(new LiteralControl("<div class='alert alert-success' role='alert'>")); MyServerControlDiv.Controls.Add(new LiteralControl("<h3 style='font-size:18px !important; text-align:center;'><strong> " + dr1.GetValue(0).ToString() + " </strong></h3>")); MyServerControlDiv.Controls.Add(new LiteralControl("<h4 style='font-size:16px !important;text-align:center;'> Door No " + dr1.GetValue(1).ToString() + "</h4>")); MyServerControlDiv.Controls.Add(new LiteralControl("<h4 style='font-size:16px !important;text-align:center;'> " + dr1.GetValue(2).ToString() + "</h4>")); MyServerControlDiv.Controls.Add(new LiteralControl("<h4 style='font-size:16px !important;text-align:center;'> " + dr1.GetValue(3).ToString() + "</h4>")); MyServerControlDiv.Controls.Add(new LiteralControl("<h3 style='font-size:18px !important;text-align:center;'> <strong> Req. Morning: </strong>" + dr1.GetValue(4).ToString() + "</h3>")); MyServerControlDiv.Controls.Add(new LiteralControl("<h3 style='font-size:18px !important;text-align:center;'> <strong> Req. Eve: </strong>" + dr1.GetValue(5).ToString() + "</h3>")); MyServerControlDiv.Controls.Add(new LiteralControl("</div>")); isRecordExist(); } dr1.Close(); } else { MyServerControlDiv.Controls.Add(new LiteralControl("<div class='alert alert-info alert-dismissible' role='alert'>")); MyServerControlDiv.Controls.Add(new LiteralControl("<button type='button' class='close' data-dismiss='alert'><span aria-hidden='true'>×</span></button>")); MyServerControlDiv.Controls.Add(new LiteralControl("<strong>Sorry!</strong> the information doesnot exist. further details please contact administrator.")); MyServerControlDiv.Controls.Add(new LiteralControl("</div>")); } } else { Response.Redirect("ScanQR.html"); } }
public void CanCreate() { var ic = new ImageCompressor("PapaWestray.jpg"); Assert.IsInstanceOfType(ic, typeof(ImageCompressor)); }
public void IsImageRejectsAnInvalidImage() { Assert.IsFalse(ImageCompressor.IsImage("PapaWestray.txt")); }