Skip to content

Commit

Permalink
Refactor AddWatermarkIfNeeded for clarity and readability
Browse files Browse the repository at this point in the history
Refactored the `AddWatermarkIfNeeded` method in the `ImageController` class to improve readability and logic clarity. The method now returns early if the watermark is not enabled, should be skipped, or if the file extension is `.gif`. This change simplifies the code by removing nested conditions and making the watermarking logic more straightforward. The use of `using var` for the `ImageWatermarker` instance remains unchanged to ensure proper resource disposal.
  • Loading branch information
EdiWang committed Nov 1, 2024
1 parent 9ac3f0c commit e3c6b27
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions src/Moonglade.Web/Controllers/ImageController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,23 +98,21 @@ public async Task<IActionResult> Image([Required] IFormFile file, [FromQuery] bo

private byte[] AddWatermarkIfNeeded(MemoryStream stream, string ext, bool skipWatermark)
{
if (blogConfig.ImageSettings.IsWatermarkEnabled && !skipWatermark && !ext.Equals(".gif", StringComparison.OrdinalIgnoreCase))
{
using var watermarker = new ImageWatermarker(stream, ext, blogConfig.ImageSettings.WatermarkSkipPixel);
return watermarker.AddWatermark(
blogConfig.ImageSettings.WatermarkText,
Color.FromRgba(128, 128, 128, (byte)blogConfig.ImageSettings.WatermarkColorA),
WatermarkPosition.BottomRight,
15,
blogConfig.ImageSettings.WatermarkFontSize)?.ToArray();
}
if (!blogConfig.ImageSettings.IsWatermarkEnabled || skipWatermark) return null;

if (ext.Equals(".gif", StringComparison.OrdinalIgnoreCase))
{
logger.LogInformation($"Skipped watermark for extension name: {ext}");
return null;
}

return null;
using var watermarker = new ImageWatermarker(stream, ext, blogConfig.ImageSettings.WatermarkSkipPixel);
return watermarker.AddWatermark(
blogConfig.ImageSettings.WatermarkText,
Color.FromRgba(128, 128, 128, (byte)blogConfig.ImageSettings.WatermarkColorA),
WatermarkPosition.BottomRight,
15,
blogConfig.ImageSettings.WatermarkFontSize)?.ToArray();
}

private bool ShouldKeepOriginal(bool skipWatermark)
Expand Down

0 comments on commit e3c6b27

Please sign in to comment.