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样式,但导致了一个问题 ...
随机推荐
- CareerCup chapter 1 Arrays and Strings
1.Implement an algorithm to determine if a string has all unique characters What if you can not use ...
- Telnet,SSH1,SSH2,Telnet/SSL,Rlogin,Serial,TAPI,RAW
一.Telnet 采用Telnet用来訪问远程计算机的TCP/IP协议以控制你的网络设备,相当于在离开某个建筑时大喊你的username和口令.非常快会有人进行监听, 并且他们会利用你安全意识的缺乏. ...
- UVA 11149 - Power of Matrix(矩阵乘法)
UVA 11149 - Power of Matrix 题目链接 题意:给定一个n*n的矩阵A和k,求∑kiAi 思路:利用倍增去搞.∑kiAi=(1+Ak/2)∑k/2iAi,不断二分就可以 代码: ...
- 在JBuilder8在使用ANT
在JBuilder8中使用ANT 作者:翁驰原 在JBuilder8中.Ap ...
- 编程算法 - 分割数 代码(C)
分割数 代码(C) 本文地址: http://blog.csdn.net/caroline_wendy 题目: 有n个无差别的物品, 将它们划分成不超过m组, 求出划分方法数模M的余数. 比如: n= ...
- WebService 用户名密码验证
原文:WebService 用户名密码验证 在项目开发的过程中,WebService是经常要用的,当调用WebService方法时,需要经过服务的验证才可以调用,一般就是用户名/密码验证,还有一个就是 ...
- UVA 11402 - Ahoy, Pirates!(段树)
UVA 11402 - Ahoy, Pirates! 题目链接 题意:总的来说意思就是给一个01串,然后有3种操作 1.把一个区间变成1 2.把一个区间变成0 3.把一个区间翻转(0变1,1变0) 思 ...
- HDOJ 5188 zhx and contest 贪婪+01背包
zhx and contest Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) ...
- 一个用于每一天JavaScript示例-使用缓存计算(memoization)为了提高应用程序性能
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...
- Cocos2d-x 单点触摸--让我们用手指动起来的精灵
转载请注明出处:http://blog.csdn.net/oyangyufu/article/details/25656673 效果图: CCTouch类装载了触摸点的信息.包含触摸点的横纵坐标值和触 ...