I'm building an API that among other things allows users to change their photo. This photo is sent in as a base64 string and I want to be able to validate that it's an actual .jpeg or .png format. Since System.Drawing is missing in .NET core i'm not sure how to go about doing this. Before i could have simply used something like
public Image Base64ToImage(string base64String)
{
// Convert base 64 string to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
// Convert byte[] to Image
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
Image image = Image.FromStream(ms, true);
return image;
}
}
and then gone from there to check what i needed about the Image.
Any help would be appreciated
When you don't have System.Drawing I would look at the actual bytes instead to see if they match the JPEG or PNG file standard.
For a PNG file the first eight bytes always contains the following decimal values: 137 80 78 71 13 10 26 10
(Source)
A JPEG file is more complex but it can be done as well. The first two bytes, at least, seems to always be 0xFF 0xD8
(Source). Read a bit more about the file structure to get better comparison values.
Based on this you can do a simple comparison on the bytes in your imageBytes
array.