public System.IO.Stream CombineImages(System.IO.Stream sourceImageStream, System.IO.Stream detailImageStream, Rect detailImageRect) { #region validation if (sourceImageStream == null) { throw new ArgumentNullException(nameof(sourceImageStream)); } if (detailImageStream == null) { throw new ArgumentNullException(nameof(detailImageStream)); } #endregion using (Image <Rgba32> sourceImage = LoadImageFromStream(sourceImageStream)) using (Image <Rgba32> detailImage = LoadImageFromStream(detailImageStream)) { SixLabors.Primitives.Point detailImagePosition = new SixLabors.Primitives.Point(0, 0); if (detailImageRect != null) { SixLabors.Primitives.Size detailImageSize = new SixLabors.Primitives.Size(detailImageRect.Width, detailImageRect.Height); detailImage.Mutate(x => x.Resize(detailImageSize)); detailImagePosition = new SixLabors.Primitives.Point(detailImageRect.X, detailImageRect.Y); } sourceImage.Mutate(x => x.DrawImage(detailImage, 1.0f, detailImagePosition)); return(SaveAsStream(sourceImage)); } }
private ResizeOptions ThumbnailResize(ImageType type, int width, int height) { var resize = new ResizeOptions(); var size = new SixLabors.Primitives.Size(); switch (type) { case ImageType.Profile: resize.Mode = ResizeMode.Crop; size.Width = Settings.Services.Images.ProfileThumbnailWidth; size.Height = Settings.Services.Images.ProfileThumbnailHeight; resize.Size = size; break; case ImageType.DorehamiAlbum: resize.Mode = ResizeMode.Crop; size.Width = Settings.Services.Images.DorehamiThumbnailWidth; size.Height = Settings.Services.Images.DorehamiThumbnailHeight; resize.Size = size; break; case ImageType.UnSet: throw new InvalidValueException(nameof(ImageType), type.ToString()); } return(resize); }
protected override IMAGE32 Evaluate() { var size = new SixLabors.Primitives.Size(Width, Height); var result = new IMAGE32(size.Width, size.Height); using (var target = new IMAGE32(size.Width, size.Height)) { var substrate = Epsylon.ImageSharp.Procedural.Processing.Substrate.Create(target, RandomSeed.GetRandomSeedHash(), Palette); for (int i = 0; i < Iterations; ++i) { this.SetProgressPercent(i * 100 / Iterations); substrate.DrawStep(); } result.Mutate ( dc => { dc.Fill(Rgba32.White); dc.DrawImage(target, 1); } ); return(result); } }
//public static IImageProcessingContext DrawTextWithHebrew( // this IImageProcessingContext source, // TextGraphicsOptions options, // string text, // Font font, // Color color, // PointF location) //{ // var textToApply = text; // return source.DrawText(options, textToApply, font, color, location); //} public static IImageProcessingContext DrawText( this IImageProcessingContext source, string text, int fontSize, string color, Size size, SixLabors.Primitives.Point location) { using var myBitmap = new Bitmap(size.Width, size.Height + 10); var x = new Span <char>(text.ToCharArray()); for (int i = x.Length - 1; i >= 0; i--) { if (char.IsPunctuation(x[i]) || char.IsSeparator(x[i]) || char.IsSymbol(x[i])) { x = x.Slice(0, i); } else { break; } } var textToDraw = new string(x); //pfcoll.AddFontFile(Server.MapPath("~/Fonts/" + fontName)); //FontFamily ff = pfcoll.Families[0]; var colorToWorkWith = ColorTranslator.FromHtml(color); using (var g = Graphics.FromImage(myBitmap)) { g.SmoothingMode = SmoothingMode.AntiAlias; g.TextRenderingHint = TextRenderingHint.AntiAlias; //var colorToWorkWith = System.Drawing.Color.FromArgb(color.ToArgb()); var brush = new System.Drawing.SolidBrush(colorToWorkWith); g.DrawString(textToDraw, new Font("Calibri", fontSize, FontStyle.Regular, GraphicsUnit.Pixel), brush, new RectangleF(0, 0, size.Width, size.Height), new StringFormat() { Alignment = StringAlignment.Center, Trimming = StringTrimming.Word, }); //g.DrawString("My Text very very nice", // new Font("Tahoma", 20), // Brushes.White, // new PointF(0, 0)); } using var ms = new MemoryStream(); myBitmap.Save(ms, ImageFormat.Png); var image = Image.Load(ms.ToArray()); return(source.DrawImage(image, location, GraphicsOptions.Default)); }
/// <summary> /// Calculates picture dimensions whilst maintaining aspect /// </summary> /// <param name="originalSize">The original picture size</param> /// <param name="targetSize">The target picture size (longest side)</param> /// <param name="resizeType">Resize type</param> /// <param name="ensureSizePositive">A value indicating whether we should ensure that size values are positive</param> /// <returns></returns> protected virtual Size CalculateDimensions(Size originalSize, int targetSize, ResizeType resizeType = ResizeType.LongestSide, bool ensureSizePositive = true) { float width, height; switch (resizeType) { case ResizeType.LongestSide: if (originalSize.Height > originalSize.Width) { // portrait width = originalSize.Width * (targetSize / (float)originalSize.Height); height = targetSize; } else { // landscape or square width = targetSize; height = originalSize.Height * (targetSize / (float)originalSize.Width); } break; case ResizeType.Width: width = targetSize; height = originalSize.Height * (targetSize / (float)originalSize.Width); break; case ResizeType.Height: width = originalSize.Width * (targetSize / (float)originalSize.Height); height = targetSize; break; default: throw new Exception("Not supported ResizeType"); } if (!ensureSizePositive) { return(new Size((int)Math.Round(width), (int)Math.Round(height))); } if (width < 1) { width = 1; } if (height < 1) { height = 1; } //we invoke Math.Round to ensure that no white background is rendered - https://www.nopcommerce.com/boards/t/40616/image-resizing-bug.aspx return(new Size((int)Math.Round(width), (int)Math.Round(height))); }
public void DrawImage(PointF position, SizeF size, ImageSharpTexture texture, float opacity) { var rect = ToRectangleF(new RectangleF(position, size), world); var s = new SixLabors.Primitives.Size((int)rect.Width, (int)rect.Height); var p = new SixLabors.Primitives.Point((int)rect.X, (int)rect.Y); commandQueue.Enqueue(ctx => { ctx.DrawImage(texture.Image, opacity, s, p); }); }
public static Stream ResizeImage(Image <Rgba32> fullSizeImage, decimal resizeWidth, decimal resizeHeight) { MemoryStream ms = new MemoryStream(); decimal rnd = Math.Min(resizeWidth / (decimal)fullSizeImage.Width, resizeHeight / (decimal)fullSizeImage.Height); var newSize = new SixLabors.Primitives.Size( (int)Math.Round(fullSizeImage.Width * rnd), (int)Math.Round(fullSizeImage.Height * rnd)); fullSizeImage.Mutate(ctx => ctx.Resize(newSize)); fullSizeImage.Save(ms, new JpegEncoder()); ms.Seek(0, SeekOrigin.Begin); return(ms); }
public static IImageProcessingContext ApplyRoundedCorners(this IImageProcessingContext ctx, float cornerRadius) { Size size = ctx.GetCurrentSize(); IPathCollection corners = BuildCorners(size.Width, size.Height, cornerRadius); var graphicOptions = new GraphicsOptions(true) { AlphaCompositionMode = PixelAlphaCompositionMode .DestOut // enforces that any part of this shape that has color is punched out of the background }; // mutating in here as we already have a cloned original // use any color (not Transparent), so the corners will be clipped return(ctx.Fill(graphicOptions, Rgba32.LimeGreen, corners)); }
public async Task Get(string key, string filtertype, int maxwidth) { try { var getResponse = await this.S3Client.GetObjectAsync(new GetObjectRequest { BucketName = this.BucketName, Key = key }); string strContentType = getResponse.Headers.ContentType; MemoryStream ms = new MemoryStream(); using (Stream responseStream = getResponse.ResponseStream) { using (Image <Rgba32> image = Image.Load(responseStream)) { var newSize = new SixLabors.Primitives.Size( (int)maxwidth, (int)(maxwidth / image.Width * image.Height)); image.Mutate(ctx => ctx.Resize(newSize)); FilterImage(image, filtertype); strContentType = "image/jpeg"; image.Save(ms, new JpegEncoder()); ms.Seek(0, SeekOrigin.Begin); } } this.Response.ContentLength = ms.Length; this.Response.ContentType = strContentType; ms.CopyTo(this.Response.Body); } catch (AmazonS3Exception e) { this.Response.StatusCode = (int)e.StatusCode; var writer = new StreamWriter(this.Response.Body); writer.Write(e.Message); } catch (Exception ex) { this.Response.StatusCode = 500; var writer = new StreamWriter(this.Response.Body); writer.Write(ex.Message); } }
public byte[] TransformIntoCircle(byte[] image) { //doc: https://github.com/SixLabors/Samples/blob/master/ImageSharp/AvatarWithRoundedCorner/Program.cs byte[] retImageBytes; using (var img = Image.Load(image)) { var breadth = img.Width > img.Height ? img.Height : img.Width; var cornerRadius = breadth / 2; var size = new Size(breadth, breadth); using (var cropped = img.Clone(x => WindowsImageUtility.ConvertToAvatar(x, size, cornerRadius))) { using (var memoryStream = new MemoryStream()) { cropped.SaveAsPng(memoryStream); retImageBytes = memoryStream.ToArray(); } } } return(retImageBytes); }
public async Task <MemoryStream> Swap(IList <byte[]> images) { var imgs = images.Select(image => Mat.FromImageData(image)).ToList(); var facesLookup = (await DetectFaces(imgs)); if (facesLookup.Count < 2) { throw new Exception("not enough faces"); } var img1 = facesLookup.First(); var img2 = facesLookup.Last(); var output1 = Swap(img1.Key, img1.First(), img2.Key, img2.Last()); var output2 = Swap(img2.Key, img2.Last(), img1.Key, img1.First()); output1.Mutate(i => { var currentSize = output1.Size(); var newSizeVert = new Size(Math.Max(output1.Width, output2.Width), output1.Height + output2.Height); var newSizeHor = new Size(output1.Width + output2.Width, Math.Max(output1.Height, output2.Height)); var(newSize, location) = newSizeVert.Height + newSizeVert.Width > newSizeHor.Height + newSizeHor.Width ? (newSizeHor, new SixLabors.Primitives.Point(currentSize.Width, 0)) : (newSizeVert, new SixLabors.Primitives.Point(0, currentSize.Height)); i.Resize(new ResizeOptions { Mode = ResizeMode.BoxPad, Size = newSize, Position = AnchorPositionMode.TopLeft }); i.DrawImage(output2, 1, location); }); var output = new MemoryStream(); output1.SaveAsJpeg(output); output.Seek(0, SeekOrigin.Begin); return(output); }
public async Task <List <MultipleImagesResponseModel> > UploadMultipleSavingValid(List <IFormFile> images, ImageType type) { try { // Define image uploading sizes var uploadingSize = GetSize(type); var result = new List <MultipleImagesResponseModel>(); // If image doesn`t pass at least one check - change status and pass to next iteration foreach (var y in images) { // Add name to show wich image incorrect var data = new MultipleImagesResponseModel { Name = y.FileName }; result.Add(data); var extention = Path.GetExtension(y.FileName).ToLower(); if (y.Length > MAX_FILE_SIZE) { data.Status = ImageSaveStatus.InvalidLength; continue; } if (!EXTENTIONS.Contains(extention)) { data.Status = ImageSaveStatus.InvalidFormat; continue; } var response = new ImageResponseModel(); using (var fileStream = y.OpenReadStream()) { var fileInfo = SixLabors.ImageSharp.Image.Identify(fileStream); // Restriction for server correct work if (fileInfo.Width > MAX_IMAGE_SIDE || fileInfo.Height > MAX_IMAGE_SIDE) { data.Status = ImageSaveStatus.InvalidSize; continue; } // Set default image dimention var compactSize = new SixLabors.Primitives.Size { Height = fileInfo.Height, Width = fileInfo.Width }; switch (type) { case ImageType.Square: if (fileInfo.Width < MIN_IMAGE_WIDTH || fileInfo.Height < MIN_IMAGE_HEIGHT) { data.Status = ImageSaveStatus.InvalidDimension; continue; } if (Math.Abs(fileInfo.Width - fileInfo.Height) > 0) { data.Status = ImageSaveStatus.InvalidDimension; continue; } if (fileInfo.Width > IMAGE_COMPACT_WIDTH || fileInfo.Height > IMAGE_COMPACT_HEIGHT) { compactSize.Width = IMAGE_COMPACT_WIDTH; compactSize.Height = IMAGE_COMPACT_HEIGHT; } break; case ImageType.Normal: if (fileInfo.Height < MIN_IMAGE_HEIGHT || fileInfo.Width < MIN_IMAGE_WIDTH) { data.Status = ImageSaveStatus.InvalidDimension; continue; } // Passing zero for one of height or width will automatically preserve the aspect ratio of the original image if (fileInfo.Width > IMAGE_COMPACT_WIDTH || fileInfo.Height > IMAGE_COMPACT_HEIGHT) { if (fileInfo.Width > fileInfo.Height) { compactSize.Width = IMAGE_COMPACT_WIDTH; compactSize.Height = 0; } else { compactSize.Height = IMAGE_COMPACT_HEIGHT; compactSize.Width = 0; } } break; } response = await Save(fileStream, y.FileName, uploadingSize, compactSize); // In case of succes change status and return image response model data.Status = ImageSaveStatus.Saved; data.Image = _mapper.Map <ImageResponseModel>(response); } } // Throw an exception there are no valid images if (result.Any(x => x.Status == ImageSaveStatus.Saved)) { return(result); } else { throw new CustomException(HttpStatusCode.BadRequest, "images", "No image has been saved"); } } catch (Exception ex) { throw new CustomException(HttpStatusCode.BadRequest, "images", ex.InnerException?.Message ?? ex.Message); } }
private async Task <ImageResponseModel> Save(Stream fileStream, string fileName, ImageUploadingSize uploadingSize, SixLabors.Primitives.Size compactSize) { var response = new Domain.Entities.Image(); fileStream.Seek(0, SeekOrigin.Begin); using (var image = SixLabors.ImageSharp.Image.Load(fileStream, out IImageFormat format)) { var key = Guid.NewGuid().ToString(); var ext = Path.GetExtension(fileName); if (uploadingSize != ImageUploadingSize.Compact) { response.OriginalPath = "Test"; } //response.OriginalPath = await _s3Service.UploadFile(fileStream, key + ext); if (uploadingSize != ImageUploadingSize.Normal) { using (var memoryStream = new MemoryStream()) { image.Mutate(x => x.Resize(compactSize)); image.Save(memoryStream, format); key += COMPACT_KEY; response.CompactPath = "Test_min"; //response.CompactPath = await _s3Service.UploadFile(memoryStream, key + ext); } } } response.IsActive = true; _unitOfWork.Repository <Image>().Insert(response); _unitOfWork.SaveChanges(); return(_mapper.Map <ImageResponseModel>(response)); }
private SixLabors.Primitives.Size GetCompactImageSize(int width, int height, ImageType type, string fileName) { // Restriction for server correct work if (width > MAX_IMAGE_SIDE || height > MAX_IMAGE_SIDE) { throw new CustomException(HttpStatusCode.BadRequest, "Image", $"{fileName} Maximum image side is {MAX_IMAGE_SIDE} px"); } // Set default image dimention SixLabors.Primitives.Size res = new SixLabors.Primitives.Size { Height = height, Width = width }; switch (type) { case ImageType.Square: if (width < MIN_IMAGE_WIDTH || height < MIN_IMAGE_HEIGHT) { throw new CustomException(HttpStatusCode.BadRequest, "Image", $"{fileName} Invalid image dimension {MIN_IMAGE_WIDTH}x{MIN_IMAGE_HEIGHT}"); } if (Math.Abs(width - height) > 0) { throw new CustomException(HttpStatusCode.BadRequest, "Image", $"{fileName} Invalid image dimension"); } if (width > IMAGE_COMPACT_WIDTH || height > IMAGE_COMPACT_HEIGHT) { res.Width = IMAGE_COMPACT_WIDTH; res.Height = IMAGE_COMPACT_HEIGHT; } break; case ImageType.Normal: if (height < MIN_IMAGE_HEIGHT || width < MIN_IMAGE_WIDTH) { throw new CustomException(HttpStatusCode.BadRequest, "Image", $"{fileName} Invalid image dimension"); } // Passing zero for one of height or width will automatically preserve the aspect ratio of the original image if (width > IMAGE_COMPACT_WIDTH || height > IMAGE_COMPACT_HEIGHT) { if (width > height) { res.Width = IMAGE_COMPACT_WIDTH; res.Height = 0; } else { res.Height = IMAGE_COMPACT_HEIGHT; res.Width = 0; } } break; } return(res); }
private static IImageProcessingContext <Rgba32> ConvertToAvatar(IImageProcessingContext <Rgba32> processingContext, Size size, float cornerRadius) { return(processingContext.Resize(new ResizeOptions { Size = size, Mode = ResizeMode.Crop }).Apply(i => ApplyRoundedCorners(i, cornerRadius))); }