ImgMetadataRemover/ImageCore/Files/SimpleOutputSink.cs

73 lines
2.7 KiB
C#
Raw Normal View History

2022-01-23 17:30:05 +00:00
using System.IO;
using Ardalis.GuardClauses;
using Image.Core;
2022-01-23 17:30:05 +00:00
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Image.Files
2022-01-23 17:30:05 +00:00
{
/// <summary>
2022-02-12 20:12:57 +00:00
/// SimpleOutputFormatter keeps the original file name of the image when formatting it.
/// SimpleOutputFormatter also saves all the file names into a new directory.
2022-01-23 17:30:05 +00:00
/// path.
/// </summary>
2022-02-12 20:12:57 +00:00
public class SimpleOutputSink : IOutputSink
2022-01-23 17:30:05 +00:00
{
public static ILogger Logger = NullLogger.Instance;
private readonly string _outputDirectory;
/// <summary>
2022-02-12 20:12:57 +00:00
/// Creates an instance of SimpleOutputFormatter.
2022-01-23 17:30:05 +00:00
/// </summary>
/// <param name="outputDirectory">The output directory.</param>
2022-02-12 20:12:57 +00:00
public SimpleOutputSink(string outputDirectory)
2022-01-23 17:30:05 +00:00
{
if (outputDirectory.Equals(""))
{
outputDirectory = ".";
}
else
{
FileSystemHelpers.CreateDestinationDirectory(outputDirectory);
}
2022-01-23 17:30:05 +00:00
_outputDirectory = outputDirectory;
}
/// <summary>
/// Returns a path containing the file name in the output directory.
/// </summary>
/// <param name="initialFilePath">The initial path of the image.</param>
/// <returns>An absolute path of the form output_directory/initialFileName.jpg</returns>
public string GetOutputPath(string initialFilePath)
{
2022-01-26 18:50:02 +00:00
Logger.LogDebug($"KeepFilenameFormatter - {_outputDirectory} - {initialFilePath}");
Guard.Against.NullOrEmpty(initialFilePath, nameof(initialFilePath));
2022-01-27 21:22:10 +00:00
var fileName = Path.GetFileName(initialFilePath).Split('.')[0];
var path = Path.Combine(_outputDirectory, $"{fileName}.jpg");
2022-01-23 17:30:05 +00:00
return path;
}
public bool Save(IMetadataRemover metadataRemover)
{
var newFilePath = GetOutputPath(metadataRemover.GetImagePath());
var fileExists = FileSystemHelpers.CheckIfFileExists(newFilePath);
if (fileExists)
{
Logger.LogWarning($"File {newFilePath} exists, skipping");
return false;
}
// Save the image under the same name in the new directory.
metadataRemover.CleanImage(newFilePath);
return true;
}
2022-01-23 17:30:05 +00:00
/// <summary>
/// Creates an instance of OriginalFilenameFileOutputPathFormatter.
/// </summary>
/// <param name="outputDirectory">The output directory.</param>
2022-02-12 20:12:57 +00:00
public static SimpleOutputSink Create(string outputDirectory)
2022-01-23 17:30:05 +00:00
{
2022-02-12 20:12:57 +00:00
return new SimpleOutputSink(outputDirectory);
2022-01-23 17:30:05 +00:00
}
}
}