/// <summary>
/// 封面图压缩
/// </summary>
/// <param name="coopCode">商家</param>
/// <param name="url">封面图源链接</param>
/// <returns>本地封面图链接</returns>
protected string DownUrltoFile(string coopCode, string url)
{
try
{
//根目录
string saveDirection = ConfigurationManager.AppSettings["ImgChangeSavePath"];

//不存在则创建
if (!System.IO.Directory.Exists(saveDirection))
{
System.IO.Directory.CreateDirectory(saveDirection);
}

//每个商家的文件夹名称
string coopCodePath = saveDirection + "\\" + coopCode;

//不存在则创建
if (!System.IO.Directory.Exists(coopCodePath))
{
System.IO.Directory.CreateDirectory(coopCodePath);
}

//每个商家下的日期文件夹(年月)
string date = DateTime.Now.ToString("yyyyMM");

string SavePath = coopCodePath + "\\" + date;
//不存在则创建
if (!System.IO.Directory.Exists(SavePath))
{
System.IO.Directory.CreateDirectory(SavePath);
}

//文件名
string fileName = Guid.NewGuid() + ".jpg";

//创建一个request 同时可以配置requst其余属性
System.Net.WebRequest imgRequst = System.Net.WebRequest.Create(url);
HttpWebResponse mResponse = (HttpWebResponse)imgRequst.GetResponse();

//文件大小
int aSize = Convert.ToInt32((mResponse.ContentLength / 1024).ToString());

if (aSize > 15) //大于15kb进行压缩
{
//在这里以流的方式保存图片
System.Drawing.Image downImage = System.Drawing.Image.FromStream(mResponse.GetResponseStream());

Bitmap map = new Bitmap(downImage, 120, 90);
System.Drawing.Image newImg = map;

EncoderParameters encoderParams = new EncoderParameters();
long[] quality = new long[1];
quality[0] = 90; //压缩比例,决定图片大小的重要因素。
EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
encoderParams.Param[0] = encoderParam;

newImg.Save(SavePath + "\\" + fileName, GetCodecInfo("image/jpeg"), encoderParams);//保存
newImg.Dispose();//用完要释放
downImage.Dispose();//用完要释放

string getDirection = ConfigurationManager.AppSettings["GetImgPath"] + "ImgChangeSavePath/" + coopCode + "/" + date + "/" + fileName;//保存在本地服务器的地址

return getDirection;
}
else
{
return url;
}
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}

/// <summary>
/// 保存JPG时用
/// </summary>
/// <param name="mimeType"></param>
/// <returns>得到指定mimeType的ImageCodecInfo</returns>
private ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in CodecInfo)
{
if (ici.MimeType == mimeType) return ici;
}
return null;
}

 posted on 2015-08-19 15:34  代码改变世界&1024  阅读(212)  评论(0编辑  收藏  举报