C#关于图片的相关处理
- public class ImageHelper
- {
- /// <summary>
- /// 图片转换成字节流
- /// </summary>
- /// <param name="img">要转换的Image对象</param>
- /// <returns>转换后返回的字节流</returns>
- public static byte[] ImgToByt(Image img)
- {
- MemoryStream ms = new MemoryStream();
- byte[] imagedata = null;
- img.Save(ms, ImageFormat.Jpeg);
- imagedata = ms.GetBuffer();
- return imagedata;
- }
- /// <summary>
- /// 字节流转换成图片
- /// </summary>
- /// <param name="byt">要转换的字节流</param>
- /// <returns>转换得到的Image对象</returns>
- public static Image BytToImg(byte[] byt)
- {
- MemoryStream ms = new MemoryStream(byt);
- Image img = Image.FromStream(ms);
- return img;
- }
- /// <summary>
- /// 根据图片路径返回图片的字节流byte[]
- /// </summary>
- /// <param name="imagePath">图片路径</param>
- /// <returns>返回的字节流</returns>
- private static byte[] GetImageByte(string imagePath)
- {
- Stream files;
- try
- {
- //如果本地含有图片则从本地读取,反之从服务器下载
- var localurl = AppDomain.CurrentDomain.BaseDirectory + imagePath.Substring(imagePath.IndexOf('D'));
- files = new FileStream(localurl, FileMode.Open);
- }
- catch
- {
- files = DownLoadImage(imagePath);
- }
- byte[] imgByte = new byte[files.Length];
- files.Read(imgByte, , imgByte.Length);
- files.Close();
- return imgByte;
- }
- /// <summary>
- /// 将图片下载到流
- /// </summary>
- /// <param name="path">图片路径</param>
- /// <returns></returns>
- public static Stream DownLoadImage(string path)
- {
- WebRequest request = WebRequest.Create(@path);
- WebResponse response = request.GetResponse();
- return response.GetResponseStream();
- }
- public static bool ThumbnailCallback()
- {
- return false;
- }
- /// <summary>
- /// 字节流转换成图片路径
- /// </summary>
- /// <param name="byt">要转换的字节流</param>
- /// <param name="id">用户Id</param>
- /// <param name="catalogPath">存储目录</param>
- /// <returns>转换得到的Image对象</returns>
- public static string GetImageUrl(string id,byte[] byt,string catalogPath)
- {
- string catalog = "DownLoads/" + catalogPath;
- var filename = id + ".jpg";
- var path = string.Format("{0}/{1}", catalog, filename);
- var existpath = AppDomain.CurrentDomain.BaseDirectory + @path;
- if (File.Exists(@existpath))
- {
- return BaseHelper.GetValue("Server") + path;
- }
- else
- {
- MemoryStream ms = new MemoryStream(byt);
- Image img = Image.FromStream(ms);
- string root = AppDomain.CurrentDomain.BaseDirectory + catalog;
- if (!Directory.Exists(@root))
- {
- Directory.CreateDirectory(@root);
- }
- img.Save(AppDomain.CurrentDomain.BaseDirectory + @path);
- return BaseHelper.GetValue("Server") + @path;
- }
- }
- /// <summary>
- /// 获取缩略图路径
- /// </summary>
- /// <param name="id"></param>
- /// <param name="url"></param>
- /// <param name="catalogPath"></param>
- /// <param name="size"></param>
- /// <returns></returns>
- public static string GetThumbnailUrl(string id, string url, string catalogPath,int size)
- {
- string catalog = "DownLoads/" + catalogPath;
- var filename = id + ".jpg";
- var path = string.Format("{0}/{1}", catalog, filename);
- var existpath = AppDomain.CurrentDomain.BaseDirectory + path;
- if (File.Exists(@existpath))
- {
- return BaseHelper.GetValue("Server") + @path;
- }
- else
- {
- FileStream ms = new FileStream(@url, FileMode.Open);
- Image img = Image.FromStream(ms);
- //压缩图片大小
- var myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
- Image myThumbnail = img.GetThumbnailImage(size, size, myCallback, IntPtr.Zero);
- string root = AppDomain.CurrentDomain.BaseDirectory + catalog;
- if (!Directory.Exists(@root))
- {
- Directory.CreateDirectory(@root);
- }
- myThumbnail.Save(AppDomain.CurrentDomain.BaseDirectory + @path);
- return BaseHelper.GetValue("Server") + path;
- }
- }
- /// <summary>
- /// 判断用户图片是否已缓存
- /// </summary>
- /// <param name="filename"></param>
- /// <returns></returns>
- public static string IsExist(string filename)
- {
- var filepath = @"DownLoads/Temp/" + filename + ".jpg";
- var path = AppDomain.CurrentDomain.BaseDirectory + @filepath;
- return File.Exists(@path) ? BaseHelper.GetValue("Server") + @filepath : string.Empty;
- }
- /// <summary>
- /// 获取用户的Base64缩略图
- /// </summary>
- /// <param name="stream">图片流</param>
- /// <param name="width">缩略图宽度</param>
- /// <param name="height">缩略图宽度</param>
- /// <param name="isfixWidthHeight">是否固定高宽</param>
- /// <returns></returns>
- public static string GetBase64Image(int width,int height, Stream stream,bool isfixWidthHeight=false)
- {
- try
- {
- Image img = Image.FromStream(stream);
- //var id = BaseHelper.CreateGuid();
- //压缩图片大小
- var myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
- Image myThumbnail;
- if (isfixWidthHeight)
- {
- myThumbnail = img.GetThumbnailImage(width, height, myCallback, IntPtr.Zero);
- }
- else
- {
- int startX = ,startY=;
- var w = img.Width;
- var h = img.Height;
- int getX = w, getY = h;
- float dw =(float) w/width;
- float dh =(float) h/height;
- if (Equals(dw, dh))
- {
- myThumbnail = img.GetThumbnailImage(width, height, myCallback, IntPtr.Zero);
- }
- else
- {
- //按比例截取中间部分
- if (dw > dh)
- {
- getX = Convert.ToInt32(width * dh);
- startX = Convert.ToInt32((w - getX) / );
- }
- else
- {
- getY = Convert.ToInt32(height * dw);
- startY = Convert.ToInt32((h - getX)/);
- }
- Bitmap destBitmap = new Bitmap(getX, getY);//目标图
- Rectangle destRect = new Rectangle(, , getX, getY); //生成图区域
- Rectangle srcRect = new Rectangle(startX, startY, getX, getY);//截取区域
- Graphics g = Graphics.FromImage(destBitmap);
- g.DrawImage(img, destRect, srcRect, GraphicsUnit.Pixel);
- //SaveImage(destBitmap,id + "_Src");
- myThumbnail = destBitmap.GetThumbnailImage(width, height, myCallback, IntPtr.Zero);
- }
- }
- //SaveImage(myThumbnail,id+"_Thu");
- //将压缩图片转为Base64字符串
- return ImageToBase64(myThumbnail);
- }
- catch
- {
- return null;
- }
- }
- /// <summary>
- /// 将图片流转为base64编码
- /// </summary>
- /// <param name="stream"></param>
- /// <returns></returns>
- public static string GetBase64Image(Stream stream)
- {
- Image img = Image.FromStream(stream);
- return ImageToBase64(img);
- }
- /// <summary>
- /// 获取用户的Base64缩略图
- /// </summary>
- /// <param name="byt">图片存储字节</param>
- /// <param name="width">缩略图宽度</param>
- /// <param name="height">缩略图宽度</param>
- /// <returns></returns>
- public static string GetBase64Image(int width, int height, byte[] byt)
- {
- MemoryStream ms = new MemoryStream(byt);
- return GetBase64Image(width,height,ms);
- }
- /// <summary>
- /// 将图片字节转为base64编码
- /// </summary>
- /// <param name="byt"></param>
- /// <returns></returns>
- public static string GetBase64Image(byte[] byt)
- {
- MemoryStream stream = new MemoryStream(byt);
- Image img = Image.FromStream(stream);
- return ImageToBase64(img);
- }
- /// <summary>
- /// 获取用户的Base64缩略图
- /// </summary>
- /// <param name="imagePath">图片存储路径</param>
- /// <param name="width">缩略图宽度</param>
- /// <param name="height">缩略图宽度</param>
- /// <returns></returns>
- public static string GetBase64Image(int width, int height, string imagePath)
- {
- var stream = DownLoadImage(imagePath);
- return GetBase64Image(width, height, stream);
- }
- /// <summary>
- /// 将图片数据转换为Base64字符串
- /// </summary>
- /// <param name="img"></param>
- public static string ImageToBase64(Image img)
- {
- return "data:image/jpg;base64," + Convert.ToBase64String(ImgToByt(img));
- }
- /// <summary>
- /// 将图片流转换为Base64字符串
- /// </summary>
- /// <param name="ms"></param>
- /// <returns></returns>
- private static string StreamToBase64(MemoryStream ms)
- {
- return "data:image/gif;base64," + Convert.ToBase64String(ms.GetBuffer());
- }
- /// <summary>
- /// 将Base64字符串转换为图片
- /// </summary>
- /// <param name="str"></param>
- private static Image Base64ToImage(string str)
- {
- byte[] bytes = Convert.FromBase64String(str);
- return BytToImg(bytes);
- }
- /// <summary>
- /// 导出图片
- /// </summary>
- /// <param name="img">图片</param>
- /// <param name="fileName">文件名</param>
- private static void SaveImage(Image img,string fileName=null)
- {
- string root = AppDomain.CurrentDomain.BaseDirectory + "DownLoads/Thumbnail";
- if (!Directory.Exists(@root))
- {
- Directory.CreateDirectory(@root);
- }
- string path = fileName == null ? @root + "/" + BaseHelper.CreateGuid() + ".jpg" : @root + "/" + fileName + ".jpg";
- img.Save(path);
- }
- /// <summary>
- /// 裁剪图片
- /// </summary>
- /// <param name="stream">图片流</param>
- /// <param name="startX">开始坐标X</param>
- /// <param name="startY">开始坐标Y</param>
- /// <param name="getX">截取横向距离</param>
- /// <param name="getY">截取纵向距离</param>
- /// <returns>图片base64编码</returns>
- public static string CutImage(Stream stream, int startX, int startY, int getX, int getY)
- {
- Image img = Image.FromStream(stream);
- int w = img.Width;
- int h = img.Height;
- if (startX < w && startY < h)
- {
- if (getX + startX > w)
- {
- getX = w - startX;
- }
- if (startY + getY > h)
- {
- getY = h - startY;
- }
- }
- //var id = BaseHelper.CreateGuid();
- Bitmap destBitmap = new Bitmap(getX, getY);//目标图
- Rectangle destRect = new Rectangle(, , getX, getY); //生成图区域
- Rectangle srcRect = new Rectangle(startX, startY, getX, getY);//截取区域
- Graphics g = Graphics.FromImage(destBitmap);
- g.DrawImage(img, destRect, srcRect, GraphicsUnit.Pixel);
- //SaveImage(destBitmap,id + "_Src");
- return ImageToBase64(destBitmap);
- }
- /// <summary>
- /// 生成验证码
- /// <param name="width">验证码宽度</param>
- /// <param name="height">验证码高度</param>
- /// </summary>
- public static void DrawVerifyCode(int width=,int height=)
- {
- MemoryStream ms = new MemoryStream();
- DrawValidationCode validationCode = new DrawValidationCode {FontMinSize = , FontMaxSize = };
- if (width != ) validationCode.Width = width;
- if (height != ) validationCode.Height = height;
- validationCode.CreateImage(ms);
- var id = BaseHelper.CreateGuid(); //生成ID
- var code = validationCode.ValidationCode; //验证码字符串
- var image = StreamToBase64(ms); //验证码图片
- var createTime = DateTime.Now; //生成时间
- //将图片存储到本地
- string root = AppDomain.CurrentDomain.BaseDirectory + "DownLoads/VerifyCode";
- if (!Directory.Exists(@root))
- {
- Directory.CreateDirectory(@root);
- }
- Image img = Image.FromStream(ms);
- img.Save(@root + "/" + id + ".jpg");
- }
- /// <summary>
- /// 根据姓名生成默认缩略图
- /// </summary>
- /// <param name="name">姓名</param>
- /// <param name="width"></param>
- /// <param name="height"></param>
- /// <returns></returns>
- public static string DrawDefaultIcon(string name,int width=,int height=)
- {
- if (!string.IsNullOrEmpty(name))
- {
- var text = name.Substring(, );
- Bitmap bit = new Bitmap(width + , height + );
- Graphics g = Graphics.FromImage(bit);
- g.SmoothingMode = SmoothingMode.HighQuality;
- g.Clear(Color.Transparent);
- Rectangle rectangle = new Rectangle(, , width, height);
- // 如要使边缘平滑,请取消下行的注释
- g.SmoothingMode = SmoothingMode.HighQuality;
- //设置文本背景色
- SolidBrush[] sbrush =
- {
- new SolidBrush(Color.FromArgb(,,)),
- new SolidBrush(Color.FromArgb(,,)),
- new SolidBrush(Color.FromArgb(,,)),
- new SolidBrush(Color.FromArgb(,,)),
- new SolidBrush(Color.FromArgb(,,)),
- new SolidBrush(Color.FromArgb(,,)),
- new SolidBrush(Color.FromArgb(,,)),
- new SolidBrush(Color.FromArgb(,,)),
- new SolidBrush(Color.FromArgb(,,))
- };
- Random r=new Random();
- //Thread.Sleep(10);
- g.FillEllipse(sbrush[r.Next(sbrush.Length)], rectangle);
- Font font = new Font(new FontFamily("微软雅黑"), , FontStyle.Regular);
- g.DrawString(text, font, new SolidBrush(Color.White), new Rectangle(, , width, height), new StringFormat { Alignment = StringAlignment.Center });
- MemoryStream ms = new MemoryStream();
- bit.Save(ms, ImageFormat.Png);
- return "data:image/png;base64," + Convert.ToBase64String(ms.GetBuffer());
- }
- return null;
- }
- }
C#关于图片的相关处理的更多相关文章
- 渐进式jpeg(progressive jpeg)图片及其相关 --图片的两种加载方式
渐进式jpeg(progressive jpeg)图片及其相关 一.基本JPEG(baseline jpeg)和渐进JPEG 网络上那些色色的照片都是.jpg格式的("色色"指 ...
- css图片的相关操作
css图片的相关操作 1.案例源码 <!DOCTYPE html><html lang="en"><head> <meta charset ...
- SAP Leonardo图片处理相关的机器学习服务在SAP智能服务场景中的应用
本文作为Jerry最近正在做的一个项目的工作思路的梳理. 我们假设这样一个服务场景,技师上门维修某设备,发现设备上某零件损坏了,假设这位技师由于种种原因,没能根据自己的经验识别出这个零件的型号.此时技 ...
- Android中图片处理相关问题
在Android的开发中,我们经常回去处理一些图片相关的问题,比如当加载图片到内存中产生的OOM(OutOfMemory)异常.图片加载到内存中占多大内存的问题.jpg png两种常见的图片的原理及区 ...
- ASP.NET、JAVA跨服务器远程上传文件(图片)的相关解决方案整合
一.图片提交例: A端--提交图片 protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string u ...
- nginx图片处理相关
nginx本身有支持图片处理的模块,通过外部插件也可以实现此功能. libgd的安装 前提是要有libgd的库文件, (1)去官网访问主页没问题,下载文件还是FQ下的,为了方便大家提供一个链接:htt ...
- 渐进式jpeg(progressive jpeg)图片及其相关
最近看有些网站上的jpg格式的图片在呈现的时候,有两种方式,一种是自上而下扫描式的,还有一种就是先是全部的模糊图片,然后逐渐清晰(就像GIF格式的交错显示). 一.基本JPEG(baseline jp ...
- HTML - 图片标签相关
<html> <head></head> <body> <!-- src : 图片的路径 (本地资源路径, 网络资源路径) title : 图片的 ...
- 单行中文字和图片的相关height和line-height特性
这几天在做仿京东的产品页,发现在制作过程中的一些问题,需要好好研究下. 需要实现的效果如上图所示: 在写CSS样式的时候,对于我的关于竖线的做法是: 设置高度为14,border样式,但导致了一个问题 ...
随机推荐
- 如何区分MNO和MVNO
MVNO(Mobile Virtaul Network Operator)虚拟网络运营商,没有自己的物理网络,租用MNO(Mobile Network Operator)网络提供的网络服务. 我们知道 ...
- Android访问设置
在需求 AndroidManifest.xml 中增加下面代码: (1)假设应用程序须要訪问网络权限 <uses-permission android:name="android.pe ...
- POJ 1176 Party Lamps (DFS)
对于一束灯光.提供四种改变彩灯状态(ON<=>OFF)的操作:a.改变全部彩灯状态:b.改变奇数彩灯状态.c.改变偶数彩灯状态:d.改变3k+1号彩灯状态(1,4,7,10...). 给定 ...
- 【Android进阶】获取Android软件的版本信息
PackageInfo pinfo = getPackageManager().getPackageInfo("com.andbase", PackageManager.GET_C ...
- Net中的反应式编程
Net中的反应式编程(Reactive Programming) 系列主题:基于消息的软件架构模型演变 一.反应式编程(Reactive Programming) 1.什么是反应式编程:反应式编程 ...
- 马云收购UC你,至于到底是谁宣战
近日,阿里巴巴官方正式宣布,UC优视全资融入阿里巴巴集团,并组建阿里UC移动事业群. 据阿里方面表示,整个交易对UC的估值远超百度对91无线的估值,外界推測估值近50美元.是中国互联网最大一笔交易.业 ...
- super.getClass()与this.getClass()
原文地址:http://leihuang.org/2014/11/14/getClass-method/ 首先看一段代码: import java.util.Date; public class Te ...
- 第十二章——SQLServer统计信息(3)——发现过期统计信息并处理
原文:第十二章--SQLServer统计信息(3)--发现过期统计信息并处理 前言: 统计信息是关于谓词中的数据分布的主要信息源,如果不知道具体的数据分布,优化器不能获得预估的数据集,从而不能统计需要 ...
- CSDN个人空间能再烂吗?
CSDN空间你敢再烂么? 从CSDN博客跳转到CSDN个人空间的入口还算明显,可是想从个人空间跳转到博客,可真是众里寻他千百度.跳转接口怎么寻都寻不到.根本没有这个跳转的入口.唯一的途径仅仅能从写博文 ...
- 我的java学习笔记(一)
第一个java程序,还是熟悉的hello world public class FirstSample { //类 public static void main(String[] args) //方 ...