博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

net core 后端获取网络图片的扩展名

Posted on 2026-04-15 10:22  火冰·瓶  阅读(5)  评论(0)    收藏  举报

 

public static string GetImageExtension(byte[] bytes)
{
    if (bytes.Length < 12) return "unknown";
    if (bytes[0] == 0xFF && bytes[1] == 0xD8) return "jpg";
    if (bytes[0] == 0x89 && bytes[1] == 0x50) return "png";
    if (bytes[0] == 0x47 && bytes[1] == 0x49) return "gif";
    if (bytes[0] == 0x52 && bytes[1] == 0x49 && bytes[8] == 0x57 && bytes[9] == 0x45) return "webp";
    return "unknown";
}

  

使用:

HttpClient client = new HttpClient();  //正式环境不这样使用
var bytes = client.GetByteArrayAsync(url).Result;
string ext = Path.GetExtension(url);   //url以扩展名结尾的,先用库函数判断
if (string.IsNullOrEmpty(ext))
{
	ext= GetImageExtension(bytes);
}