我正在构建一个API,其中包括允许用户更改照片的API。这张照片作为base64字符串发送,我希望能够验证它是一个真正的.jpeg或.png格式。 由于.NET核心中缺少System.Drawing,我不知道该怎么做。之前我可以简单地使用像
这样的东西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;
}
}
然后从那里开始检查我对图像的需求。
任何帮助将不胜感激
答案 0 :(得分:1)
当你没有System.Drawing时,我会查看实际的字节,看看它们是否与JPEG或PNG文件标准相匹配。
对于PNG文件,前八个字节始终包含以下十进制值:@echo off
rem This iterates through all lines of `server.txt`;
rem `type` ensures the file to be read completely
rem before the any further activities are pursued;
rem `break` does nothing and is used to empty files:
for /F "delims=" %%S in ('
type "server.txt" ^& ^
^> "server.txt" break ^
^> "serverdone.txt" break
') do (
rem Call copying sub-routine for each item:
call :SUB_COPY %%S
if ErrorLevel 1 (
rem (`ErrorLevel` is `>=1`, so failure)
>> "server.txt" echo %%S
) else (
rem (`ErrorLevel` is `0`, so success)
>> "serverdone.txt" echo %%S
)
)
exit /B
:SUB_COPY
rem (do your copying stuff here, using `%1`;
rem in case of errors, set `ErrorLevel`)
exit /B 0 & rem (success: `ErrorLevel` is `0`)
exit /B 1 & rem (failure: `ErrorLevel` is `1`)
(Source)
JPEG文件更复杂,但也可以。至少前两个字节似乎总是137 80 78 71 13 10 26 10
(Source)。阅读有关文件结构的更多信息,以获得更好的比较值。
基于此,您可以对0xFF 0xD8
数组中的字节进行简单比较。