分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

【aspnetcore】抓取远程图片

发布时间:2023-09-06 02:31责任编辑:傅花花关键词:暂无标签

找到要抓取的图片地址:http://i.imgur.com/8S7OaEB.jpg

抓取的步骤:

  1. 请求图片路径
  2. 获取返回的数据
  3. 将数据转换为stream
  4. 将stream转换为Image
  5. 保存Image

明晰了步骤,接下来就简单了,直接上代码

public class RemoteImageCatchUtil{ ???private static string[] ImageExts = new[] { "jpg", "jpeg", "png", "bitmap", "gif" }; ???public static string Catch(string remoteImagePath, string saveFolder, int timeout = 2000) ???{ ???????try ???????{ ???????????var request = WebRequest.Create(remoteImagePath) as HttpWebRequest; ???????????request.Timeout = timeout > 0 ? timeout : 1000; ???????????using (var response = request.GetResponse() as HttpWebResponse) ???????????{ ???????????????if (response.StatusCode != HttpStatusCode.OK) ???????????????{ ???????????????????throw new Exception("远程访问失败"); ???????????????} ???????????????else ???????????????{ ???????????????????var ext = GetImageExtension(response.ContentType).ToLower(); ???????????????????if (!ImageExts.Contains(ext)) ???????????????????{ ???????????????????????throw new Exception("非图片文件"); ???????????????????} ???????????????????var stream = response.GetResponseStream(); ???????????????????var buffer = new byte[2048]; ???????????????????int count; ???????????????????using (var ms = new MemoryStream()) ???????????????????{ ???????????????????????while ((count = stream.Read(buffer, 0, buffer.Length)) != 0) ???????????????????????{ ???????????????????????????ms.Write(buffer, 0, count); ???????????????????????} ???????????????????????if (!Directory.Exists(saveFolder)) ???????????????????????{ ???????????????????????????Directory.CreateDirectory(saveFolder); ???????????????????????} ???????????????????????var imageName = Path.GetRandomFileName() + "." + ext; ???????????????????????var imagePath = Path.Combine(saveFolder, imageName); ???????????????????????var image = new Bitmap(ms); ???????????????????????image.Save(imagePath); ???????????????????????return imageName; ???????????????????} ???????????????} ???????????} ???????} ???????catch(Exception ex) ???????{ ???????????throw ex; ???????} ???} ???private static string GetImageExtension(string contentType) ???{ ???????if (contentType.StartsWith("image")) ???????{ ???????????return contentType.Split(@"/").Last(); ???????} ???????return string.Empty; ???}}

注意,这里的代码仅供测试,使用时请自行完善。

【aspnetcore】抓取远程图片

原文地址:https://www.cnblogs.com/diwu0510/p/10336444.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved