How to check if base64 url is an image in c#
You can check if a base64 URL is an image in C# by decoding the base64 string and checking if the result is a valid image format. Here's an example code snippet:
public static bool IsBase64UrlAnImage(string base64Url)
{
try
{
// Remove data URI scheme if present
if (base64Url.StartsWith("data:image"))
{
base64Url = base64Url.Split(',')[1];
}
// Decode base64 string to byte array
byte[] imageBytes = Convert.FromBase64String(base64Url);
// Check if byte array can be converted to image
using (MemoryStream ms = new MemoryStream(imageBytes))
{
Image.FromStream(ms);
}
return true;
}
catch
{
return false;
}
}
The function first checks if the base64 URL has a data URI scheme (data:image) and removes it if present. Then, it decodes the base64 string to a byte array and tries to create an Image object from it. If the byte array can be converted to an image, the function returns true. Otherwise, it returns false
原文地址: https://www.cveoy.top/t/topic/fQ8j 著作权归作者所有。请勿转载和采集!