写在前面
从浏览器的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
}
原文地址:https://blog.csdn.net/rjcql/article/details/134635280
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_34442.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。