public async Task <int?> GetMaximumAllowedPointsAsync(int siteId) { var(IsSet, SetValue) = await _siteLookupService.GetSiteSettingIntAsync(siteId, SiteSettingKey.Challenges.MaxPointsPerChallengeTask); return(IsSet ? SetValue : (int?)null); }
public async Task ValidateBadgeImageAsync(byte[] badgeImage) { var(IsSet, SetValue) = await _siteLookupService .GetSiteSettingIntAsync(GetCurrentSiteId(), SiteSettingKey.Badges.MaxFileSize); if (IsSet && badgeImage != null && badgeImage.Length > SetValue * KBSize) { throw new GraException($"File size exceeds the maximum of {SetValue}KB"); } try { using var image = Image.Load(badgeImage); if (image.Height != image.Width) { throw new GraException("Image must be square."); } } catch (UnknownImageFormatException uifex) { throw new GraException("Unknown image type, please upload a JPEG or PNG image.", uifex); } }
private async Task <string> WriteBadgeFileAsync(Badge badge, byte[] imageFile, ImageType?imageType) { string extension = imageType.HasValue ? "." + imageType.ToString().ToLowerInvariant() : Path.GetExtension(badge.Filename).ToLowerInvariant(); string filename = $"badge{badge.Id}{extension}"; string fullFilePath = GetFilePath(filename); using (var image = Image.Load(imageFile)) { var(IsSet, SetValue) = await _siteLookupService.GetSiteSettingIntAsync( GetCurrentSiteId(), SiteSettingKey.Badges.MaxDimension); int maxDimension = IsSet ? SetValue : DefaultMaxDimension; if (image.Width > maxDimension || image.Height > maxDimension) { _logger.LogInformation("Resizing badge file {BadgeFile}", fullFilePath); var sw = Stopwatch.StartNew(); image.Mutate(_ => _.Resize(maxDimension, maxDimension, KnownResamplers.Lanczos3)); if (image.Metadata != null) { image.Metadata.ExifProfile = null; image.Metadata.IccProfile = null; image.Metadata.IptcProfile = null; } switch (extension) { case "jpg": case "jpeg": await image.SaveAsJpegAsync(fullFilePath, new JpegEncoder { Quality = 77 }); break; default: await image.SaveAsPngAsync(fullFilePath, new PngEncoder { CompressionLevel = PngCompressionLevel.BestCompression, IgnoreMetadata = true }); break; } _logger.LogInformation("Image resize and save of {Filename} took {Elapsed} ms", filename, sw.ElapsedMilliseconds); } else { _logger.LogDebug("Writing out badge file {BadgeFile}", fullFilePath); File.WriteAllBytes(fullFilePath, imageFile); } return(GetUrlPath(filename)); } }