C#保存图片、压缩图片大小、缩放图片比例

一、保存web网络图片

/// <summary>
/// 保存web图片到本地
/// </summary>
/// <param name="FileName"></param>
/// <param name="Url"></param>
/// <returns></returns>
public static bool SavePhotoFromUrl(string FileName, string Url)
{
    bool value = false;
    WebResponse response = null;
    Stream stream = null;

    try
    {
        WebRequest request = WebRequest.Create(Url);
        response = request.GetResponse();
        stream = response.GetResponseStream();

        if (!response.ContentType.ToLower().StartsWith("text/"))
        {
            value = SaveBinaryFile(response, FileName);
        }

    }
    catch (Exception err)
    {
        string aa = err.ToString();
    }
    return value;
}

/// <summary>
/// 保存图片
/// </summary>
/// <param name="response"></param>
/// <param name="FileName"></param>
/// <returns></returns>
public static bool SaveBinaryFile(WebResponse response, string FileName)
{
    bool Value = true;
    byte[] buffer = new byte[1024];

    try
    {
        if (File.Exists(FileName))
        {
            DeleteFile(Application.StartupPath + "\\" + FileName);
        }

        Stream outStream = System.IO.File.Create(FileName);
        Stream inStream = response.GetResponseStream();

        int l;
        do
        {
            l = inStream.Read(buffer, 0, buffer.Length);
            if (l > 0)
                outStream.Write(buffer, 0, l);
        }
        while (l > 0);

        outStream.Close();
        inStream.Close();
    }
    catch
    {
        Value = false;
    }

    return Value;
}

二、压缩图片大小

/// <summary>
/// 图片压缩
/// </summary>
/// <param name="sFile">原文件路径</param>
/// <param name="dFile">新文件路径</param>
/// <param name="flag"></param>
/// <param name="sfsc"></param>
/// <returns></returns>
public static bool CompressImage(string sFile, ref string dFile, int flag = 90, bool sfsc = true)
{
   // 读取设置的文件大小为多少kb
   int size = int.Parse(SysContent.tabOneConfigDic["compressImageSize"]);
   Image iSource = Image.FromFile(sFile);
   ImageFormat tFormat = iSource.RawFormat;
   //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
   FileInfo firstFileInfo = new FileInfo(sFile);
   if (sfsc == true && firstFileInfo.Length < size * 1024)
   {
       if (File.Exists(dFile))
       {
           DeleteFile(dFile);
       }
       firstFileInfo.CopyTo(dFile);
       return true;
   }

   int dHeight = iSource.Height / 2;
   int dWidth = iSource.Width / 2;
   int sW = 0, sH = 0;
   //按比例缩放
   Size tem_size = new Size(iSource.Width, iSource.Height);
   if (tem_size.Width > dHeight || tem_size.Width > dWidth)
   {
       if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
       {
           sW = dWidth;
           sH = (dWidth * tem_size.Height) / tem_size.Width;
       }
       else
       {
           sH = dHeight;
           sW = (tem_size.Width * dHeight) / tem_size.Height;
       }
   }
   else
   {
       sW = tem_size.Width;
       sH = tem_size.Height;
   }

   Bitmap ob = new Bitmap(dWidth, dHeight);
   Graphics g = Graphics.FromImage(ob);

   g.Clear(Color.WhiteSmoke);
   g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
   g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
   g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

   g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

   g.Dispose();

   //以下代码为保存图片时,设置压缩质量
   EncoderParameters ep = new EncoderParameters();
   long[] qy = new long[1];
   qy[0] = flag;//设置压缩的比例1-100
   EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
   ep.Param[0] = eParam;

   try
   {
       ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
       ImageCodecInfo jpegICIinfo = null;
       for (int x = 0; x < arrayICI.Length; x++)
       {
           if (arrayICI[x].FormatDescription.Equals("JPEG"))
           {
               jpegICIinfo = arrayICI[x];
               break;
           }
       }
       if (jpegICIinfo != null)
       {
           ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
           FileInfo fi = new FileInfo(dFile);
           if (fi.Length > 1024 * size)
           {
               flag = flag - 10;
               CompressImage(sFile, ref dFile, flag, false);
           }
       }
       else
       {
           ob.Save(dFile, tFormat);
       }
       return true;
   }
   catch
   {
       return false;
   }
   finally
   {
       iSource.Dispose();
       ob.Dispose();
   }
}

三、缩放图片比例

/// <summary>
/// 生成高清缩略图片方法
/// </summary>
/// <param name="image"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
public static Image GetThumbnail(Image image, int width, int height)
{
    Bitmap bmp = new Bitmap(width, height);
    //从Bitmap创建一个System.Drawing.Graphics
    System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
    //设置 
    gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
    //下面这个也设成高质量
    gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
    //下面这个设成High
    gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
    //把原始图像绘制成上面所设置宽高的缩小图
    System.Drawing.Rectangle rectDestination = new Rectangle(0, 0, width, height);

    gr.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
    return bmp;
}

/// <summary>
/// 获取图片
/// </summary>
/// <param name="path"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
public static Image GetImage(string path, int width, int height)
{
    try
    {
        string newPath = "";
        if (File.Exists(Application.StartupPath + path))
        {
            newPath = Application.StartupPath + path;
        }
        else
        {//如果图片不存在,使用默认图片
            //newPath = Application.StartupPath + LocalConfig.defaultPicPath;
        }
        FileStream fs = new FileStream(newPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        Image result = Image.FromStream(fs);
        fs.Close();
        result = GetThumbnail(result, width, height);
        return result;
    }
    catch (Exception e)
    {
        return null;
    }
}

四、删除图片

/// <summary>
/// 删除文件
/// </summary>
/// <param name="filePath"></param>
public static void DeleteFile(string filePath)
{
    if (File.Exists(Path.GetFullPath(filePath)))
    {
        File.Delete(Path.GetFullPath(filePath));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哎呦喂O_o嗨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值