1. public class ImageHelper
  2. {
  3. /// <summary>
  4. /// 图片转换成字节流
  5. /// </summary>
  6. /// <param name="img">要转换的Image对象</param>
  7. /// <returns>转换后返回的字节流</returns>
  8. public static byte[] ImgToByt(Image img)
  9. {
  10. MemoryStream ms = new MemoryStream();
  11. byte[] imagedata = null;
  12. img.Save(ms, ImageFormat.Jpeg);
  13. imagedata = ms.GetBuffer();
  14. return imagedata;
  15. }
  16.  
  17. /// <summary>
  18. /// 字节流转换成图片
  19. /// </summary>
  20. /// <param name="byt">要转换的字节流</param>
  21. /// <returns>转换得到的Image对象</returns>
  22. public static Image BytToImg(byte[] byt)
  23. {
  24. MemoryStream ms = new MemoryStream(byt);
  25. Image img = Image.FromStream(ms);
  26. return img;
  27. }
  28.  
  29. /// <summary>
  30. /// 根据图片路径返回图片的字节流byte[]
  31. /// </summary>
  32. /// <param name="imagePath">图片路径</param>
  33. /// <returns>返回的字节流</returns>
  34. private static byte[] GetImageByte(string imagePath)
  35. {
  36. Stream files;
  37. try
  38. {
  39. //如果本地含有图片则从本地读取,反之从服务器下载
  40. var localurl = AppDomain.CurrentDomain.BaseDirectory + imagePath.Substring(imagePath.IndexOf('D'));
  41. files = new FileStream(localurl, FileMode.Open);
  42. }
  43. catch
  44. {
  45. files = DownLoadImage(imagePath);
  46. }
  47.  
  48. byte[] imgByte = new byte[files.Length];
  49. files.Read(imgByte, , imgByte.Length);
  50. files.Close();
  51. return imgByte;
  52. }
  53.  
  54. /// <summary>
  55. /// 将图片下载到流
  56. /// </summary>
  57. /// <param name="path">图片路径</param>
  58. /// <returns></returns>
  59. public static Stream DownLoadImage(string path)
  60. {
  61. WebRequest request = WebRequest.Create(@path);
  62. WebResponse response = request.GetResponse();
  63. return response.GetResponseStream();
  64. }
  65.  
  66. public static bool ThumbnailCallback()
  67. {
  68. return false;
  69. }
  70.  
  71. /// <summary>
  72. /// 字节流转换成图片路径
  73. /// </summary>
  74. /// <param name="byt">要转换的字节流</param>
  75. /// <param name="id">用户Id</param>
  76. /// <param name="catalogPath">存储目录</param>
  77. /// <returns>转换得到的Image对象</returns>
  78. public static string GetImageUrl(string id,byte[] byt,string catalogPath)
  79. {
  80. string catalog = "DownLoads/" + catalogPath;
  81. var filename = id + ".jpg";
  82. var path = string.Format("{0}/{1}", catalog, filename);
  83. var existpath = AppDomain.CurrentDomain.BaseDirectory + @path;
  84. if (File.Exists(@existpath))
  85. {
  86. return BaseHelper.GetValue("Server") + path;
  87. }
  88. else
  89. {
  90. MemoryStream ms = new MemoryStream(byt);
  91. Image img = Image.FromStream(ms);
  92.  
  93. string root = AppDomain.CurrentDomain.BaseDirectory + catalog;
  94. if (!Directory.Exists(@root))
  95. {
  96. Directory.CreateDirectory(@root);
  97. }
  98.  
  99. img.Save(AppDomain.CurrentDomain.BaseDirectory + @path);
  100. return BaseHelper.GetValue("Server") + @path;
  101. }
  102. }
  103.  
  104. /// <summary>
  105. /// 获取缩略图路径
  106. /// </summary>
  107. /// <param name="id"></param>
  108. /// <param name="url"></param>
  109. /// <param name="catalogPath"></param>
  110. /// <param name="size"></param>
  111. /// <returns></returns>
  112. public static string GetThumbnailUrl(string id, string url, string catalogPath,int size)
  113. {
  114. string catalog = "DownLoads/" + catalogPath;
  115. var filename = id + ".jpg";
  116. var path = string.Format("{0}/{1}", catalog, filename);
  117. var existpath = AppDomain.CurrentDomain.BaseDirectory + path;
  118. if (File.Exists(@existpath))
  119. {
  120. return BaseHelper.GetValue("Server") + @path;
  121. }
  122. else
  123. {
  124. FileStream ms = new FileStream(@url, FileMode.Open);
  125. Image img = Image.FromStream(ms);
  126.  
  127. //压缩图片大小
  128. var myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
  129. Image myThumbnail = img.GetThumbnailImage(size, size, myCallback, IntPtr.Zero);
  130.  
  131. string root = AppDomain.CurrentDomain.BaseDirectory + catalog;
  132. if (!Directory.Exists(@root))
  133. {
  134. Directory.CreateDirectory(@root);
  135. }
  136.  
  137. myThumbnail.Save(AppDomain.CurrentDomain.BaseDirectory + @path);
  138. return BaseHelper.GetValue("Server") + path;
  139. }
  140. }
  141.  
  142. /// <summary>
  143. /// 判断用户图片是否已缓存
  144. /// </summary>
  145. /// <param name="filename"></param>
  146. /// <returns></returns>
  147. public static string IsExist(string filename)
  148. {
  149. var filepath = @"DownLoads/Temp/" + filename + ".jpg";
  150. var path = AppDomain.CurrentDomain.BaseDirectory + @filepath;
  151. return File.Exists(@path) ? BaseHelper.GetValue("Server") + @filepath : string.Empty;
  152. }
  153.  
  154. /// <summary>
  155. /// 获取用户的Base64缩略图
  156. /// </summary>
  157. /// <param name="stream">图片流</param>
  158. /// <param name="width">缩略图宽度</param>
  159. /// <param name="height">缩略图宽度</param>
  160. /// <param name="isfixWidthHeight">是否固定高宽</param>
  161. /// <returns></returns>
  162. public static string GetBase64Image(int width,int height, Stream stream,bool isfixWidthHeight=false)
  163. {
  164. try
  165. {
  166. Image img = Image.FromStream(stream);
  167. //var id = BaseHelper.CreateGuid();
  168. //压缩图片大小
  169. var myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
  170. Image myThumbnail;
  171. if (isfixWidthHeight)
  172. {
  173. myThumbnail = img.GetThumbnailImage(width, height, myCallback, IntPtr.Zero);
  174. }
  175. else
  176. {
  177. int startX = ,startY=;
  178. var w = img.Width;
  179. var h = img.Height;
  180. int getX = w, getY = h;
  181. float dw =(float) w/width;
  182. float dh =(float) h/height;
  183. if (Equals(dw, dh))
  184. {
  185. myThumbnail = img.GetThumbnailImage(width, height, myCallback, IntPtr.Zero);
  186. }
  187. else
  188. {
  189. //按比例截取中间部分
  190. if (dw > dh)
  191. {
  192. getX = Convert.ToInt32(width * dh);
  193. startX = Convert.ToInt32((w - getX) / );
  194. }
  195. else
  196. {
  197. getY = Convert.ToInt32(height * dw);
  198. startY = Convert.ToInt32((h - getX)/);
  199. }
  200.  
  201. Bitmap destBitmap = new Bitmap(getX, getY);//目标图
  202. Rectangle destRect = new Rectangle(, , getX, getY); //生成图区域
  203. Rectangle srcRect = new Rectangle(startX, startY, getX, getY);//截取区域
  204. Graphics g = Graphics.FromImage(destBitmap);
  205. g.DrawImage(img, destRect, srcRect, GraphicsUnit.Pixel);
  206. //SaveImage(destBitmap,id + "_Src");
  207. myThumbnail = destBitmap.GetThumbnailImage(width, height, myCallback, IntPtr.Zero);
  208. }
  209. }
  210. //SaveImage(myThumbnail,id+"_Thu");
  211.  
  212. //将压缩图片转为Base64字符串
  213. return ImageToBase64(myThumbnail);
  214. }
  215. catch
  216. {
  217. return null;
  218. }
  219.  
  220. }
  221.  
  222. /// <summary>
  223. /// 将图片流转为base64编码
  224. /// </summary>
  225. /// <param name="stream"></param>
  226. /// <returns></returns>
  227. public static string GetBase64Image(Stream stream)
  228. {
  229. Image img = Image.FromStream(stream);
  230. return ImageToBase64(img);
  231. }
  232.  
  233. /// <summary>
  234. /// 获取用户的Base64缩略图
  235. /// </summary>
  236. /// <param name="byt">图片存储字节</param>
  237. /// <param name="width">缩略图宽度</param>
  238. /// <param name="height">缩略图宽度</param>
  239. /// <returns></returns>
  240. public static string GetBase64Image(int width, int height, byte[] byt)
  241. {
  242. MemoryStream ms = new MemoryStream(byt);
  243. return GetBase64Image(width,height,ms);
  244. }
  245.  
  246. /// <summary>
  247. /// 将图片字节转为base64编码
  248. /// </summary>
  249. /// <param name="byt"></param>
  250. /// <returns></returns>
  251. public static string GetBase64Image(byte[] byt)
  252. {
  253. MemoryStream stream = new MemoryStream(byt);
  254. Image img = Image.FromStream(stream);
  255. return ImageToBase64(img);
  256. }
  257.  
  258. /// <summary>
  259. /// 获取用户的Base64缩略图
  260. /// </summary>
  261. /// <param name="imagePath">图片存储路径</param>
  262. /// <param name="width">缩略图宽度</param>
  263. /// <param name="height">缩略图宽度</param>
  264. /// <returns></returns>
  265. public static string GetBase64Image(int width, int height, string imagePath)
  266. {
  267. var stream = DownLoadImage(imagePath);
  268. return GetBase64Image(width, height, stream);
  269. }
  270.  
  271. /// <summary>
  272. /// 将图片数据转换为Base64字符串
  273. /// </summary>
  274. /// <param name="img"></param>
  275. public static string ImageToBase64(Image img)
  276. {
  277. return "data:image/jpg;base64," + Convert.ToBase64String(ImgToByt(img));
  278. }
  279.  
  280. /// <summary>
  281. /// 将图片流转换为Base64字符串
  282. /// </summary>
  283. /// <param name="ms"></param>
  284. /// <returns></returns>
  285. private static string StreamToBase64(MemoryStream ms)
  286. {
  287. return "data:image/gif;base64," + Convert.ToBase64String(ms.GetBuffer());
  288. }
  289.  
  290. /// <summary>
  291. /// 将Base64字符串转换为图片
  292. /// </summary>
  293. /// <param name="str"></param>
  294. private static Image Base64ToImage(string str)
  295. {
  296. byte[] bytes = Convert.FromBase64String(str);
  297. return BytToImg(bytes);
  298. }
  299.  
  300. /// <summary>
  301. /// 导出图片
  302. /// </summary>
  303. /// <param name="img">图片</param>
  304. /// <param name="fileName">文件名</param>
  305. private static void SaveImage(Image img,string fileName=null)
  306. {
  307. string root = AppDomain.CurrentDomain.BaseDirectory + "DownLoads/Thumbnail";
  308. if (!Directory.Exists(@root))
  309. {
  310. Directory.CreateDirectory(@root);
  311. }
  312. string path = fileName == null ? @root + "/" + BaseHelper.CreateGuid() + ".jpg" : @root + "/" + fileName + ".jpg";
  313.  
  314. img.Save(path);
  315. }
  316.  
  317. /// <summary>
  318. /// 裁剪图片
  319. /// </summary>
  320. /// <param name="stream">图片流</param>
  321. /// <param name="startX">开始坐标X</param>
  322. /// <param name="startY">开始坐标Y</param>
  323. /// <param name="getX">截取横向距离</param>
  324. /// <param name="getY">截取纵向距离</param>
  325. /// <returns>图片base64编码</returns>
  326. public static string CutImage(Stream stream, int startX, int startY, int getX, int getY)
  327. {
  328. Image img = Image.FromStream(stream);
  329.  
  330. int w = img.Width;
  331. int h = img.Height;
  332.  
  333. if (startX < w && startY < h)
  334. {
  335. if (getX + startX > w)
  336. {
  337. getX = w - startX;
  338. }
  339. if (startY + getY > h)
  340. {
  341. getY = h - startY;
  342. }
  343. }
  344. //var id = BaseHelper.CreateGuid();
  345.  
  346. Bitmap destBitmap = new Bitmap(getX, getY);//目标图
  347. Rectangle destRect = new Rectangle(, , getX, getY); //生成图区域
  348. Rectangle srcRect = new Rectangle(startX, startY, getX, getY);//截取区域
  349. Graphics g = Graphics.FromImage(destBitmap);
  350. g.DrawImage(img, destRect, srcRect, GraphicsUnit.Pixel);
  351. //SaveImage(destBitmap,id + "_Src");
  352. return ImageToBase64(destBitmap);
  353. }
  354.  
  355. /// <summary>
  356. /// 生成验证码
  357. /// <param name="width">验证码宽度</param>
  358. /// <param name="height">验证码高度</param>
  359. /// </summary>
  360. public static void DrawVerifyCode(int width=,int height=)
  361. {
  362. MemoryStream ms = new MemoryStream();
  363. DrawValidationCode validationCode = new DrawValidationCode {FontMinSize = , FontMaxSize = };
  364. if (width != ) validationCode.Width = width;
  365. if (height != ) validationCode.Height = height;
  366.  
  367. validationCode.CreateImage(ms);
  368.  
  369. var id = BaseHelper.CreateGuid(); //生成ID
  370. var code = validationCode.ValidationCode; //验证码字符串
  371. var image = StreamToBase64(ms); //验证码图片
  372. var createTime = DateTime.Now; //生成时间
  373.  
  374. //将图片存储到本地
  375. string root = AppDomain.CurrentDomain.BaseDirectory + "DownLoads/VerifyCode";
  376. if (!Directory.Exists(@root))
  377. {
  378. Directory.CreateDirectory(@root);
  379. }
  380. Image img = Image.FromStream(ms);
  381. img.Save(@root + "/" + id + ".jpg");
  382. }
  383.  
  384. /// <summary>
  385. /// 根据姓名生成默认缩略图
  386. /// </summary>
  387. /// <param name="name">姓名</param>
  388. /// <param name="width"></param>
  389. /// <param name="height"></param>
  390. /// <returns></returns>
  391. public static string DrawDefaultIcon(string name,int width=,int height=)
  392. {
  393. if (!string.IsNullOrEmpty(name))
  394. {
  395. var text = name.Substring(, );
  396. Bitmap bit = new Bitmap(width + , height + );
  397. Graphics g = Graphics.FromImage(bit);
  398. g.SmoothingMode = SmoothingMode.HighQuality;
  399. g.Clear(Color.Transparent);
  400. Rectangle rectangle = new Rectangle(, , width, height);
  401. // 如要使边缘平滑,请取消下行的注释
  402. g.SmoothingMode = SmoothingMode.HighQuality;
  403.  
  404. //设置文本背景色
  405. SolidBrush[] sbrush =
  406. {
  407. new SolidBrush(Color.FromArgb(,,)),
  408. new SolidBrush(Color.FromArgb(,,)),
  409. new SolidBrush(Color.FromArgb(,,)),
  410. new SolidBrush(Color.FromArgb(,,)),
  411. new SolidBrush(Color.FromArgb(,,)),
  412. new SolidBrush(Color.FromArgb(,,)),
  413. new SolidBrush(Color.FromArgb(,,)),
  414. new SolidBrush(Color.FromArgb(,,)),
  415. new SolidBrush(Color.FromArgb(,,))
  416. };
  417.  
  418. Random r=new Random();
  419. //Thread.Sleep(10);
  420. g.FillEllipse(sbrush[r.Next(sbrush.Length)], rectangle);
  421.  
  422. Font font = new Font(new FontFamily("微软雅黑"), , FontStyle.Regular);
  423.  
  424. g.DrawString(text, font, new SolidBrush(Color.White), new Rectangle(, , width, height), new StringFormat { Alignment = StringAlignment.Center });
  425.  
  426. MemoryStream ms = new MemoryStream();
  427. bit.Save(ms, ImageFormat.Png);
  428. return "data:image/png;base64," + Convert.ToBase64String(ms.GetBuffer());
  429. }
  430. return null;
  431. }
  432. }

C#关于图片的相关处理的更多相关文章

  1. 渐进式jpeg(progressive jpeg)图片及其相关 --图片的两种加载方式

    渐进式jpeg(progressive jpeg)图片及其相关   一.基本JPEG(baseline jpeg)和渐进JPEG 网络上那些色色的照片都是.jpg格式的("色色"指 ...

  2. css图片的相关操作

    css图片的相关操作 1.案例源码 <!DOCTYPE html><html lang="en"><head> <meta charset ...

  3. SAP Leonardo图片处理相关的机器学习服务在SAP智能服务场景中的应用

    本文作为Jerry最近正在做的一个项目的工作思路的梳理. 我们假设这样一个服务场景,技师上门维修某设备,发现设备上某零件损坏了,假设这位技师由于种种原因,没能根据自己的经验识别出这个零件的型号.此时技 ...

  4. Android中图片处理相关问题

    在Android的开发中,我们经常回去处理一些图片相关的问题,比如当加载图片到内存中产生的OOM(OutOfMemory)异常.图片加载到内存中占多大内存的问题.jpg png两种常见的图片的原理及区 ...

  5. ASP.NET、JAVA跨服务器远程上传文件(图片)的相关解决方案整合

    一.图片提交例: A端--提交图片 protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string u ...

  6. nginx图片处理相关

    nginx本身有支持图片处理的模块,通过外部插件也可以实现此功能. libgd的安装 前提是要有libgd的库文件, (1)去官网访问主页没问题,下载文件还是FQ下的,为了方便大家提供一个链接:htt ...

  7. 渐进式jpeg(progressive jpeg)图片及其相关

    最近看有些网站上的jpg格式的图片在呈现的时候,有两种方式,一种是自上而下扫描式的,还有一种就是先是全部的模糊图片,然后逐渐清晰(就像GIF格式的交错显示). 一.基本JPEG(baseline jp ...

  8. HTML - 图片标签相关

    <html> <head></head> <body> <!-- src : 图片的路径 (本地资源路径, 网络资源路径) title : 图片的 ...

  9. 单行中文字和图片的相关height和line-height特性

    这几天在做仿京东的产品页,发现在制作过程中的一些问题,需要好好研究下. 需要实现的效果如上图所示: 在写CSS样式的时候,对于我的关于竖线的做法是: 设置高度为14,border样式,但导致了一个问题 ...

随机推荐

  1. 如何区分MNO和MVNO

    MVNO(Mobile Virtaul Network Operator)虚拟网络运营商,没有自己的物理网络,租用MNO(Mobile Network Operator)网络提供的网络服务. 我们知道 ...

  2. Android访问设置

    在需求 AndroidManifest.xml 中增加下面代码: (1)假设应用程序须要訪问网络权限 <uses-permission android:name="android.pe ...

  3. POJ 1176 Party Lamps (DFS)

    对于一束灯光.提供四种改变彩灯状态(ON<=>OFF)的操作:a.改变全部彩灯状态:b.改变奇数彩灯状态.c.改变偶数彩灯状态:d.改变3k+1号彩灯状态(1,4,7,10...). 给定 ...

  4. 【Android进阶】获取Android软件的版本信息

    PackageInfo pinfo = getPackageManager().getPackageInfo("com.andbase", PackageManager.GET_C ...

  5. Net中的反应式编程

    Net中的反应式编程(Reactive Programming)   系列主题:基于消息的软件架构模型演变 一.反应式编程(Reactive Programming) 1.什么是反应式编程:反应式编程 ...

  6. 马云收购UC你,至于到底是谁宣战

    近日,阿里巴巴官方正式宣布,UC优视全资融入阿里巴巴集团,并组建阿里UC移动事业群. 据阿里方面表示,整个交易对UC的估值远超百度对91无线的估值,外界推測估值近50美元.是中国互联网最大一笔交易.业 ...

  7. super.getClass()与this.getClass()

    原文地址:http://leihuang.org/2014/11/14/getClass-method/ 首先看一段代码: import java.util.Date; public class Te ...

  8. 第十二章——SQLServer统计信息(3)——发现过期统计信息并处理

    原文:第十二章--SQLServer统计信息(3)--发现过期统计信息并处理 前言: 统计信息是关于谓词中的数据分布的主要信息源,如果不知道具体的数据分布,优化器不能获得预估的数据集,从而不能统计需要 ...

  9. CSDN个人空间能再烂吗?

    CSDN空间你敢再烂么? 从CSDN博客跳转到CSDN个人空间的入口还算明显,可是想从个人空间跳转到博客,可真是众里寻他千百度.跳转接口怎么寻都寻不到.根本没有这个跳转的入口.唯一的途径仅仅能从写博文 ...

  10. 我的java学习笔记(一)

    第一个java程序,还是熟悉的hello world public class FirstSample { //类 public static void main(String[] args) //方 ...