public static Image ResizeImage(Image source, Size size, ResizeOptions options) { double rate = CalculateResizeRate(source, size, options); Size newSize = new Size((int)(source.Width * rate), (int)(source.Height * rate)); Bitmap bitmap = new Bitmap(source, newSize); return (Image)bitmap; }
/// <summary> /// Resize started /// </summary> /// <param name="content"></param> /// <param name="options"></param> public override void OnResizeStart(ISmartContent content, ResizeOptions options) { // Check if we have editor mode element ID if (content.Properties.Contains(_elementIdProperty)) { string elementId = content.Properties.GetString(_elementIdProperty, null); if (elementId != null) { options.ResizeableElementId = elementId; } } }
public double CalculateResizeRate(string imageUrl, Size size, ResizeOptions resizeOption) { double rate = 1.0; byte[] imageContent; using (WebClient client = new WebClient()) { imageContent = client.DownloadData(Server.UrlDecode(imageUrl)); } using (MemoryStream ms = new MemoryStream(imageContent)) { Image image = Image.FromStream(ms); rate = ImageProcessor.CalculateResizeRate(image, size, resizeOption); } return rate; }
public static double CalculateResizeRate(Image image, Size size, ResizeOptions option) { double widthRate = (double)size.Width / image.Size.Width; double heightRate = (double)size.Height / image.Size.Height; double result = 1.0; switch (option) { case ResizeOptions.Fit: result = Math.Min(heightRate, widthRate); break; case ResizeOptions.Fill: result = Math.Max(heightRate, widthRate); break; } return Math.Min(result, 1.0); }
public virtual FileAndDir SaveBitmapImage(Stream stream, ResizeOptions ro, string ext) { using (Image <Rgba32> image = Image.Load(stream)) { var fileAndDir = imagesNamesService.GetNewImageNameAndDir(ext); var dirFullPath = Path.Combine(env.WebRootPath, imagesOptions.UploadDir, fileAndDir.Dir); lock (lockObject) if (!Directory.Exists(dirFullPath)) { Directory.CreateDirectory(dirFullPath); } var fullFileName = Path.Combine(dirFullPath, fileAndDir.File); image.Mutate(x => x.Resize(ro)); image.Save(fullFileName); return(fileAndDir); } }
private void ApplyFitWithLetterbox(IImageProcessingContext <Rgba32> context, Rectangle area, Image <Rgba32> image) { using (var img2 = image.Clone()) { img2.Mutate(ctx => { var resizeOptions = new ResizeOptions { Mode = ResizeMode.Max, Compand = false, Sampler = area.Width > image.Width ? (IResampler) new BicubicResampler() : new BoxResampler(), Size = area.Size }; ctx.Resize(resizeOptions); }); var sx = area.X + (area.Width - img2.Width) / 2; var sy = area.Y + (area.Height - img2.Height) / 2; context.DrawImage(img2, new Point(sx, sy), _graphicsOptions); } }
Stream GetResizedStream(Stream stream, decimal scalingFactor, string mimeType) { using (Image <Rgba32> image = Image.Load(stream)) { var resizeOptions = new ResizeOptions { Size = new SixLabors.Primitives.Size { Width = Convert.ToInt32(image.Width * scalingFactor), Height = Convert.ToInt32(image.Height * scalingFactor) }, Mode = ResizeMode.Stretch }; image.Mutate(x => x.Resize(resizeOptions)); var memoryStream = new MemoryStream(); image.Save(memoryStream, mimeType.AsEncoder()); return(memoryStream); } }
public override async Task <ActionResult <string> > HandleAsync([FromRoute] int trailId, CancellationToken cancellationToken = default) { var trail = await _database.Trails.SingleOrDefaultAsync(x => x.Id == trailId, cancellationToken); if (trail is null) { return(BadRequest("Trail does not exist.")); } var file = Request.Form.Files[0]; if (file.Length == 0) { return(BadRequest("No image found.")); } var filename = $"{Guid.NewGuid()}.jpg"; var saveLocation = Path.Combine(Directory.GetCurrentDirectory(), "Images", filename); var resizeOptions = new ResizeOptions { Mode = ResizeMode.Pad, Size = new Size(640, 426) }; using var image = Image.Load(file.OpenReadStream()); image.Mutate(x => x.Resize(resizeOptions)); await image.SaveAsJpegAsync(saveLocation, cancellationToken : cancellationToken); if (!string.IsNullOrWhiteSpace(trail.Image)) { System.IO.File.Delete(Path.Combine(Directory.GetCurrentDirectory(), "Images", trail.Image)); } trail.Image = filename; await _database.SaveChangesAsync(cancellationToken); return(Ok(trail.Image)); }
/// <summary> /// Gets the size of the preferred. /// </summary> /// <param name="options">The options.</param> /// <param name="image">The image.</param> /// <returns></returns> private Size GetPreferredSize(ResizeOptions options, Image image) { if (options.Scale > 0f) { return(new Size(this.Scale(image.Width, options.Scale), this.Scale(image.Height, options.Scale))); } if (options.Size.IsEmpty || (options.Size == image.Size)) { return(new Size(image.Size.Width, image.Size.Height)); } if (options.Size.Width == 0) { float scale = ((float)options.Size.Height) / ((float)image.Height); return(new Size(this.Scale(image.Width, scale), options.Size.Height)); } if (options.Size.Height == 0) { float num2 = ((float)options.Size.Width) / ((float)image.Width); return(new Size(options.Size.Width, this.Scale(image.Height, num2))); } return(new Size(options.Size.Width, options.Size.Height)); }
public void ImageShouldResizeWithPadMode(string name, IResampler sampler) { name = $"{name}-Pad"; string path = this.CreateOutputDirectory("Resize"); foreach (TestFile file in Files) { string filename = file.GetFileName(name); using (Image image = file.CreateImage()) using (FileStream output = File.OpenWrite($"{path}/{filename}")) { ResizeOptions options = new ResizeOptions { Size = new Size(image.Width + 200, image.Height), Mode = ResizeMode.Pad }; image.Resize(options).Save(output); } } }
public void ImageShouldResizeWithCropHeightMode(string name, IResampler sampler) { name = $"{name}-CropHeight"; string path = this.CreateOutputDirectory("Resize"); foreach (TestFile file in Files) { string filename = file.GetFileName(name); using (Image <Rgba32> image = file.CreateImage()) using (FileStream output = File.OpenWrite($"{path}/{filename}")) { ResizeOptions options = new ResizeOptions { Sampler = sampler, Size = new Size(image.Width, image.Height / 2) }; image.Resize(options).Save(output); } } }
public Task CreateThumbnailAsync(Stream source, Stream destination, int?width, int?height, string mode) { return(Task.Run(() => { if (width == null && height == null) { source.CopyTo(destination); return; } if (!Enum.TryParse <ResizeMode>(mode, true, out var resizeMode)) { resizeMode = ResizeMode.Max; } var w = width ?? int.MaxValue; var h = height ?? int.MaxValue; using (var sourceImage = Image.Load(source)) { if (w >= sourceImage.Width && h >= sourceImage.Height && resizeMode == ResizeMode.Crop) { resizeMode = ResizeMode.BoxPad; } var options = new ResizeOptions { Size = new Size(w, h), Mode = resizeMode }; sourceImage.MetaData.Quality = 0; sourceImage.Resize(options).Save(destination); } })); }
/// <summary> /// Transforms an image to add a watermark. /// </summary> /// <param name="input"></param> /// <param name="output"></param> /// <param name="waterMarkText"></param> public async Task TransformDownloadImage(string input, Stream output, IExportSettings config) { Logging.Log($" Running image transform for Watermark: {config.WatermarkText}"); using var img = Image.Load(input, out IImageFormat fmt); if (config.Size != ExportSize.FullRes) { int maxSize = config.MaxImageSize; var opts = new ResizeOptions { Mode = ResizeMode.Max, Size = new Size { Height = maxSize, Width = maxSize }, Sampler = KnownResamplers.Lanczos3 }; // Rotate and resize. img.Mutate(x => x.AutoOrient().Resize(opts)); } else { // Just rotate. img.Mutate(x => x.AutoOrient()); } if (!string.IsNullOrEmpty(config.WatermarkText) && fontCollection != null) { // Apply the watermark if one's been specified. var fontFamily = fontCollection.Get("Arial"); var font = fontFamily.CreateFont(10); img.Mutate(context => ApplyWaterMark(context, font, config.WatermarkText, Color.White)); } await img.SaveAsync(output, fmt); }
public async Task SubscribeAndUnsubcribe_SingleSubscription() { var customResizeOptioons = new ResizeOptions(); Action <ListenForResizeCallbackInfo> feedbackCaller = (x) => { if (x.ListenerId == default) { throw new ArgumentException(); } SetupJsMockForUnsubscription(x.ListenerId); }; SetupJsMockForSubscription(customResizeOptioons, feedbackCaller); var subscriptionId = await _service.Subscribe((BrowserWindowSize size) => { }, null); var result = await _service.Unsubscribe(subscriptionId); result.Should().BeTrue(); _jsruntimeMock.Verify(); }
public void ImageShouldResizeWithMinMode(string name, IResampler sampler) { name = $"{name}-Min"; string path = this.CreateOutputDirectory("Resize"); foreach (TestFile file in Files) { string filename = file.GetFileName(name); using (Image image = file.CreateImage()) using (FileStream output = File.OpenWrite($"{path}/{filename}")) { ResizeOptions options = new ResizeOptions { Sampler = sampler, Size = new Size((int)Math.Round(image.Width * .75F), (int)Math.Round(image.Height * .95F)), Mode = ResizeMode.Min }; image.Resize(options).Save(output); } } }
public static bool SaveImageThumbnail(string path, string thumbnailPath, int width, int height) { try { using (Image <Rgba32> image = Image.Load(path)) { if (image == null) { return(false); } ResizeOptions options = new ResizeOptions(); options.Mode = ResizeMode.BoxPad; options.Size = new Size(width, height); image.Mutate(x => x.Resize(options)); image.Save(thumbnailPath); } } catch { return(false); } return(true); }
public RenderTexture Resize(Texture texture, ResizeOptions options) { if (resizeTexture == null || resizeTexture.width != options.width || resizeTexture.height != options.height) { TryDispose(resizeTexture); resizeTexture = new RenderTexture(options.width, options.height, 0, GraphicsFormat.R16G16B16A16_SFloat); } if (transfromMat == null) { transfromMat = new Material(Shader.Find("Hidden/Barracuda/Resize")); } // Set options float rotation = options.rotationDegree; if (texture is WebCamTexture) { var webcamTex = (WebCamTexture)texture; rotation += webcamTex.videoRotationAngle; if (webcamTex.videoVerticallyMirrored) { options.flipX = !options.flipX; } } Matrix4x4 trs = GetVertTransform(rotation, options.flipX, options.flipY); transfromMat.SetMatrix(_VertTransform, trs); transfromMat.SetVector(_UVRect, GetTextureST( (float)texture.width / (float)texture.height, // src (float)options.width / (float)options.height, // dst options.aspectMode)); Graphics.Blit(texture, resizeTexture, transfromMat, 0); return(resizeTexture); }
public async Task <IActionResult> UpdateOtherPicturesAsync() { var spec = new CatalogFilterSpecification(false); var products = await _catalogRepository.ListAsync(spec); foreach (var item in products) { foreach (var other in item.Pictures.Where(x => !x.IsMain).ToList()) { if (!string.IsNullOrEmpty(other.PictureHighUri)) { Uri uri = new Uri(other.PictureHighUri); var fileName = Path.GetFileName(uri.LocalPath); var originalPath = Path.Combine(_backofficeSettings.WebProductsPictureFullPath, fileName); var newFileName = Utils.URLFriendly(Path.GetFileNameWithoutExtension(uri.LocalPath)) + Path.GetExtension(uri.LocalPath); var newPath = Path.Combine(_backofficeSettings.WebProductsPictureV2FullPath, newFileName); using (Image image = Image.Load(originalPath)) { var options = new ResizeOptions { Mode = ResizeMode.Crop, Size = new Size(700, 700) }; image.Mutate(x => x.Resize(options)); image.Save(newPath, new JpegEncoder { Quality = 90 }); // Automatic encoder selected based on extension. } other.UpdatePictureUri(_backofficeSettings.WebProductsPictureV2Uri + newFileName); } } await _catalogRepository.UpdateAsync(item); } return(Ok()); }
internal static float DetermineDownsampleRatio( ImageRequest imageRequest, EncodedImage encodedImage) { Preconditions.CheckArgument(EncodedImage.IsMetaDataAvailable(encodedImage)); ResizeOptions resizeOptions = imageRequest.ResizeOptions; if (resizeOptions == null || resizeOptions.Height <= 0 || resizeOptions.Width <= 0 || encodedImage.Width == 0 || encodedImage.Height == 0) { return(1.0f); } int rotationAngle = GetRotationAngle(imageRequest, encodedImage); bool swapDimensions = rotationAngle == 90 || rotationAngle == 270; int widthAfterRotation = swapDimensions ? encodedImage.Height : encodedImage.Width; int heightAfterRotation = swapDimensions ? encodedImage.Width : encodedImage.Height; float widthRatio = ((float)resizeOptions.Width) / widthAfterRotation; float heightRatio = ((float)resizeOptions.Height) / heightAfterRotation; float ratio = Math.Max(widthRatio, heightRatio); Debug.Write(string.Format( "Downsample - Specified size: {0}x{1}, image size: {2}x{3} ratio: {4} x {5}, ratio: {6} for {7}", resizeOptions.Width, resizeOptions.Height, widthAfterRotation, heightAfterRotation, widthRatio, heightRatio, ratio, imageRequest.SourceUri.ToString())); return(ratio); }
/// <summary> /// Limits the size of to max. /// </summary> /// <param name="options">The options.</param> /// <param name="size">The size.</param> /// <returns></returns> private static Size LimitToMaxSize(ResizeOptions options, Size size) { if (!options.MaxSize.IsEmpty) { if ((options.MaxSize.Width > 0) && (size.Width > options.MaxSize.Width)) { if (options.Size.Height == 0) { size.Height = (int)Math.Round((double)((((float)options.MaxSize.Width) / ((float)size.Width)) * size.Height)); } size.Width = options.MaxSize.Width; } if ((options.MaxSize.Height <= 0) || (size.Height <= options.MaxSize.Height)) { return(size); } if (options.Size.Width == 0) { size.Width = (int)Math.Round((double)((((float)options.MaxSize.Height) / ((float)size.Height)) * size.Width)); } size.Height = options.MaxSize.Height; } return(size); }
public MemoryStream StreamImageConvertAndResizeAndCompress(Stream data) { data.Position = 0; using Image <Rgba32> image = Image.Load(data); ResizeOptions resizeOptions = new ResizeOptions(); resizeOptions.Size = new SixLabors.Primitives.Size(500, 500); resizeOptions.Position = AnchorPositionMode.Center; resizeOptions.Mode = ResizeMode.Max; image.Mutate(x => x .Resize(resizeOptions) ); var memoryStream = new MemoryStream(); image.SaveAsJpeg(memoryStream, new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder() { Quality = 100 } ); // Automatic encoder selected based on extension. memoryStream.Position = 0; return(memoryStream); }
public static IImageEncoder GetEncoder(this ResizeOptions options, IImageFormat format) { var imageFormatsManager = Configuration.Default.ImageFormatsManager; if (options.Format != null) { format = imageFormatsManager.FindFormatByMimeType(options.Format.Value.ToMimeType()) ?? format; } var encoder = imageFormatsManager.FindEncoder(format); if (encoder == null) { throw new NotSupportedException(); } if (encoder is PngEncoder png && png.ColorType != PngColorType.RgbWithAlpha) { encoder = new PngEncoder { ColorType = PngColorType.RgbWithAlpha }; } var quality = options.Quality ?? 80; if (encoder is JpegEncoder jpg && jpg.Quality != quality) { encoder = new JpegEncoder { Quality = quality }; } return(encoder); }
public void ImageShouldResizeWithCropWidthMode(string name, IResampler sampler) { name = name + "-CropWidth"; string path = CreateOutputDirectory("Resize"); foreach (TestFile file in Files) { string filename = file.GetFileName(name); Image image = file.CreateImage(); using (FileStream output = File.OpenWrite($"{path}/{filename}")) { ResizeOptions options = new ResizeOptions() { Sampler = sampler, Size = new Size(image.Width / 2, image.Height) }; image.Resize(options) .Save(output); } } }
private MemoryStream ResizeImage(Stream stream, Size size) { MemoryStream outStream = new MemoryStream(); using (var image = Image.Load(stream)) { var options = new ResizeOptions() { Mode = ResizeMode.Min, Size = new SixLabors.Primitives.Size(size.Width, size.Height) }; // Load, resize, set the format, and quality and save an image. image.Mutate(x => x .Resize(options)); image.Save(outStream, new JpegEncoder() { Quality = 70 }); return(outStream); } }
public ImageViewModel(TViewModel viewModel, byte[] image) { if (viewModel == null) { throw new ArgumentNullException(nameof(viewModel)); } if (image == null) { throw new ArgumentNullException(nameof(image)); } ViewModel = viewModel; IImageFormat imageFormat; using (Image <Rgba32> sourceImage = Image.Load(image, out imageFormat)) { OriginalMimeType = imageFormat.DefaultMimeType; OriginalImageAsBase64 = sourceImage.ToBase64String(imageFormat); int centerX = sourceImage.Width / 2; int centerY = sourceImage.Height / 2; ResizeOptions resizeOptions = new ResizeOptions { Compand = false, Mode = ResizeMode.Crop, Size = new Size(MaxWidth, MaxHeight) }; using (Image <Rgba32> targetImage = sourceImage.Clone(img => img.Resize(resizeOptions))) { TransformedMimeType = imageFormat.DefaultMimeType; TransformedImageAsBase64 = targetImage.ToBase64String(imageFormat); } } }
// 너무 큰 이미지를 작은 이미지로 줄이면서 PNG 파일이 아니면 PNG로 바꾼다. static string ExecuteResizeAndSaveAsPng(string sourceFileName, int threshold) { Logger.WriteLine($"Running {nameof(ExecuteResizeAndSaveAsPng)}"); using var image = Image.Load <Rgba32>(sourceFileName); // 정사각형이 아니라면 우선 큰 변 기준으로 정사각형으로 만든다. (여백 추가) if (image.Width != image.Height) { var maxSide = Math.Max(image.Width, image.Height); var options = new ResizeOptions { Size = new Size(maxSide, maxSide), Mode = ResizeMode.BoxPad, Sampler = new NearestNeighborResampler() }; image.Mutate(x => x.Resize(options)); } if (image.Width > threshold) { var options = new ResizeOptions { Size = new Size(threshold, threshold), Mode = ResizeMode.BoxPad }; image.Mutate(x => x.Resize(options)); } var targetFileName = AppendToFileName(sourceFileName, "", ".png", outputNewFileName); image.Save(targetFileName, new PngEncoder()); return(targetFileName); }
public static void Resize(string pathSource, int newWidth, int newHeight, string pathDestiny) { if (File.Exists(pathDestiny)) { return; } var resizeOptions = new ResizeOptions { Mode = ResizeMode.Max, Size = new Size(newWidth, newHeight) }; using (var image = Image.Load(pathSource)) using (var thumbnail = image.Clone(operation => operation.Resize(resizeOptions))) { var directoryDestiny = Path.GetDirectoryName(pathDestiny); if (!Directory.Exists(directoryDestiny)) { Directory.CreateDirectory(directoryDestiny); } thumbnail.Save(pathDestiny); } }
public byte[] ConstrainResize(byte[] bytes, int maxWidth, int maxHeight, int qualityLevel) { if (bytes == null) { throw new Exception("Bytes parameter is null."); } using (var stream = new MemoryStream(bytes)) using (var image = Image.Load <Rgba32>(stream)) using (var output = new MemoryStream()) { var options = new ResizeOptions { Size = new Size(maxWidth, maxHeight), Mode = ResizeMode.Max }; image.Mutate(x => x .Resize(options) .GaussianSharpen(0.5f)); image.Save(output, new JpegEncoder { Quality = qualityLevel }); return(output.ToArray()); } }
/// <summary> /// Limits the size of to max. /// </summary> /// <param name="options">The options.</param> /// <param name="size">The size.</param> /// <returns></returns> private static Size LimitToMaxSize(ResizeOptions options, Size size) { if (!options.MaxSize.IsEmpty) { if ((options.MaxSize.Width > 0) && (size.Width > options.MaxSize.Width)) { if (options.Size.Height == 0) { size.Height = (int)Math.Round((double)((((float)options.MaxSize.Width) / ((float)size.Width)) * size.Height)); } size.Width = options.MaxSize.Width; } if ((options.MaxSize.Height <= 0) || (size.Height <= options.MaxSize.Height)) { return size; } if (options.Size.Width == 0) { size.Width = (int)Math.Round((double)((((float)options.MaxSize.Height) / ((float)size.Height)) * size.Width)); } size.Height = options.MaxSize.Height; } return size; }
public async Task CreateThumbnailAsync(Stream source, string mimeType, Stream destination, ResizeOptions options, CancellationToken ct = default) { Guard.NotNull(source, nameof(source)); Guard.NotNull(destination, nameof(destination)); Guard.NotNull(options, nameof(options)); if (!options.IsValid) { await source.CopyToAsync(destination, ct); return; } var w = options.TargetWidth ?? 0; var h = options.TargetHeight ?? 0; using (var collection = new MagickImageCollection()) { await collection.ReadAsync(source, GetFormat(mimeType), ct); collection.Coalesce(); foreach (var image in collection) { var clone = image.Clone(); var color = options.ParseColor(); if (w > 0 || h > 0) { var isCropUpsize = options.Mode == ResizeMode.CropUpsize; var resizeMode = options.Mode; if (isCropUpsize) { resizeMode = ResizeMode.Crop; } if (w >= image.Width && h >= image.Height && resizeMode == ResizeMode.Crop && !isCropUpsize) { resizeMode = ResizeMode.BoxPad; } PointF?centerCoordinates = null; if (options.FocusX.HasValue && options.FocusY.HasValue) { centerCoordinates = new PointF( +(options.FocusX.Value / 2f) + 0.5f, -(options.FocusY.Value / 2f) + 0.5f ); } var(size, pad) = ResizeHelper.CalculateTargetLocationAndBounds(resizeMode, new Size(image.Width, image.Height), w, h, centerCoordinates); var sourceRectangle = new MagickGeometry(pad.Width, pad.Height) { IgnoreAspectRatio = true }; clone.Resize(sourceRectangle); image.Extent(size.Width, size.Height); image.CompositeClear(color); image.Composite(clone, pad.X, pad.Y, CompositeOperator.Over); } else { image.CompositeClear(color); image.Composite(clone, 0, 0, CompositeOperator.Over); } image.AutoOrient(); if (options.Quality.HasValue) { image.Quality = options.Quality.Value; } } var firstImage = collection[0]; var firstFormat = firstImage.Format; var targetFormat = options.GetFormat(firstFormat); await collection.WriteAsync(destination, targetFormat, ct); } }
public Task CreateThumbnailAsync(Stream source, Stream destination, ResizeOptions options) { Guard.NotNull(options); return(Task.Run(() => { var w = options.Width ?? 0; var h = options.Height ?? 0; if (w <= 0 && h <= 0 && !options.Quality.HasValue) { source.CopyTo(destination); return; } using (var sourceImage = Image.Load(source, out var format)) { var encoder = Configuration.Default.ImageFormatsManager.FindEncoder(format); if (options.Quality.HasValue) { encoder = new JpegEncoder { Quality = options.Quality.Value }; } if (encoder == null) { throw new NotSupportedException(); } if (w > 0 || h > 0) { var isCropUpsize = options.Mode == ResizeMode.CropUpsize; if (!Enum.TryParse <ISResizeMode>(options.Mode.ToString(), true, out var resizeMode)) { resizeMode = ISResizeMode.Max; } if (isCropUpsize) { resizeMode = ISResizeMode.Crop; } if (w >= sourceImage.Width && h >= sourceImage.Height && resizeMode == ISResizeMode.Crop && !isCropUpsize) { resizeMode = ISResizeMode.BoxPad; } var resizeOptions = new ISResizeOptions { Size = new Size(w, h), Mode = resizeMode }; if (options.FocusX.HasValue && options.FocusY.HasValue) { resizeOptions.CenterCoordinates = new float[] { +(options.FocusX.Value / 2f) + 0.5f, -(options.FocusX.Value / 2f) + 0.5f }; } sourceImage.Mutate(x => x.Resize(resizeOptions)); } sourceImage.Save(destination, encoder); } })); }
private ResizeOptions ToResizeOptions(Image <Rgba32> image, ImageResizeOptions resizeOptions) { ResizeMode mode; switch (resizeOptions.Mode) { case ImageResizeMode.PreserveAspectRatio: mode = ResizeMode.Max; break; case ImageResizeMode.IgnoreAspectRatio: mode = ResizeMode.Stretch; break; case ImageResizeMode.ShrinkLarger: mode = ResizeMode.Min; break; case ImageResizeMode.Fill: mode = ResizeMode.Min; break; default: throw new NotImplementedException(); } var resizeOptionsResult = new ResizeOptions { Size = new Size(resizeOptions.Width, resizeOptions.Height), Mode = mode }; switch (resizeOptions.Resampler) { // https://www.imagemagick.org/discourse-server/viewtopic.php?t=15742 case Resampler.Auto: { if (image.Width < resizeOptions.Width) { resizeOptionsResult.Sampler = new MitchellNetravaliResampler(); break; } // TODO split resizeOptionsResult.Sampler = new Lanczos2Resampler(); break; } case Resampler.Bicubic: resizeOptionsResult.Sampler = new BicubicResampler(); break; case Resampler.Box: resizeOptionsResult.Sampler = new BoxResampler(); break; case Resampler.CatmullRom: resizeOptionsResult.Sampler = new CatmullRomResampler(); break; case Resampler.Hermite: resizeOptionsResult.Sampler = new HermiteResampler(); break; case Resampler.MitchellNetravali: resizeOptionsResult.Sampler = new MitchellNetravaliResampler(); break; case Resampler.NearestNeighbor: resizeOptionsResult.Sampler = new NearestNeighborResampler(); break; case Resampler.Robidoux: resizeOptionsResult.Sampler = new RobidouxResampler(); break; case Resampler.RobidouxSharp: resizeOptionsResult.Sampler = new RobidouxSharpResampler(); break; case Resampler.Spline: resizeOptionsResult.Sampler = new SplineResampler(); break; case Resampler.Lanczos2: resizeOptionsResult.Sampler = new Lanczos2Resampler(); break; case Resampler.Lanczos3: resizeOptionsResult.Sampler = new Lanczos3Resampler(); break; case Resampler.Lanczos5: resizeOptionsResult.Sampler = new Lanczos5Resampler(); break; case Resampler.Lanczos8: resizeOptionsResult.Sampler = new Lanczos8Resampler(); break; case Resampler.Triangle: resizeOptionsResult.Sampler = new TriangleResampler(); break; case Resampler.Welch: resizeOptionsResult.Sampler = new WelchResampler(); break; default: throw new NotImplementedException($"'{resizeOptions.Resampler}' Resampler is not implemented"); } return(resizeOptionsResult); }
/// <summary> /// Gets the size of the frame. /// </summary> /// <param name="image">The image.</param> /// <param name="options">The options.</param> /// <returns></returns> private Size GetFrameSize(Bitmap image, ResizeOptions options) { Size preferredSize = this.GetPreferredSize(options, image); return LimitToMaxSize(options, preferredSize); }
public static System.Drawing.Bitmap ResizeImage(System.Drawing.Bitmap image, int width, int height, ResizeOptions resizeOptions) { float f_width; float f_height; float dim; switch (resizeOptions) { case ResizeOptions.ExactWidthAndHeight: return(DoResize(image, width, height)); case ResizeOptions.MaxHeight: f_width = image.Width; f_height = image.Height; if (f_height <= height) { return(DoResize(image, (int)f_width, (int)f_height)); } dim = f_width / f_height; width = (int)((float)(height) * dim); return(DoResize(image, width, height)); case ResizeOptions.MaxWidth: f_width = image.Width; f_height = image.Height; if (f_width <= width) { return(DoResize(image, (int)f_width, (int)f_height)); } dim = f_width / f_height; height = (int)((float)(width) / dim); return(DoResize(image, width, height)); case ResizeOptions.MaxWidthAndHeight: int tmpHeight = height; int tmpWidth = width; f_width = image.Width; f_height = image.Height; if (f_width <= width && f_height <= height) { return(DoResize(image, (int)f_width, (int)f_height)); } dim = f_width / f_height; // Check if the width is ok if (f_width < width) { width = (int)f_width; } height = (int)((float)(width) / dim); // The width is too width if (height > tmpHeight) { if (f_height < tmpHeight) { height = (int)f_height; } else { height = tmpHeight; } width = (int)((float)(height) * dim); } return(DoResize(image, width, height)); default: return(image); } }
/// <summary> /// Get a picture URL /// </summary> /// <param name="picture">Picture instance</param> /// <param name="targetSize">The target picture size (longest side)</param> /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param> /// <returns>Picture URL</returns> public virtual string GetPictureUrl(Picture picture, int targetSize = 0, bool showDefaultPicture = true) { byte[] pictureBinary = null; if (picture != null) { pictureBinary = LoadPictureFromFile(picture.Id, picture.MimeType); } if (picture == null || pictureBinary == null || pictureBinary.Length == 0) { if (showDefaultPicture) { return(GetDefaultPictureUrl(targetSize)); } } string seoFileName = picture.SeoFilename; string lastPart = MimeTypeMap.GetExtension(picture.MimeType); string thumbFileName; if (targetSize == 0) { if (string.IsNullOrEmpty(seoFileName)) { thumbFileName = string.Format("{0:0000000}{1}", picture.Id, lastPart); } else { thumbFileName = string.Format("{0:0000000}_{1}{2}", picture.Id, seoFileName, lastPart); } } else { if (string.IsNullOrEmpty(seoFileName)) { thumbFileName = string.Format("{0:0000000}_{1}{2}", picture.Id, targetSize, lastPart); } else { thumbFileName = string.Format("{0:0000000}_{1}_{2}{3}", picture.Id, seoFileName, targetSize, lastPart); } thumbFileName = !String.IsNullOrEmpty(seoFileName) ? $"{picture.Id.ToString("0000000")}_{seoFileName}_{targetSize}.{lastPart}" : $"{picture.Id.ToString("0000000")}_{targetSize}.{lastPart}"; } string thumbFilePath = GetThumbLocalPath(thumbFileName); //the named mutex helps to avoid creating the same files in different threads, //and does not decrease performance significantly, because the code is blocked only for the specific file. using (var mutex = new Mutex(false, thumbFileName)) { if (!File.Exists(thumbFilePath)) { mutex.WaitOne(); //check, if the file was created, while we were waiting for the release of the mutex. if (!File.Exists(thumbFilePath)) { byte[] pictureBinaryResized; if (targetSize == 0) { pictureBinaryResized = pictureBinary; } else { using (Image <Rgba32> b = Image.Load(pictureBinary)) { using (var ms = new MemoryStream()) { var newSize = CalculateDimensions(new Size(b.Width, b.Height), targetSize); var options = new ResizeOptions { Size = new SixLabors.Primitives.Size(newSize.Width, newSize.Height), Mode = ResizeMode.Pad }; b.Mutate(x => x.Resize(options)); b.Save(ms, ImageFormats.Jpeg); pictureBinaryResized = ms.ToArray(); } } } //save to file SaveThumbToFile(thumbFilePath, pictureBinaryResized); } mutex.ReleaseMutex(); } } return(string.Format("{0}{1}/{2}", _webHelper.GetCurrentLocation(), ThumbFolder, thumbFileName)); }
/// <summary> /// Gets the size of the image. /// </summary> /// <param name="image">The image.</param> /// <param name="frameSize">Size of the frame.</param> /// <param name="options">The options.</param> /// <returns></returns> private Size GetImageSize(Bitmap image, Size frameSize, ResizeOptions options) { float scale = GetScale(options, image, frameSize); int width = this.Scale(image.Width, scale); return new Size(width, this.Scale(image.Height, scale)); }
/// <summary> /// Gets the scale. /// </summary> /// <param name="options">The options.</param> /// <param name="originalImage">The original image.</param> /// <param name="size">The size.</param> /// <returns></returns> private static float GetScale(ResizeOptions options, Image originalImage, Size size) { float num = ((float)size.Width) / ((float)originalImage.Width); float num2 = ((float)size.Height) / ((float)originalImage.Height); float num3 = Math.Min(num, num2); if (!options.AllowStretch && (num3 > 1f)) { num3 = 1f; } return num3; }
/// <summary> /// Gets the size of the preferred. /// </summary> /// <param name="options">The options.</param> /// <param name="image">The image.</param> /// <returns></returns> private Size GetPreferredSize(ResizeOptions options, Image image) { if (options.Scale > 0f) { return new Size(this.Scale(image.Width, options.Scale), this.Scale(image.Height, options.Scale)); } if (options.Size.IsEmpty || (options.Size == image.Size)) { return new Size(image.Size.Width, image.Size.Height); } if (options.Size.Width == 0) { float scale = ((float)options.Size.Height) / ((float)image.Height); return new Size(this.Scale(image.Width, scale), options.Size.Height); } if (options.Size.Height == 0) { float num2 = ((float)options.Size.Width) / ((float)image.Width); return new Size(options.Size.Width, this.Scale(image.Height, num2)); } return new Size(options.Size.Width, options.Size.Height); }
public static void Resize(Image <Rgba32> image, int maxWidth, int maxHeight) { if (image is null) { throw new ArgumentNullException(nameof(image)); } if (maxWidth <= 0) { throw new ArgumentOutOfRangeException(nameof(maxWidth), "Width must be positive."); } if (maxHeight <= 0) { throw new ArgumentOutOfRangeException(nameof(maxHeight), "Height must be positive."); } // So the spary takes up full size, make the larger dimension the size of the max allowed. // This could make the source bigger or smaller. if (image.Width != maxWidth || image.Height != maxHeight) { double scaleFactor; if (image.Width >= image.Height) { scaleFactor = 1.0 * maxWidth / image.Width; } else { scaleFactor = 1.0 * maxHeight / image.Height; } image.Mutate(x => x.Resize( (int)Math.Floor(image.Width * scaleFactor), (int)Math.Floor(image.Height * scaleFactor) )); } if (image.Width != maxWidth || image.Height != maxHeight) { var resizeOptions = new ResizeOptions { Size = new Size { Width = maxWidth, Height = maxHeight }, Mode = ResizeMode.Manual, Position = AnchorPositionMode.TopLeft, TargetRectangle = new Rectangle { X = (maxWidth - image.Width) / 2, Y = (maxHeight - image.Height) / 2, Width = image.Width, Height = image.Height }, Compand = false, }; image.Mutate(x => x .Resize(resizeOptions) .BackgroundColor(Color.Transparent)); } }
/// <summary> /// Resizes the specified bitmap. /// </summary> /// <param name="bitmap">The bitmap.</param> /// <param name="options">The options.</param> /// <param name="format">The format.</param> /// <returns></returns> public Bitmap Resize(Bitmap bitmap, ResizeOptions options, ImageFormat format) { Size frameSize = this.GetFrameSize(bitmap, options); Size imageSize = this.GetImageSize(bitmap, frameSize, options); return this.Resize(bitmap, imageSize, frameSize, options.BackgroundColor, format); }