C# 图片下载工具类
写在前面
从浏览器的Html文本中获取图片链接并保存到本地,同时对图片的分辨率和品质进行处理,以满足某些平台的规格需求;可以放到多线程中调用以提高下载效率。
代码实现
public class ImageDownloader
{
private int minImageSize = 1024 * 10;
private int limitImageSize = 1024 * 1024;
public Image SaveWebImage(string url, string savePath)
{
try
{
if (url.EndsWith("gif"))
return null;
using (var c = new WebClient())
{
string imgUrl = url;
if (imgUrl.StartsWith("//"))
{
imgUrl = "http:" + imgUrl;
}
var img = Image.FromStream(new MemoryStream(c.DownloadData(imgUrl)));
// 小图直接略过
if (img.Width < 200 || img.Height < 200)
return null;
var r = Resize(img, 640, 640, true);
r.Save(savePath);
var fileInfo = new FileInfo(savePath);
if (fileInfo.Length < minImageSize) // 如果小于10kb那就是无效图片
return r;
if (fileInfo.Length > limitImageSize) // 品质可以通过参数来控制
{
EncoderParameters encoderParams = new EncoderParameters();
long[] quality = new long[1];
quality[0] = 85; // 品质参数,最大为100
EncoderParameter encoderParam = new EncoderParameter(Encoder.Quality, quality);
encoderParams.Param[0] = encoderParam;
ImageCodecInfo codecInfo = GetEncoder(ImageFormat.Jpeg);
r.Save(savePath, codecInfo, encoderParams);
encoderParam.Dispose();
encoderParams.Dispose();
}
img.Dispose();
return r;
}
}
catch (Exception ex)
{
LogHelper.Error(ex);
LogHelper.Error("error url:" + url);
return null;
}
}
public Image Resize(Image image, int newWidth, int maxHeight, bool onlyResizeIfWider)
{
if (onlyResizeIfWider && image.Width <= newWidth) newWidth = image.Width;
var newHeight = image.Height * newWidth / image.Width;
var res = new Bitmap(newWidth, newHeight);
using (var graphic = Graphics.FromImage(res))
{
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.CompositingQuality = CompositingQuality.HighQuality;
graphic.DrawImage(image, 0, 0, newWidth, newHeight);
}
return res;
}
#region Private Methods
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
#endregion
}