Add method to validate and load images from file paths

This commit is contained in:
Thorsten Sommer 2025-12-16 21:24:35 +01:00
parent 89aa28d972
commit 741f72bc5a
Signed by: tsommer
GPG Key ID: 371BBA77A02C0108
2 changed files with 45 additions and 0 deletions

View File

@ -1,6 +1,7 @@
using System.Text.Json.Serialization;
using AIStudio.Provider;
using AIStudio.Tools.Validation;
namespace AIStudio.Chat;
@ -50,6 +51,23 @@ public sealed class ContentImage : IContent, IImageSource
#endregion
/// <summary>
/// Creates a ContentImage from a local file path.
/// </summary>
/// <param name="filePath">The path to the image file.</param>
/// <returns>A new ContentImage instance if the file is valid, null otherwise.</returns>
public static async Task<ContentImage?> CreateFromFileAsync(string filePath)
{
if (!await FileExtensionValidation.IsImageExtensionValidWithNotifyAsync(filePath))
return null;
return new ContentImage
{
SourceType = ContentImageSource.LOCAL_PATH,
Source = filePath,
};
}
/// <summary>
/// The type of the image source.
/// </summary>

View File

@ -52,4 +52,31 @@ public static class FileExtensionValidation
return true;
}
/// <summary>
/// Validates that the file is a supported image format and sends appropriate MessageBus notifications when invalid.
/// </summary>
/// <param name="filePath">The file path to validate.</param>
/// <returns>True if valid image, false if invalid (error already sent via MessageBus).</returns>
public static async Task<bool> IsImageExtensionValidWithNotifyAsync(string filePath)
{
var ext = Path.GetExtension(filePath).TrimStart('.');
if (string.IsNullOrWhiteSpace(ext))
{
await MessageBus.INSTANCE.SendError(new(
Icons.Material.Filled.ImageNotSupported,
TB("File has no extension")));
return false;
}
if (!Array.Exists(FileTypeFilter.AllImages.FilterExtensions, x => x.Equals(ext, StringComparison.OrdinalIgnoreCase)))
{
await MessageBus.INSTANCE.SendError(new(
Icons.Material.Filled.ImageNotSupported,
TB("Unsupported image format")));
return false;
}
return true;
}
}