C# 请求图片类型判断webp

之前下载图片不了,在获取流的时候有数据的,就是保存不了。就类型对不上,只能加个判断。

加的代码:


if (w.ResponseHeaders.AllKeys.FirstOrDefault(f=>f.Contains("Content")&& f.Contains("Type"))!=null)
{
    var ct = w.ResponseHeaders.AllKeys.FirstOrDefault(f => f.Contains("Content") && f.Contains("Type"));
    var ct_value = w.ResponseHeaders[ct.ToString()];
    if (ct_value!=null && ct_value.Contains("webp"))
    {
        ContentType = ct_value.ToString();
    }
}

if (ContentType!=null && bs.Length > 0 && ContentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
{
    // MessageBox.Show(System.Text.Encoding.UTF8.GetString(bs).Substring(0, 1000));
    if (ContentType.ToLower().EndsWith("webp") || ContentType.ToLower().EndsWith("avif"))
    {

        using (var client = new System.Net.WebClient())
        {
            var bytes = client.DownloadData(imgurl);
            using (var m = new MemoryStream(bytes))
            {
                var mimg = new ImageMagick.MagickImage(m);
                mimg.Write(filename, ImageMagick.MagickFormat.Jpg);
            }
        }

    }
    else
    {

        using (MemoryStream m = new MemoryStream(bs))
        {
            using (System.Drawing.Image img = System.Drawing.Image.FromStream(m))
            {
                img.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
    }

    isDown = true;
}

你可能感兴趣的:(c#)