private void ResizeCropToAspectRatio(MagickImage input, Stream output, int width, int height) { if (input.Width > width && input.Height > height) { input.Resize(new MagickGeometry(width, height) { FillArea = true }); } var desiredAspectRatio = width / (double)height; var currentAspectRatio = input.Width / (double)input.Height; if (desiredAspectRatio != currentAspectRatio) { if (desiredAspectRatio > currentAspectRatio) { input.Crop(width, (int)Math.Round(input.Height * currentAspectRatio / desiredAspectRatio)); } else { input.Crop((int)Math.Round(input.Width * desiredAspectRatio / currentAspectRatio), height); } } }
public void CopyFile(string filename, string destFile) { using (MagickImage image = new MagickImage(filename)) { double zw = (double)Width / image.Width; double zh = (double)Height / image.Height; double za = FillImage ? ((zw <= zh) ? zw : zh) : ((zw >= zh) ? zw : zh); if (FillImage) { double aspect = (double)VideoType.Width / VideoType.Height; double pAspect = (double)image.Width / image.Height; if (aspect > pAspect) { image.Crop(image.Width, (int)(image.Width / aspect), Gravity.Center); } else { image.Crop((int)(image.Height / aspect), image.Height, Gravity.Center); } } MagickGeometry geometry = new MagickGeometry(VideoType.Width, VideoType.Height) { IgnoreAspectRatio = false, FillArea = false }; image.FilterType = FilterType.Point; image.Resize(geometry); image.Quality = 80; image.Format = MagickFormat.Jpeg; image.Write(destFile); } }
public override void Execute(object parameter) { DateTime startTime = DateTime.Now; ViewModel.CreateTargetDirectory(); string targetExt = ViewModel.TargetExtension; ViewModel.TargetExtension = ".ico"; using (var image = new MagickImage(ImageFile.FullName)) { if (ImageFile.Width > ImageFile.Height) { image.Crop(ImageFile.Height, ImageFile.Height, Gravity.Center); } else if (ImageFile.Height > ImageFile.Width) { image.Crop(ImageFile.Width, ImageFile.Width, Gravity.Center); } image.Settings.SetDefine(MagickFormat.Icon, "auto-resize", "256,128,64,48,32,16"); image.Write(ViewModel.TargetFileName); } if (ViewModel.OptimizeTarget) { base.Execute(ViewModel.TargetFileName); } ViewModel.TargetExtension = targetExt; ViewModel.ElapsedTime = DateTime.Now.Subtract(startTime); }
public async Task <ActionResult <Attachment> > UploadAvatar(IFormFile file) { try { var extension = Path.GetExtension(file.FileName); if (extension.ToLower().StartsWith(".jp") || extension.ToLower().StartsWith(".png")) { var dirPath = UploadPath(); var path = Path.Combine(dirPath, file.FileName); if (System.IO.File.Exists(path)) { dirPath = CreateRandomNameDirectory(); path = Path.Combine(dirPath, file.FileName); } await using (var stream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(stream); } using (MagickImage image = new MagickImage(path)) { image.AutoOrient(); if (image.Width > image.Height) { image.Crop(image.Height, image.Height, Gravity.Center); image.RePage(); } else { var n = new MagickGeometry(0, -image.Height / 10, image.Width, image.Width); image.Crop(n, Gravity.Center); image.RePage(); } if (image.Width > 300) { image.Resize(240, 0); } image.Quality = 60; image.Write(path); } return(Ok(path)); } return(BadRequest()); } catch (NotSupportedException ex) { return(BadRequest(new { Message = $"Error: {ex.Message}" })); } }
internal static bool TrySaveImage(Int32Rect rect, BitmapSource bitmapSource, string destination) { try { using var SaveImage = new MagickImage { Quality = 100 }; var encoder = new PngBitmapEncoder(); // or any other BitmapEncoder encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); using (var stream = new MemoryStream()) { encoder.Save(stream); SaveImage.Read(stream.ToArray()); } if (Rotateint != 0) { SaveImage.Rotate(Rotateint); } SaveImage.Crop(new MagickGeometry(rect.X, rect.Y, rect.Width, rect.Height)); SaveImage.Write(destination); } catch (Exception) { return(false); } return(true); }
private static void ConvertToPng(FileInfo file) { Console.WriteLine(file.FullName); var pngPath = Path.Combine(file.DirectoryName, Path.GetFileNameWithoutExtension(file.FullName) + ".png"); var jsonPath = Path.Combine(file.DirectoryName, Path.GetFileNameWithoutExtension(file.FullName) + ".json"); var hotSpots = GetCursorHotSpots(file.FullName); if (hotSpots.Length != 1) { throw new Exception("More than one cursor hot spot! We only expect one!"); } var hotSpot = hotSpots[0]; using (var image = new MagickImage(file.FullName)) { hotSpot.X -= image.BoundingBox.X; hotSpot.Y -= image.BoundingBox.Y; image.Crop(image.BoundingBox); // +repage to remove the PNG layer offset. image.SetAttribute("page", "0x0+0+0"); image.Format = MagickFormat.Png; image.Write(pngPath); //Console.WriteLine("{0} -- {1} {2}x{3} BoundingBox={4}x{5} HotSpot={6}x{7}", pngPath, image.Format, image.Width, image.Height, image.BoundingBox.Width, image.BoundingBox.Height, hotSpot.X, hotSpot.Y); File.WriteAllText(jsonPath, hotSpot.ToJson()); } }
public static byte[] ProcessImage(MagickImage image) { if (image.Width < 1000 || image.Height < 500) { throw new ArgumentException("Image supplied is too small. Need at least 1000x500"); } if (image.Width > 2000 || image.Height > 2000) { throw new ArgumentException("Image supplied is too large. Need at maximum 2000x2000"); } //Calculate the relative position int x = (int)Math.Round(xRatio * image.Width); int y = (int)Math.Round(yRatio * image.Height); int width = (int)Math.Round(widthRatio * image.Width); int height = (int)Math.Round(heightRatio * image.Height); //Perform the crop, repage and return the bytes image.Crop(new MagickGeometry(x, y, width, height)); image.Format = MagickFormat.Jpeg; image.RePage(); return(image.ToByteArray()); }
/// <summary> /// Crops an image according to a selection rectangel /// </summary> /// <param name="image"> /// the image to be cropped /// </param> /// <param name="selection"> /// the selection /// </param> /// <returns> /// cropped image /// </returns> public static Image Crop(this Image source, Rectangle selection) { Bitmap bmp = source as Bitmap; Bitmap copy = null; // Check if it is a bitmap: if (bmp != null) { if (selection.Width < 0) { selection = new Rectangle(selection.X + selection.Width, selection.Y, Math.Abs(selection.Width), selection.Height); } if (selection.Height < 0) { selection = new Rectangle(selection.X, selection.Y + selection.Height, selection.Width, Math.Abs(selection.Height)); } using (MagickImage image = new MagickImage(bmp)) { copy = new Bitmap(selection.Width, selection.Height); image.Format = MagickFormat.Png; image.Crop(selection.X, selection.Y, selection.Width, selection.Height); using (Graphics g = Graphics.FromImage(copy)) { g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(image.ToBitmap(), 0, 0, copy.Width, copy.Height); } } } return(copy); }
public override MagickImage ApplyFilter(MagickImage image) { using (var pixels = image.GetPixels()) { SetPixelSkipRates(image.Width, image.Height); var prescanH = preScan_H(pixels, image.Width, image.Height); var prescanV = preScan_V(pixels, image.Width, image.Height); var rangeResult = FindPreScanEdgeRange(prescanH); var edgeTop = FindEdge(pixels, rangeResult[0], rangeResult[1], EnumAxis.Horiztontal, image.Width, EnumScanDirection.Forward); rangeResult = FindPreScanEdgeRange(FlipPreScanResults(prescanH)); var edgeBottom = FindEdge(pixels, rangeResult[1], rangeResult[0], EnumAxis.Horiztontal, image.Width, EnumScanDirection.Backward); rangeResult = FindPreScanEdgeRange(prescanV); var edgeLeft = FindEdge(pixels, rangeResult[0], rangeResult[1], EnumAxis.Vertical, image.Height, EnumScanDirection.Forward); rangeResult = FindPreScanEdgeRange(FlipPreScanResults(prescanV)); var edgeRight = FindEdge(pixels, rangeResult[1], rangeResult[0], EnumAxis.Vertical, image.Height, EnumScanDirection.Backward); var cropWidth = edgeRight - edgeLeft; var cropHeight = edgeBottom - edgeTop; image.Crop(edgeLeft, edgeTop, cropWidth, cropHeight); return(image); } }
private void makeTile(int x, int y, MyImage img, int tile_size) { int x_offset = x * tile_size; int y_offset = y * tile_size; int z = img.Zoom; MagickGeometry geometry = new MagickGeometry(); geometry.Width = tile_size; geometry.Height = tile_size; geometry.X = x_offset; geometry.Y = y_offset; MagickImage chunk = (MagickImage)img.Image.Clone(); chunk.Crop(geometry); chunk.Format = MagickFormat.Png; string zPath = "./tiles/" + z; if (!Directory.Exists(zPath)) { Directory.CreateDirectory(zPath); } string xPath = "./tiles/" + z + "/" + x; if (!Directory.Exists(xPath)) { Directory.CreateDirectory(xPath); } string fullPath = "./tiles/" + z + "/" + x + "/" + y + ".png"; chunk.Write(fullPath); }
public static void crop(string image_path, string output_path, Tuple <int, int> from, Tuple <int, int> to) { using (MagickImage image = new MagickImage(image_path)) { image.Crop(new MagickGeometry(from.Item1, from.Item2, to.Item1 - from.Item1, to.Item2 - from.Item2)); image.Write(output_path); } }
public BaseReturn Crop(ImageCropDTO dto) { var result = new BaseReturn(); try { using (var image = new MagickImage(dto.Source)) { image.Crop(dto.Width, dto.Height); image.Write(dto.FullDestination); } if (dto.DeleteSource) { File.Delete(dto.Source); } result.Ok(); } catch (Exception ex) { result.AddMessage("[error]", ex.Message); } return(result); }
public string Execute(FileItem item, string infile, string dest, ValuePairEnumerator configData) { var conf = new CropTransformViewModel(configData); using (MagickImage image = new MagickImage(infile)) { if (conf.FromLiveView && ServiceProvider.DeviceManager.SelectedCameraDevice != null) { var prop = ServiceProvider.DeviceManager.SelectedCameraDevice.LoadProperties(); conf.Left = (int)(image.Width * prop.LiveviewSettings.HorizontalMin / 100); conf.Width = (image.Width * (prop.LiveviewSettings.HorizontalMax - prop.LiveviewSettings.HorizontalMin) / 100); conf.Top = (image.Height * prop.LiveviewSettings.VerticalMin / 100); conf.Height = (image.Height * (prop.LiveviewSettings.VerticalMax - prop.LiveviewSettings.VerticalMin) / 100); } if (conf.CropMargins) { conf.Left = image.Width * conf.WidthProcent / 100; conf.Width = image.Width - (conf.Left * 2); conf.Top = image.Height * conf.HeightProcent / 100; conf.Height = image.Height - (conf.Top * 2); } MagickGeometry geometry = new MagickGeometry(); geometry.Width = conf.Width; geometry.Height = conf.Height; geometry.X = conf.Left; geometry.Y = conf.Top; image.Crop(geometry); image.Format = MagickFormat.Jpeg; image.Write(dest); } return(dest); }
public void Execute_ImageWithAlpha_AlphaIsRestored() { var tshirtFile = GetInputFile("tshirt_gray.jpg"); var overlayFile = GetInputFile("flowers_van_gogh.jpg"); using (var tshirtImage = new MagickImage(tshirtFile)) { tshirtImage.Opaque(new MagickColor("#FEFEFE"), MagickColors.None); using (var overlayImage = new MagickImage(overlayFile)) { overlayImage.Crop(479, 479); var script = new TshirtScript { Fit = TshirtFit.Crop, Blur = 0, Lighting = 0, Sharpen = 0 }; script.SetCoordinates(new MagickGeometry(275, 175, 130, 130)); using (var scriptOutput = script.Execute(tshirtImage, overlayImage)) { AssertOutput(scriptOutput, "flowers_van_gogh_alpha.jpg"); } } } }
public void Crop(string imagePath, string outputPath) { if (imagePath == null || outputPath == null) { return; } bool valx, valy; string msg = "Invalid numeric value"; Point ptFrom = ParsePoint(txtFrom.Text, out valx); Point ptTo = ParsePoint(txtTo.Text, out valy); if (!valx || !valy) { LogError(msg); return; } Tuple <int, int> from = new Tuple <int, int>(ptFrom.X, ptFrom.Y); Tuple <int, int> to = new Tuple <int, int>(ptTo.X, ptTo.Y); using (MagickImage image = new MagickImage(imagePath)) { image.Crop(new MagickGeometry(from.Item1, from.Item2, to.Item1 - from.Item1, to.Item2 - from.Item2)); image.Grayscale(); image.Write(outputPath); } }
public static string CaptureElementBitmap(IWebDriver driver, string directory, string fileName, IWebElement element, MagickFormat imageFormat) { Directory.CreateDirectory(directory); var filename = directory + fileName + ".png"; // Take ScreenCap of Entire Screen var screenshotDriver = driver as ITakesScreenshot; Screenshot screenshot = screenshotDriver.GetScreenshot(); // Read image from file using (MagickImage image = new MagickImage()) { image.Read(new MemoryStream(screenshot.AsByteArray)); // Sets the output format to jpeg image.Format = imageFormat; image.Page = new MagickGeometry(element.Location.X, element.Location.Y); image.Crop(new MagickGeometry(element.Size.Width, element.Size.Height), Gravity.Northwest); image.RePage(); // Create byte array that contains a jpeg file File.WriteAllBytes(filename, image.ToByteArray()); return(filename); } }
public void Execute_ImageWithAlpha_AlphaIsRestored() { var tshirtFile = GetInputFile("tshirt_gray.jpg"); /* LosslessCompress(tshirtFile); */ var overlayFile = GetInputFile("flowers_van_gogh.jpg"); /* LosslessCompress(overlayFile); */ using (var tshirtImage = new MagickImage(tshirtFile)) { tshirtImage.Opaque(MagickColors.White, MagickColors.None); using (var overlayImage = new MagickImage(overlayFile)) { overlayImage.Crop(479, 479); var script = new TshirtScript(); script.Fit = TshirtFit.Crop; script.Blur = 0; script.Lighting = 0; script.Sharpen = 0; script.SetCoordinates(new MagickGeometry(275, 175, 130, 130)); using (var scriptOutput = script.Execute(tshirtImage, overlayImage)) { AssertOutput(scriptOutput, "flowers_van_gogh_alpha.jpg"); } } } }
private void crop_images() { foreach (var s in sheet.sprites) { using (MagickImage image_a = new MagickImage(alphaPath)) { using (MagickImage image_rgb = new MagickImage(rgbPath)) { var g = new ImageMagick.MagickGeometry(s.x, s.y, s.w, s.h); image_a.Crop(g); image_rgb.Crop(g); image_rgb.Composite(image_a, CompositeOperator.CopyAlpha); int i = 1; while (i < Math.Max(s.w, s.h)) { i = i * 2; } image_rgb.Extent(new MagickGeometry(-(i / 2 - s.w / 2), -(i / 2 - s.h / 2), i, i), MagickColor.FromRgba(255, 255, 255, 0)); image_rgb.Write(folderPath + "/" + s.n); } } //return; } }
public async Task <string> SavePasswordImageAsync(int par_PasswordId, IFormFile par_FormFile) { await semaphore.WaitAsync(); try { string sExt = Path.GetExtension(par_FormFile.FileName); string sPath = $"/Passwords/{par_PasswordId}{sExt}"; string sPhysicalPath = Path.Combine(par_WebHostEnvironment.WebRootPath, "Passwords", $"{par_PasswordId}{sExt}"); using Stream var_InputStream = par_FormFile.OpenReadStream(); using MagickImage var_Image = new MagickImage(var_InputStream); //manipolare immagine int iHeightImage = configuration.GetSection("SizeImage").GetValue <int>("Height"); int iWidthImage = configuration.GetSection("SizeImage").GetValue <int>("Width"); MagickGeometry var_MagickGeometry = new MagickGeometry(iWidthImage, iHeightImage); var_MagickGeometry.FillArea = true; var_Image.Resize(var_MagickGeometry); var_Image.Crop(iWidthImage, iHeightImage, Gravity.Northwest); var_Image.Quality = 70; var_Image.Write(sPhysicalPath, MagickFormat.Jpg); //restiture il percorso del file return(sPath); } finally { semaphore.Release(); } }
public static IMagickImage Crop(IMagickImage image, CropDimension cropDimensions) { var mImage = new MagickImage(image); mImage.Crop(cropDimensions.X, cropDimensions.Y, cropDimensions.Width, cropDimensions.Height); mImage.RePage(); return(mImage); }
private async Task <string> InsertImage(string imageName, string itemsHtml, int imageSize, int imageWidth, string basePicturePath) { var filePath = Path.Combine(basePicturePath, imageName); Stream stream; if (_swiftEnabled) { var storageResult = await _sdkCore.GetFileFromSwiftStorage(imageName); stream = storageResult.ObjectStreamContent; } else if (_s3Enabled) { var storageResult = await _sdkCore.GetFileFromS3Storage(imageName); stream = storageResult.ResponseStream; } else if (!File.Exists(filePath)) { return(null); // return new OperationDataResult<Stream>( // false, // _localizationService.GetString($"{imagesName} not found")); } else { stream = new FileStream(filePath, FileMode.Open, FileAccess.Read); } using (var image = new MagickImage(stream)) { var profile = image.GetExifProfile(); // Write all values to the console foreach (var value in profile.Values) { Console.WriteLine("{0}({1}): {2}", value.Tag, value.DataType, value.ToString()); } // image.AutoOrient(); decimal currentRation = image.Height / (decimal)image.Width; int newWidth = imageSize; int newHeight = (int)Math.Round((currentRation * newWidth)); image.Resize(newWidth, newHeight); image.Crop(newWidth, newHeight); if (newWidth > newHeight) { image.Rotate(90); } var base64String = image.ToBase64(); itemsHtml += $@"<p><img src=""data:image/png;base64,{base64String}"" width=""{imageWidth}px"" alt="""" /></p>"; } await stream.DisposeAsync(); return(itemsHtml); }
public void ShouldSetImageToCorrectDimensions() { using (var image = new MagickImage(Files.Builtin.Logo)) { image.Crop(40, 50); Assert.AreEqual(40, image.Width); Assert.AreEqual(50, image.Height); } }
public static void CropDivisible(string path, int divisibleBy, Gravity grav, bool expand) { MagickImage img = IOUtils.ReadImage(path); if (img == null) { return; } int divisbleWidth = img.Width; int divisibleHeight = img.Height; if (!expand) // Crop { while (divisbleWidth % divisibleBy != 0) { divisbleWidth--; } while (divisibleHeight % divisibleBy != 0) { divisibleHeight--; } } else // Expand { while (divisbleWidth % divisibleBy != 0) { divisbleWidth++; } while (divisibleHeight % divisibleBy != 0) { divisibleHeight++; } img.BackgroundColor = new MagickColor("#" + Config.Get("backgroundColor")); } if (divisbleWidth == img.Width && divisibleHeight == img.Height) { Program.Print("-> Skipping " + Path.GetFileName(path) + " as its resolution is already divisible by " + divisibleBy); } else { Program.Print("-> Divisible resolution: " + divisbleWidth + "x" + divisibleHeight); if (!expand) // Crop { img.Crop(divisbleWidth, divisibleHeight, grav); } else // Expand { img.Extent(divisbleWidth, divisibleHeight, grav); } img.RePage(); img.Write(path); } }
private string Process() { try { using (MagickImage srcMagickImage = new MagickImage(_inputFilePath)) { using (MagickImage sepiaImage = new MagickImage(new MagickColor(125, 125, 125, 55), srcMagickImage.Width, srcMagickImage.Height)) { sepiaImage.SepiaTone(new Percentage(92)); sepiaImage.Composite(srcMagickImage, CompositeOperator.Overlay); sepiaImage.BrightnessContrast(new Percentage(10), new Percentage(0)); using (Bitmap bitmap = new Bitmap(srcMagickImage.Width * 2, srcMagickImage.Height * 2)) { using (Graphics graphics = Graphics.FromImage(bitmap)) { Rectangle rectangle = new Rectangle(0, 0, srcMagickImage.Width * 2, srcMagickImage.Height * 2); GraphicsPath gp = new GraphicsPath(); gp.AddEllipse(rectangle); PathGradientBrush pgb = new PathGradientBrush(gp) { CenterPoint = new PointF(rectangle.Width / 2, rectangle.Height / 2), CenterColor = Color.White, SurroundColors = new Color[] { new MagickColor(0, 0, 0, 200) } }; graphics.FillPath(pgb, gp); bitmap.Save("gradientImage.jpg", ImageFormat.Jpeg); pgb.Dispose(); gp.Dispose(); } } using (MagickImage afterImage = new MagickImage("gradientImage.jpg")) { afterImage.Crop(afterImage.Width / 4, afterImage.Height / 4, afterImage.Width / 2, afterImage.Height / 2); sepiaImage.Composite(afterImage, CompositeOperator.ColorBurn); sepiaImage.Write(_outputFilePath); sepiaImage.Dispose(); return(string.Empty); } } } } catch (Exception e) { return(e.Message); } }
public void ShouldUseAspectRatioOfMagickGeometry() { using (IMagickImage image = new MagickImage(Files.Builtin.Logo)) { image.Crop(new MagickGeometry("3:2")); Assert.AreEqual(640, image.Width); Assert.AreEqual(427, image.Height); ColorAssert.AreEqual(MagickColors.White, image, 222, 0); } }
public void ShouldUseOffsetFromMagickGeometryAndGravity() { using (var image = new MagickImage(Files.Builtin.Logo)) { image.Crop(new MagickGeometry(10, 10, 100, 100), Gravity.Center); Assert.AreEqual(100, image.Width); Assert.AreEqual(100, image.Height); ColorAssert.AreEqual(MagickColors.White, image, 99, 99); } }
public void ShouldUseAspectRatioOfMagickGeometryAndGravity() { using (var image = new MagickImage(Files.Builtin.Logo)) { image.Crop(new MagickGeometry("3:2"), Gravity.South); Assert.AreEqual(640, image.Width); Assert.AreEqual(427, image.Height); ColorAssert.AreEqual(MagickColors.Red, image, 222, 0); } }
public void ShouldUseEastGravity() { using (var image = new MagickImage(Files.Builtin.Logo)) { image.Crop(50, 40, Gravity.East); Assert.AreEqual(50, image.Width); Assert.AreEqual(40, image.Height); ColorAssert.AreEqual(MagickColors.White, image, 25, 20); } }
public void ShouldUseCenterGravity() { using (var image = new MagickImage(Files.Builtin.Logo)) { image.Crop(50, 40, Gravity.Center); Assert.AreEqual(50, image.Width); Assert.AreEqual(40, image.Height); ColorAssert.AreEqual(new MagickColor("#223e92ff"), image, 25, 20); } }
public void ShouldUseUndefinedGravityAsTheDefault() { using (var image = new MagickImage(Files.Builtin.Logo)) { image.Crop(150, 40); Assert.AreEqual(150, image.Width); Assert.AreEqual(40, image.Height); ColorAssert.AreEqual(new MagickColor("#fecd08ff"), image, 146, 25); } }