C# 获取远程图片并裁剪

public Image SaveImg(string url)
{
    Image image = GetImg(url);
    if (image != null)
    {
        image.SaveFile(path);
    }
    return image;
}
 
public Image GetImg(string url)
{
    HttpWebRequest wr = (HttpWebRequest)GetWebRequest(new Uri(url));
    wr.CookieContainer = cc;
    wr.Method = "GET";
    try
    {
        HttpWebResponse wrs = (HttpWebResponse)wr.GetResponse();
        cc.Add(wrs.Cookies);
        System.IO.Stream s = wrs.GetResponseStream();
        //Image img = Image.FromStream(s);
 
        //裁剪图片,不包含底部的水印,2020/09/15修改
        Bitmap bmp_img = Image.FromStream(s) as Bitmap;
        Image img = crop(bmp_img, bmp_img.Width, bmp_img.Height - 100) as Image;
         
        s.Close();
        wrs.Close();
        wr.Abort();
        return img;
    }
    catch (Exception)
    {
        return null;
    }
}
 
//裁剪函数
public Bitmap crop(Bitmap src,int width,int height)
{
    Rectangle cropRect = new Rectangle(0, 0, width, height);
    Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
 
    using (Graphics g = Graphics.FromImage(target))
    {
        g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height),
              cropRect,
              GraphicsUnit.Pixel);
    }
    return target;
}


by 雪洁 2020-09-15 07:11:18 753 views
我来说几句

相关文章