public async Task <IActionResult> PostJson([FromBody] Base64ImageModel[] imageInfos) { try { //Save File foreach (var imageInfo in imageInfos) { await _imageService.FileCheck(imageInfo); var dbModel = new ImageDbModel() { FileName = imageInfo.fileName, AddedDate = DateTime.Now, ImageData = imageInfo.data, PreviewData = resizer.Resize(imageInfo.data), }; await _imageService.Save(dbModel, _dbContext); } } catch (ArgumentException ex) { return(BadRequest(ex.Message)); } catch (Exception ex) { _logger.LogError(ex.Message); return(StatusCode(500)); } return(Ok()); }
public void Resize_Image_ReturnsImageWithNewSize(Size expected) { var image = new Fixture().Create <Image>(); var result = _resizer.Resize(image, expected); var actual = new Size(result.Pixels.GetLength(1), result.Pixels.GetLength(0)); Assert.Equal(expected, actual); }
public Image CreatePixelart(Image image, PixelizingOptions options) { if (image == null) { throw new ArgumentNullException(nameof(image)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var availibleColors = options.AvailibleColors; var cache = new Dictionary <SColor, SColor>(); var pixels = _imageResizer.Resize(image, options.Size).Pixels; var result = new SColor[pixels.GetLength(0), pixels.GetLength(1)]; for (int y = 0; y < pixels.GetLength(0); y++) { for (int x = 0; x < pixels.GetLength(1); x++) { result[y, x] = FindMostSuitableAvailibleColor(pixels[y, x], availibleColors, cache); } } return(new Image { Pixels = result }); }
public byte[] Create(Stream source, ImageSize desiredSize, string contentType) { using (var image = Image.FromStream(source)) { var originalSize = new ImageSize { Height = image.Height, Width = image.Width }; var size = resizer.Resize(originalSize, desiredSize); using (var thumbnail = new Bitmap(size.Width, size.Height)) { ScaleImage(image, thumbnail); using (var memoryStream = new MemoryStream()) { thumbnail.Save(memoryStream, ImageFormats[contentType]); return(memoryStream.ToArray()); } } } }
public async Task <IActionResult> Post(User user, IFormFile file) { var fileName = "no-photo.png"; if (ModelState.IsValid) { if (file != null) { var uploads = Path.Combine(_env.WebRootPath, "Upload\\Profile"); fileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName); using (var fileStream = new FileStream(Path.Combine(uploads, fileName), FileMode.Create)) { await file.CopyToAsync(fileStream); } //---------------------resize Images ---------------------- _imageResizer.Resize(Path.Combine(uploads, fileName), Path.Combine(uploads, "thumbnail", fileName)); } } user.Profile = fileName; //--------------------------- await _userService.Add(user); return(CreatedAtAction(nameof(GetUsers), new { id = user.UserId }, user)); }
/// <summary> /// Resizes the specified image by using the specified <see cref="IImageResizer"/> and /// return a new image with /// the spezified size which is a resized version of the passed image. /// </summary> /// <param name="source">The width of the new image. Must be greater than zero.</param> /// <param name="width">The width of the new image. Must be greater than zero.</param> /// <param name="height">The height of the new image. Must be greater than zero.</param> /// <param name="resizer">The resizer, which should resize the image.</param> /// <returns>The new image.</returns> /// <exception cref="ArgumentNullException"> /// <para><paramref name="resizer"/> is null (Nothing in Visual Basic).</para> /// <para>- or -</para> /// <para><paramref name="source"/> is null (Nothing in Visual Basic).</para> /// </exception> /// <exception cref="ArgumentException"> /// <para><paramref name="width"/> is negative.</para> /// <para>- or -</para> /// <para><paramref name="height"/> is negative.</para> /// </exception> public static ExtendedImage Resize(ExtendedImage source, int width, int height, IImageResizer resizer) { Contract.Requires <ArgumentNullException>(source != null, "Source image cannot be null."); Contract.Requires <ArgumentException>(source.IsFilled, "Source image has not been loaded."); Contract.Requires <ArgumentNullException>(resizer != null, "Image Resizer cannot be null."); return(PerformAction(source, false, (sourceImage, targetImage) => resizer.Resize(sourceImage, targetImage, width, height))); }
private void EnsureResizedCovers(Series series, MediaCover cover, bool forceResize) { int[] heights; switch (cover.CoverType) { default: return; case MediaCoverTypes.Poster: case MediaCoverTypes.Headshot: heights = new[] { 500, 250 }; break; case MediaCoverTypes.Banner: heights = new[] { 70, 35 }; break; case MediaCoverTypes.Fanart: case MediaCoverTypes.Screenshot: heights = new[] { 360, 180 }; break; } foreach (var height in heights) { var mainFileName = GetCoverPath(series.Id, cover.CoverType); var resizeFileName = GetCoverPath(series.Id, cover.CoverType, height); if (forceResize || !_diskProvider.FileExists(resizeFileName) || _diskProvider.GetFileSize(resizeFileName) == 0) { _logger.Debug("Resizing {0}-{1} for {2}", cover.CoverType, height, series); try { _resizer.Resize(mainFileName, resizeFileName, height); } catch { _logger.Debug("Couldn't resize media cover {0}-{1} for {2}, using full size image instead.", cover.CoverType, height, series); } } } }
private void Resize(string path, string colorIconName, FileInfo file, int size, RequiredColor?requiredColor, string resolutionFolder) { string destinationIconPath = Path.Combine(path, colorIconName); _resizer.Resize(file.FullName, destinationIconPath, size, size, requiredColor?.ColorHexValue); string relativeIconPath = Path.Combine("Resources", resolutionFolder, colorIconName); _projectFileUpdater.AddIcon(relativeIconPath); }
private IActionResult GetFileFullContent(File file, int width, int height) { if (!file.Metadata.ContentType.Contains("image")) { return(File(file.FileBlob, file.Metadata.ContentType)); } return(File( _imageResizer.Resize(file.FileBlob, width, height), file.Metadata.ContentType )); }
public NancyDependencies() { Sources = A.Fake <ISourcesRepository>(mock => mock.Strict()); SourceImages = A.Fake <ISourceImagesRepository>(); resizer = A.Dummy <IImageResizer>(); A.CallTo(() => resizer.Resize(A <byte[]> .Ignored, A <int> .Ignored)) .ReturnsLazily(c => c.Arguments.Get <byte[]>(0)); Browser = new Browser(with => with.Module <SourcesModule>() .Module <SourceImagesModule>() .RouteResolver <global::Nancy.Routing.UriTemplates.UriTemplateRouteResolver>() .Dependency <IUriTemplateExpander>(typeof(TunnelVisionLabsUriTemplateExpander)) .Dependencies(GetDependencies().ToArray())); }
public async Task <UserAvatar> GetAvatarAsync(string email, ImageDimensions dimensions) { try { var user = await _userRepository.GetUserFromEmailAsync(email); if (user == null) { return(UserAvatar.NotAvailable); } var requestUri = new Uri(_config.ApiBaseUrl, $"/_apis/GraphProfile/MemberAvatars/{user.Descriptor}?size=2"); var client = _httpClientFactory.GetClient(); using (var response = await client.GetAsync(requestUri)) { if (response.IsSuccessStatusCode) { var data = await response.Content.ReadAsByteArrayAsync(); var contentType = response.Content.Headers.ContentType.MediaType; var type = _imageFormatManager.FindFormatByMimeType(contentType); using (var image = Image.Load(data)) { var resizedImage = _imageResizer.Resize(image, dimensions.Height, dimensions.Width); var bytes = resizedImage.ConvertToByteArray(type); return(new UserAvatar { Data = bytes, ContentType = contentType }); } } } } catch (Exception ex) { _logger.LogError($"Error getting Azure Dev Ops users list or user avatar: {ex.Message}"); } throw new NotImplementedException(); }
public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { if (request is IPictureCommand <TResponse> pictureCommand) { foreach (var requestPictureModel in pictureCommand.PictureModels) { var stream = requestPictureModel.PictureStream; if (stream != null) { var output = new MemoryStream(); _imageResizer.Resize(stream, output, _pictureSettings.MaxWidth, _pictureSettings.MaxHeight); output.Position = 0; requestPictureModel.SetPictureStream(output); } } } return(await next()); }
/// <inheritdoc/> public async Task <string> StoreAvatarAsync(string firstName, string oldAvatarId, string fileExt, Stream fileContent) { var newAvatarId = avatarIdGenerator.Generate(firstName, fileExt); using (var resizedImageStream = imageResizer.Resize( AvatarConstants.MaxSize, AvatarConstants.MaxSize, fileContent, fileExt)) { await StoreNewAvatarAsync(resizedImageStream, newAvatarId); } if (!string.IsNullOrWhiteSpace(oldAvatarId) && oldAvatarId != newAvatarId) { DeleteAllByAvatarId(oldAvatarId); } return(newAvatarId); }
protected virtual Stream EnsureMaxImageSize(Stream blobStream, Size maxSize, ImageQueue image) { using (var bitmap = Image.FromStream(blobStream)) { // if the image's dimension if larger than max size, we resize it to: // save the bandwidth // and also to prevent any quota/litmitation error might have if (bitmap.Width > maxSize.Width || bitmap.Height > maxSize.Height) { double heightWidthRatio = ((double)bitmap.Height) / bitmap.Width; var newSize = new Size(maxSize.Width, Convert.ToInt32(maxSize.Width * heightWidthRatio)); if (newSize.Height > maxSize.Height) { newSize = new Size(Convert.ToInt32(maxSize.Height / heightWidthRatio), maxSize.Height); } var imageFormat = FileExtensions.GetImageFormat(_mimeExtensionHelper.FindMime(Path.GetExtension(image.FileName)), true); return(_imageResizer.Resize(newSize, true, blobStream, imageFormat).Result); } return(blobStream); } }
#pragma warning disable 1998 private async Task <Stream> GeneratedThumbnailAsync( [NotNull] Stream photoData, PhotoCategory photoCategory, string contentType) { if (photoData == null) { throw new ArgumentNullException(nameof(photoData)); } var thumbnailConfiguration = PhotoCategoryConfig.Configs[photoCategory]; var thumbnailData = imageResizer.Resize( thumbnailConfiguration.ThumbMaxWidth, thumbnailConfiguration.ThumbMaxHeight, photoData, ".jpg", contentType); return(thumbnailData); }
//====== IThumbnailsMaker public ThumbnailMakerResult?TryMakeAndSaveThumbnail(IFileInfo fileInfo, UtcTimestamp timestamp) { Guard.NotNull(fileInfo, nameof(fileInfo)); Guard.NotNull(timestamp, nameof(timestamp)); try { using var stream = fileInfo.CreateReadStream(); using Image srcImage = Image.FromStream(stream); using Image thumbnail = imageResizer.Resize(srcImage, new Size(300, 300), true); string thumbFileName = SaveThumbnail(thumbnail, timestamp); return(new ThumbnailMakerResult(new FileName(thumbFileName), srcImage.Size)); } catch { return(null); // TODO: error logging } }
public async Task <UserAvatar> GetAvatarAsync(string email, ImageDimensions dimensions) { try { var hash = GetHash(email.ToLower().Trim()); var requestUri = new Uri($"https://www.gravatar.com/avatar/{hash}?s=400&d=404"); var client = _httpClientFactory.CreateClient(); using (var response = await client.GetAsync(requestUri)) { if (response.IsSuccessStatusCode) { var data = await response.Content.ReadAsByteArrayAsync(); var contentType = response.Content.Headers.ContentType.MediaType; var type = _imageFormatManager.FindFormatByMimeType(contentType); using (var image = Image.Load(data)) { var resizedImage = _imageResizer.Resize(image, dimensions.Height, dimensions.Width); var bytes = resizedImage.ConvertToByteArray(type); return(new UserAvatar { Data = bytes, ContentType = contentType }); } } } } catch (Exception ex) { _logger.LogError($"Error getting Gravatar for '{email}': {ex.Message}"); } return(UserAvatar.NotAvailable); }
private void AddResizedImage(IFileInfo originalFileInfo, IFileInfo variantFileInfo) { DirectoryInfo variantDirectory = new FileInfo(variantFileInfo.PhysicalPath).Directory; if (!variantDirectory.Exists) { variantDirectory.Create(); logger.LogInformation( MainCfg.LogEventId, "The variant directory '{0}' was successfully created!", variantDirectory.FullName); } using (var outputImageStream = new FileStream(variantFileInfo.PhysicalPath, FileMode.Create)) { using (Stream inputImageStream = originalFileInfo.CreateReadStream()) { imageResizer.Resize(inputImageStream, imageSizeInfo, outputImageStream); } } }
private void CreateIcons(string[] resolutionFolders, string baseIconName, int requiredSize, FileInfo file, IList <Image> imagesInfo, string destinationPath, RequiredColor color = null) { string folderName = $"{Path.GetFileNameWithoutExtension(baseIconName)}.imageset"; string folderPath = Path.Combine(destinationPath, folderName); EnsureDirectoryExists(folderPath); foreach (string scaleFactorString in resolutionFolders) { string finalIconName = _imageRenamer.AddPostfix(baseIconName, $"_{scaleFactorString}"); string destinationIconPath = Path.Combine(folderPath, finalIconName); int size = (int)(requiredSize * ResNameAssociation[scaleFactorString]); _resizer.Resize(file.FullName, destinationIconPath, size, size, color?.ColorHexValue); Image image = new Image { Appearances = new string[] { }, Scale = scaleFactorString, Idiom = "universal", FileName = finalIconName, }; imagesInfo.Add(image); string relativeIconPath = Path.Combine("Assets.xcassets", folderName, finalIconName); _projectFileUpdater.AddIcon(relativeIconPath); } CreateContentJson(folderPath, imagesInfo); string relativeContentFilePath = Path.Combine("Assets.xcassets", folderName, "Contents.json"); _projectFileUpdater.AddIcon(relativeContentFilePath); }
private void EnsureResizedCovers(Author author, MediaCover cover, bool forceResize, Book book = null) { int[] heights = GetDefaultHeights(cover.CoverType); foreach (var height in heights) { var mainFileName = GetCoverPath(author.Id, MediaCoverEntity.Author, cover.CoverType, cover.Extension); var resizeFileName = GetCoverPath(author.Id, MediaCoverEntity.Author, cover.CoverType, cover.Extension, height); if (forceResize || !_diskProvider.FileExists(resizeFileName) || _diskProvider.GetFileSize(resizeFileName) == 0) { _logger.Debug("Resizing {0}-{1} for {2}", cover.CoverType, height, author); try { _resizer.Resize(mainFileName, resizeFileName, height); } catch { _logger.Debug("Couldn't resize media cover {0}-{1} for author {2}, using full size image instead.", cover.CoverType, height, author); } } } }
/// <summary> /// Resizes the specified image by using the specified <see cref="IImageResizer"/> and /// returns new image which has the specified maximum /// extension in x and y direction. /// </summary> /// <param name="source">The source image to resize.</param> /// <param name="size">The maximum size of the image in x and y direction.</param> /// <param name="resizer">The resizer, which should resize the image.</param> /// <returns>The resized image.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is null /// (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentException"><paramref name="size"/> is negative.</exception> public static ExtendedImage Resize(ExtendedImage source, int size, IImageResizer resizer) { Contract.Requires <ArgumentNullException>(source != null, "Source image cannot be null."); Contract.Requires <ArgumentException>(source.IsFilled, "Source image has not been loaded."); Contract.Requires <ArgumentNullException>(resizer != null, "Image Resizer cannot be null."); int width = 0; int height = 0; float ratio = (float)source.PixelWidth / source.PixelHeight; if (source.PixelWidth > source.PixelHeight && ratio > 0) { width = size; height = (int)(width / ratio); } else { height = size; width = (int)(height * ratio); } return(PerformAction(source, false, (sourceImage, targetImage) => resizer.Resize(sourceImage, targetImage, width, height))); }
public async Task SynchronizeBlogPostsAsync(IBlogPostRepository sourceRepo, IBlogPostRepository destRepo, bool incremental, string overrideCursor, CancellationToken cancellationToken) { try { await _lockRepository.AcquireLockAsync("synchelperlock", 10, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), cancellationToken); _logger.LogInformation($"SynchronizeBlogPostsAsync with incremental = {incremental}"); var dropboxCursor = new CursorContainer(); if (incremental) { // Try to get a persisted cursor from our SQL database, if that's null (so we haven't got one), then we'll do a full update dropboxCursor.Cursor = overrideCursor ?? await destRepo.GetDropboxCursorAsync(cancellationToken); _logger.LogDebug($"Cursor = {dropboxCursor.Cursor}"); } var cursor = incremental && !string.IsNullOrWhiteSpace(dropboxCursor.Cursor) ? dropboxCursor : null; var sourcePosts = (await sourceRepo.GetAllAsync(cursor, cancellationToken)).ToList(); if (string.IsNullOrWhiteSpace(dropboxCursor.Cursor)) { _logger.LogInformation("No current dropbox cursor, so explicitly requesting current cursor ..."); dropboxCursor.Cursor = await _dropboxHelper.GetCurrentCursorAsync(cancellationToken); _logger.LogInformation($"Returned cursor {dropboxCursor.Cursor}"); } _logger.LogInformation($"Processing {sourcePosts.Count} source posts ..."); foreach (var sourcePost in sourcePosts) { await destRepo.AddOrUpdateAsync(sourcePost, cancellationToken); } _logger.LogInformation("Processing images ..."); var imageTasks = new List <Task>(); foreach (var sourcePost in sourcePosts) { foreach (var imageData in sourcePost.ImageData) { var imageContent = await imageData.ImageDataTask; var resizedImageFileContent = imageData.FileName.ToLower().Contains("noresize") ? imageContent : _imageResizer.Resize(imageContent, _settings.MaxResizedImageSize); imageTasks.Add(_imageRepository.AddAsync(imageData.PostFolder, imageData.FileName, resizedImageFileContent, cancellationToken)); } } await Task.WhenAll(imageTasks); if (!incremental) // Do not delete posts when in incremental mode (todo) Is this comment correct? Surely as we're reading the json file even on incremental sync, we can still delete on incremental? { var destPosts = (await destRepo.GetAllAsync(null, cancellationToken)).ToList(); var postsToDelete = destPosts.Where(d => sourcePosts.All(s => s.Id != d.Id)).ToList(); _logger.LogInformation($"Found {postsToDelete.Count} to delete out of {destPosts.Count} posts"); await destRepo.DeleteAsync(postsToDelete, cancellationToken); } await destRepo.RemoveUnusedTagsAsync(cancellationToken); _logger.LogInformation($"Saving new Dropbox cursor: {dropboxCursor.Cursor}"); await destRepo.SetDropboxCursorAsync(dropboxCursor.Cursor, cancellationToken); } finally { await _lockRepository.ReleaseLockAsync(cancellationToken); } }
/// <summary> /// Compares two images based on defined set up. /// </summary> /// <returns>An instance of <see cref="ComparisonResult"/> that results of comparison.</returns> public ComparisonResult Compare() { if (_baselineImage == null) { throw new ArgumentNullException(nameof(_baselineImage), "Baseline image is required. Use CompareTo(...) method."); } if (_scaleToSameSize) { _actualImage = _resizer.Resize(_actualImage, _baselineImage.Width, _baselineImage.Height); } var comparisonAreaWidth = _actualImage.Width > _baselineImage.Width ? _actualImage.Width : _baselineImage.Width; var comparisonAreaHeight = _actualImage.Height > _baselineImage.Height ? _actualImage.Height : _baselineImage.Height; var comparisonResultImage = new Bitmap(comparisonAreaWidth, comparisonAreaHeight); var pixelMismatchCount = 0; var differenceBounds = new DifferenceBounds { Top = comparisonAreaHeight, Left = comparisonAreaWidth, Bottom = 0, Right = 0 }; void updateBounds(int x, int y) { differenceBounds.Left = Math.Min(x, differenceBounds.Left); differenceBounds.Right = Math.Max(x, differenceBounds.Right); differenceBounds.Top = Math.Min(y, differenceBounds.Top); differenceBounds.Bottom = Math.Max(y, differenceBounds.Bottom); } var startTime = DateTime.Now; var skipTheRest = false; for (var horizontalPosition = 0; horizontalPosition < comparisonAreaWidth; horizontalPosition++) { for (var verticalPosition = 0; verticalPosition < comparisonAreaHeight; verticalPosition++) { if (skipTheRest || !IsPixelInBounds(_actualImage, horizontalPosition, verticalPosition) || !IsPixelInBounds(_baselineImage, horizontalPosition, verticalPosition)) { break; } var actualPixel = _actualImage.GetPixel(horizontalPosition, verticalPosition); var expectedPixel = _baselineImage.GetPixel(horizontalPosition, verticalPosition); var errorPixel = GetColorOfDifference(_settings.DifferenceType.Value)(actualPixel, expectedPixel); var isPixelComparable = IsPixelComparable(expectedPixel, horizontalPosition, verticalPosition); if (_ignoreColors) { if (IsPixelBrightnessSimilar(actualPixel, expectedPixel) || !isPixelComparable) { if (!_compareOnly && _settings.DifferenceType != DifferenceType.DiffOnly) { SetGrayScaledPixel(comparisonResultImage, expectedPixel, horizontalPosition, verticalPosition); } } else { if (!_compareOnly) { comparisonResultImage.SetPixel(horizontalPosition, verticalPosition, errorPixel); } pixelMismatchCount++; updateBounds(horizontalPosition, verticalPosition); } continue; } if (IsRGBSimilar(actualPixel, expectedPixel) || !isPixelComparable) { if (!_compareOnly && _settings.DifferenceType != DifferenceType.DiffOnly) { SetTransparentPixel(comparisonResultImage, actualPixel, horizontalPosition, verticalPosition); } } else if ( _ignoreAntialiasing && (IsAntialiased(_actualImage, horizontalPosition, verticalPosition) || IsAntialiased(_baselineImage, horizontalPosition, verticalPosition)) ) { if (IsPixelBrightnessSimilar(actualPixel, expectedPixel) || !isPixelComparable) { if (!_compareOnly && _settings.DifferenceType != DifferenceType.DiffOnly) { SetGrayScaledPixel(comparisonResultImage, expectedPixel, horizontalPosition, verticalPosition); } } else { if (!_compareOnly) { comparisonResultImage.SetPixel(horizontalPosition, verticalPosition, errorPixel); } pixelMismatchCount++; updateBounds(horizontalPosition, verticalPosition); } } else { if (!_compareOnly) { comparisonResultImage.SetPixel(horizontalPosition, verticalPosition, errorPixel); } pixelMismatchCount++; updateBounds(horizontalPosition, verticalPosition); } if (_compareOnly) { var currentMisMatchPercent = (double)pixelMismatchCount / (comparisonAreaHeight * comparisonAreaWidth) * 100; if (currentMisMatchPercent > _returnEarlyThreshold) { skipTheRest = true; } } } } var rawMisMatchPercentage = (float)pixelMismatchCount / (comparisonAreaHeight * comparisonAreaWidth) * 100; return(new ComparisonResult { DiffBounds = differenceBounds, Mismatch = rawMisMatchPercentage, AnalysisTime = DateTime.Now - startTime, ImageDifference = !_compareOnly ? ImageOperations.ConvertToBase64(comparisonResultImage) : null, IsSameDimensions = _actualImage.Width == _baselineImage.Width && _actualImage.Height == _baselineImage.Height, DimensionDifference = new DimensionDifference { Width = _actualImage.Width - _baselineImage.Width, Height = _actualImage.Height - _baselineImage.Height } }); }
/// <summary> /// Resizes the specified image by using the specified <see cref="IImageResizer"/> and /// return a new image with /// the spezified size which is a resized version of the passed image. /// </summary> /// <param name="source">The width of the new image. Must be greater than zero.</param> /// <param name="width">The width of the new image. Must be greater than zero.</param> /// <param name="height">The height of the new image. Must be greater than zero.</param> /// <param name="resizer">The resizer, which should resize the image.</param> /// <returns>The new image.</returns> /// <exception cref="ArgumentNullException"> /// <para><paramref name="resizer"/> is null (Nothing in Visual Basic).</para> /// <para>- or -</para> /// <para><paramref name="source"/> is null (Nothing in Visual Basic).</para> /// </exception> /// <exception cref="ArgumentException"> /// <para><paramref name="width"/> is negative.</para> /// <para>- or -</para> /// <para><paramref name="height"/> is negative.</para> /// </exception> public static ExtendedImage Resize(ExtendedImage source, int width, int height, IImageResizer resizer) { Contract.Requires<ArgumentNullException>(source != null, "Source image cannot be null."); Contract.Requires<ArgumentException>(source.IsFilled, "Source image has not been loaded."); Contract.Requires<ArgumentNullException>(resizer != null, "Image Resizer cannot be null."); return PerformAction(source, false, (sourceImage, targetImage) => resizer.Resize(sourceImage, targetImage, width, height)); }
/// <summary> /// Resizes the specified image by using the specified <see cref="IImageResizer"/> and /// returns new image which has the specified maximum /// extension in x and y direction. /// </summary> /// <param name="source">The source image to resize.</param> /// <param name="size">The maximum size of the image in x and y direction.</param> /// <param name="resizer">The resizer, which should resize the image.</param> /// <returns>The resized image.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is null /// (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentException"><paramref name="size"/> is negative.</exception> public static ExtendedImage Resize(ExtendedImage source, int size, IImageResizer resizer) { Contract.Requires<ArgumentNullException>(source != null, "Source image cannot be null."); Contract.Requires<ArgumentException>(source.IsFilled, "Source image has not been loaded."); Contract.Requires<ArgumentNullException>(resizer != null, "Image Resizer cannot be null."); int width = 0; int height = 0; float ratio = (float)source.PixelWidth / source.PixelHeight; if (source.PixelWidth > source.PixelHeight && ratio > 0) { width = size; height = (int)(width / ratio); } else { height = size; width = (int)(height * ratio); } return PerformAction(source, false, (sourceImage, targetImage) => resizer.Resize(sourceImage, targetImage, width, height)); }