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#关于图片的相关处理的更多相关文章

  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. openGL研究钞四 : 关于颜色, 尺寸, 虚线, 多边形逆转, 空洞, 使用位图

    转载请保留源,,,,hushuai1992http://blog.csdn.net/u013642494/article/category/2675731 额. 这个标题我都不知道该怎么起了. 假设没 ...

  2. Java NIO框架Netty课程(一) – Hello Netty

    首先啰嗦2,假如你不知道Netty怎么办怎么办.它可以是一个简单的搜索,找出.我只能说Netty是NIO该框架,它可用于开发分布式Java计划.详细情况可以做,我们可以尝试用你的想象力. 技术,它是服 ...

  3. UI标签库的话题:JEECG智能开发平台 BaseTag(样式表和JS标签的引入)

    UI标签库专题一:JEECG智能开发平台 BaseTag(样式表和JS引入标签) 1.BaseTag(样式表和JS引入标签) 1.1. 演示样例 <t:base type="jquer ...

  4. jQuery 代码的层定位滑动动画效果

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. JavaScript IDE

    哪些JavaScript IDE最好用?   阅读本文之前,分享大家一张图片,看图会发现JavaScript开发需求最高,占比达到42.84%,因此掌握JavaScript语言好工作就不愁啦,工欲善其 ...

  6. POJ 1745 Divisibility (线性dp)

    Divisibility Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 10598   Accepted: 3787 Des ...

  7. 从苹果系统InstallESD.dmg里提取IOS

    右键下载的Mac OS X Mountain Lion镜像:InstallESD.dmg,选择7-zip------打开压缩包 2.双击InstallMacOSX.pkg 3.选中InstallESD ...

  8. sqlserver system object type

    select distinct s.type, s.type_desc from sys.objects as s inner join (select distinct type from sys. ...

  9. 泛泰A860(高通公司8064 cpu 1080p) 拂4.4中国民营recovery TWRP2.7.1.2文本(通过刷第三版)

    专业第三方开发团队 VegaDevTeam  (本team 由 syhost suky zhaochengw(z大) xuefy(大星星) tenfar(R大师) loogeo crazyi(天下无雪 ...

  10. iOS开发无第三方控件的援助达到的效果侧边栏

    最近的研究iOS程序侧边栏.渐渐的发现iOS该方案还开始采取风侧边栏格该,QQ,今日头条,Path(Path运营商最早的侧边栏app该,效果说成是Path效果),所以就研究了下. 然后发现Git Hu ...