目录
7. JSON操作类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Data;
using System.Data.Common;
namespace Core.Json
{
//JSON转换类
public class ConvertJson
{
#region 私有方法
/// <summary>
/// 过滤特殊字符
/// </summary>
private static string String2Json(String s)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
char c = s.ToCharArray()[i];
switch (c)
{
case '\"':
sb.Append("\\\""); break;
case '\\':
sb.Append("\\\\"); break;
case '/':
sb.Append("\\/"); break;
case '\b':
sb.Append("\\b"); break;
case '\f':
sb.Append("\\f"); break;
case '\n':
sb.Append("\\n"); break;
case '\r':
sb.Append("\\r"); break;
case '\t':
sb.Append("\\t"); break;
default:
sb.Append(c); break;
}
}
return sb.ToString();
}
/// <summary>
/// 格式化字符型、日期型、布尔型
/// </summary>
private static string StringFormat(string str, Type type)
{
if (type == typeof(string))
{
str = String2Json(str);
str = "\"" + str + "\"";
}
else if (type == typeof(DateTime))
{
str = "\"" + str + "\"";
}
else if (type == typeof(bool))
{
str = str.ToLower();
}
else if (type != typeof(string) && string.IsNullOrEmpty(str))
{
str = "\"" + str + "\"";
}
return str;
}
#endregion
#region List转换成Json
/// <summary>
/// List转换成Json
/// </summary>
public static string ListToJson<T>(IList<T> list)
{
object obj = list[0];
return ListToJson<T>(list, obj.GetType().Name);
}
/// <summary>
/// List转换成Json
/// </summary>
public static string ListToJson<T>(IList<T> list, string jsonName)
{
StringBuilder Json = new StringBuilder();
if (string.IsNullOrEmpty(jsonName)) jsonName = list[0].GetType().Name;
Json.Append("{\"" + jsonName + "\":[");
if (list.Count > 0)
{
for (int i = 0; i < list.Count; i++)
{
T obj = Activator.CreateInstance<T>();
PropertyInfo[] pi = obj.GetType().GetProperties();
Json.Append("{");
for (int j = 0; j < pi.Length; j++)
{
Type type = pi[j].GetValue(list[i], null).GetType();
Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
if (j < pi.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < list.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
#endregion
#region 对象转换为Json
/// <summary>
/// 对象转换为Json
/// </summary>
/// <param name="jsonObject">对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(object jsonObject)
{
string jsonString = "{";
PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
for (int i = 0; i < propertyInfo.Length; i++)
{
object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
string value = string.Empty;
if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
{
value = "'" + objectValue.ToString() + "'";
}
else if (objectValue is string)
{
value = "'" + ToJson(objectValue.ToString()) + "'";
}
else if (objectValue is IEnumerable)
{
value = ToJson((IEnumerable)objectValue);
}
else
{
value = ToJson(objectValue.ToString());
}
jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
}
jsonString.Remove(jsonString.Length - 1, jsonString.Length);
return jsonString + "}";
}
#endregion
#region 对象集合转换Json
/// <summary>
/// 对象集合转换Json
/// </summary>
/// <param name="array">集合对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(IEnumerable array)
{
string jsonString = "[";
foreach (object item in array)
{
jsonString += ToJson(item) + ",";
}
jsonString.Remove(jsonString.Length - 1, jsonString.Length);
return jsonString + "]";
}
#endregion
#region 普通集合转换Json
/// <summary>
/// 普通集合转换Json
/// </summary>
/// <param name="array">集合对象</param>
/// <returns>Json字符串</returns>
public static string ToArrayString(IEnumerable array)
{
string jsonString = "[";
foreach (object item in array)
{
jsonString = ToJson(item.ToString()) + ",";
}
jsonString.Remove(jsonString.Length - 1, jsonString.Length);
return jsonString + "]";
}
#endregion
#region DataSet转换为Json
/// <summary>
/// DataSet转换为Json
/// </summary>
/// <param name="dataSet">DataSet对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DataSet dataSet)
{
string jsonString = "{";
foreach (DataTable table in dataSet.Tables)
{
jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
}
jsonString = jsonString.TrimEnd(',');
return jsonString + "}";
}
#endregion
#region Datatable转换为Json
/// <summary>
/// Datatable转换为Json
/// </summary>
/// <param name="table">Datatable对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DataTable dt)
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
DataRowCollection drc = dt.Rows;
for (int i = 0; i < drc.Count; i++)
{
jsonString.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
string strKey = dt.Columns[j].ColumnName;
string strValue = drc[i][j].ToString();
Type type = dt.Columns[j].DataType;
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (j < dt.Columns.Count - 1)
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
return jsonString.ToString();
}
/// <summary>
/// DataTable转换为Json
/// </summary>
public static string ToJson(DataTable dt, string jsonName)
{
StringBuilder Json = new StringBuilder();
if (string.IsNullOrEmpty(jsonName)) jsonName = dt.TableName;
Json.Append("{\"" + jsonName + "\":[");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Json.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
Type type = dt.Rows[i][j].GetType();
Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
if (j < dt.Columns.Count - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < dt.Rows.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
#endregion
#region DataReader转换为Json
/// <summary>
/// DataReader转换为Json
/// </summary>
/// <param name="dataReader">DataReader对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DbDataReader dataReader)
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
while (dataReader.Read())
{
jsonString.Append("{");
for (int i = 0; i < dataReader.FieldCount; i++)
{
Type type = dataReader.GetFieldType(i);
string strKey = dataReader.GetName(i);
string strValue = dataReader[i].ToString();
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (i < dataReader.FieldCount - 1)
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
dataReader.Close();
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
return jsonString.ToString();
}
#endregion
}
}
8.ExcelHelper 类9
-
using System; using System.Collections; using System.IO; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Windows.Forms; using DataGrid = System.Windows.Forms.DataGrid; namespace Core.Office { /// <summary> /// Excel操作辅助类(无需VBA引用) /// </summary> public class ExcelHelper { /// <summary> /// Excel 版本 /// </summary> public enum ExcelType { Excel2003, Excel2007 } /// <summary> /// IMEX 三种模式。 /// IMEX是用来告诉驱动程序使用Excel文件的模式,其值有0、1、2三种,分别代表导出、导入、混合模式。 /// </summary> public enum IMEXType { ExportMode = 0, ImportMode = 1, LinkedMode = 2 } #region 获取Excel连接字符串 /// <summary> /// 返回Excel 连接字符串 [IMEX=1] /// </summary> /// <param name="excelPath">Excel文件 绝对路径</param> /// <param name="header">是否把第一行作为列名</param> /// <param name="eType">Excel 版本 </param> /// <returns></returns> public static string GetExcelConnectstring(string excelPath, bool header, ExcelType eType) { return GetExcelConnectstring(excelPath, header, eType, IMEXType.ImportMode); } /// <summary> /// 返回Excel 连接字符串 /// </summary> /// <param name="excelPath">Excel文件 绝对路径</param> /// <param name="header">是否把第一行作为列名</param> /// <param name="eType">Excel 版本 </param> /// <param name="imex">IMEX模式</param> /// <returns></returns> public static string GetExcelConnectstring(string excelPath, bool header, ExcelType eType, IMEXType imex) { if (!File.Exists(excelPath)) throw new FileNotFoundException("Excel路径不存在!"); string connectstring = string.Empty; string hdr = "NO"; if (header) hdr = "YES"; if (eType == ExcelType.Excel2003) connectstring = "Provider=Microsoft.Jet.OleDb.4.0; data source=" + excelPath + ";Extended Properties='Excel 8.0; HDR=" + hdr + "; IMEX=" + imex.GetHashCode() + "'"; else connectstring = "Provider=Microsoft.ACE.OLEDB.12.0; data source=" + excelPath + ";Extended Properties='Excel 12.0 Xml; HDR=" + hdr + "; IMEX=" + imex.GetHashCode() + "'"; return connectstring; } #endregion #region 获取Excel工作表名 /// <summary> /// 返回Excel工作表名 /// </summary> /// <param name="excelPath">Excel文件 绝对路径</param> /// <param name="eType">Excel 版本 </param> /// <returns></returns> public static List<string> GetExcelTablesName(string excelPath, ExcelType eType) { string connectstring = GetExcelConnectstring(excelPath, true, eType); return GetExcelTablesName(connectstring); } /// <summary> /// 返回Excel工作表名 /// </summary> /// <param name="connectstring">excel连接字符串</param> /// <returns></returns> public static List<string> GetExcelTablesName(string connectstring) { using (OleDbConnection conn = new OleDbConnection(connectstring)) { return GetExcelTablesName(conn); } } /// <summary> /// 返回Excel工作表名 /// </summary> /// <param name="connection">excel连接</param> /// <returns></returns> public static List<string> GetExcelTablesName(OleDbConnection connection) { List<string> list = new List<string>(); if (connection.State == ConnectionState.Closed) connection.Open(); DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); if (dt != null && dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { list.Add(ConvertTo<string>(dt.Rows[i][2])); } } return list; } /// <summary> /// 返回Excel第一个工作表表名 /// </summary> /// <param name="excelPath">Excel文件 绝对路径</param> /// <param name="eType">Excel 版本 </param> /// <returns></returns> public static string GetExcelFirstTableName(string excelPath, ExcelType eType) { string connectstring = GetExcelConnectstring(excelPath, true, eType); return GetExcelFirstTableName(connectstring); } /// <summary> /// 返回Excel第一个工作表表名 /// </summary> /// <param name="connectstring">excel连接字符串</param> /// <returns></returns> public static string GetExcelFirstTableName(string connectstring) { using (OleDbConnection conn = new OleDbConnection(connectstring)) { return GetExcelFirstTableName(conn); } } /// <summary> /// 返回Excel第一个工作表表名 /// </summary> /// <param name="connection">excel连接</param> /// <returns></returns> public static string GetExcelFirstTableName(OleDbConnection connection) { string tableName = string.Empty; if (connection.State == ConnectionState.Closed) connection.Open(); DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); if (dt != null && dt.Rows.Count > 0) { tableName = ConvertTo<string>(dt.Rows[0][2]); } return tableName; } /// <summary> /// 获取Excel文件中指定工作表的列 /// </summary> /// <param name="excelPath">Excel文件 绝对路径</param> /// <param name="table">名称 excel table 例如:Sheet1$</param> /// <returns></returns> public static List<string> GetColumnsList(string excelPath, ExcelType eType, string table) { List<string> list = new List<string>(); DataTable tableColumns = null; string connectstring = GetExcelConnectstring(excelPath, true, eType); using (OleDbConnection conn = new OleDbConnection(connectstring)) { conn.Open(); tableColumns = GetReaderSchema(table, conn); } foreach (DataRow dr in tableColumns.Rows) { string columnName = dr["ColumnName"].ToString(); string datatype = ((OleDbType)dr["ProviderType"]).ToString();//对应数据库类型 string netType = dr["DataType"].ToString();//对应的.NET类型,如System.String list.Add(columnName); } return list; } private static DataTable GetReaderSchema(string tableName, OleDbConnection connection) { DataTable schemaTable = null; IDbCommand cmd = new OleDbCommand(); cmd.CommandText = string.Format("select * from [{0}]", tableName); cmd.Connection = connection; using (IDataReader reader = cmd.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SchemaOnly)) { schemaTable = reader.GetSchemaTable(); } return schemaTable; } #endregion #region EXCEL导入DataSet /// <summary> /// EXCEL导入DataSet /// </summary> /// <param name="excelPath">Excel文件 绝对路径</param> /// <param name="table">名称 excel table 例如:Sheet1$ </param> /// <param name="header">是否把第一行作为列名</param> /// <param name="eType">Excel 版本 </param> /// <returns>返回Excel相应工作表中的数据 DataSet [table不存在时返回空的DataSet]</returns> public static DataSet ExcelToDataSet(string excelPath, string table, bool header, ExcelType eType) { string connectstring = GetExcelConnectstring(excelPath, header, eType); return ExcelToDataSet(connectstring, table); } /// <summary> /// 判断工作表名是否存在 /// </summary> /// <param name="connection">excel连接</param> /// <param name="table">名称 excel table 例如:Sheet1$</param> /// <returns></returns> private static bool isExistExcelTableName(OleDbConnection connection, string table) { List<string> list = GetExcelTablesName(connection); foreach (string tName in list) { if (tName.ToLower() == table.ToLower()) return true; } return false; } /// <summary> /// EXCEL导入DataSet /// </summary> /// <param name="connectstring">excel连接字符串</param> /// <param name="table">名称 excel table 例如:Sheet1$ </param> /// <returns>返回Excel相应工作表中的数据 DataSet [table不存在时返回空的DataSet]</returns> public static DataSet ExcelToDataSet(string connectstring, string table) { using (OleDbConnection conn = new OleDbConnection(connectstring)) { DataSet ds = new DataSet(); //判断该工作表在Excel中是否存在 if (isExistExcelTableName(conn, table)) { OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + table + "]", conn); adapter.Fill(ds, table); } return ds; } } /// <summary> /// EXCEL所有工作表导入DataSet /// </summary> /// <param name="excelPath">Excel文件 绝对路径</param> /// <param name="header">是否把第一行作为列名</param> /// <param name="eType">Excel 版本 </param> /// <returns>返回Excel第一个工作表中的数据 DataSet </returns> public static DataSet ExcelToDataSet(string excelPath, bool header, ExcelType eType) { string connectstring = GetExcelConnectstring(excelPath, header, eType); return ExcelToDataSet(connectstring); } /// <summary> /// EXCEL所有工作表导入DataSet /// </summary> /// <param name="connectstring">excel连接字符串</param> /// <returns>返回Excel第一个工作表中的数据 DataSet </returns> public static DataSet ExcelToDataSet(string connectstring) { using (OleDbConnection conn = new OleDbConnection(connectstring)) { DataSet ds = new DataSet(); List<string> tableNames = GetExcelTablesName(conn); foreach (string tableName in tableNames) { OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + tableName + "]", conn); adapter.Fill(ds, tableName); } return ds; } } #endregion #region 数据导出至Excel文件 #region 把一个数据集中的数据导出到Excel文件中(XML格式操作) /// <summary> /// 把一个数据集中的数据导出到Excel文件中(XML格式操作) /// </summary> /// <param name="source">DataSet数据</param> /// <param name="fileName">保存的Excel文件名</param> public static void DataSetToExcel(DataSet source, string fileName) { #region Excel格式内容 var excelDoc = new StreamWriter(fileName); const string startExcelXML = "<xml version>\r\n<Workbook " + "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" + " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " + "xmlns:x=\"urn:schemas- microsoft-com:office:" + "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" + "office:spreadsheet\">\r\n <Styles>\r\n " + "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " + "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" + "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" + "\r\n <Protection/>\r\n </Style>\r\n " + "<Style ss:ID=\"BoldColumn\">\r\n <Font " + "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " + "<Style ss:ID=\"StringLiteral\">\r\n <NumberFormat" + " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " + "ss:ID=\"Decimal\">\r\n <NumberFormat " + "ss:Format=\"#,##0.###\"/>\r\n </Style>\r\n " + "<Style ss:ID=\"Integer\">\r\n <NumberFormat " + "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " + "ss:ID=\"DateLiteral\">\r\n <NumberFormat " + "ss:Format=\"yyyy-mm-dd;@\"/>\r\n </Style>\r\n " + "</Styles>\r\n "; const string endExcelXML = "</Workbook>"; #endregion int sheetCount = 1; excelDoc.Write(startExcelXML); for (int i = 0; i < source.Tables.Count; i++) { int rowCount = 0; DataTable dt = source.Tables[i]; excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">"); excelDoc.Write("<Table>"); excelDoc.Write("<Row>"); for (int x = 0; x < dt.Columns.Count; x++) { excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">"); excelDoc.Write(source.Tables[0].Columns[x].ColumnName); excelDoc.Write("</Data></Cell>"); } excelDoc.Write("</Row>"); foreach (DataRow x in dt.Rows) { rowCount++; //if the number of rows is > 64000 create a new page to continue output if (rowCount == 64000) { rowCount = 0; sheetCount++; excelDoc.Write("</Table>"); excelDoc.Write(" </Worksheet>"); excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">"); excelDoc.Write("<Table>"); } excelDoc.Write("<Row>"); //ID=" + rowCount + " for (int y = 0; y < source.Tables[0].Columns.Count; y++) { Type rowType = x[y].GetType(); #region 根据不同数据类型生成内容 switch (rowType.ToString()) { case "System.String": string XMLstring = x[y].ToString(); XMLstring = XMLstring.Trim(); XMLstring = XMLstring.Replace("&", "&"); XMLstring = XMLstring.Replace(">", ">"); XMLstring = XMLstring.Replace("<", "<"); excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" + "<Data ss:Type=\"String\">"); excelDoc.Write(XMLstring); excelDoc.Write("</Data></Cell>"); break; case "System.DateTime": //Excel has a specific Date Format of YYYY-MM-DD followed by //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000 //The Following Code puts the date stored in XMLDate //to the format above var XMLDate = (DateTime)x[y]; string XMLDatetoString = XMLDate.Year + "-" + (XMLDate.Month < 10 ? "0" + XMLDate.Month : XMLDate.Month.ToString()) + "-" + (XMLDate.Day < 10 ? "0" + XMLDate.Day : XMLDate.Day.ToString()) + "T" + (XMLDate.Hour < 10 ? "0" + XMLDate.Hour : XMLDate.Hour.ToString()) + ":" + (XMLDate.Minute < 10 ? "0" + XMLDate.Minute : XMLDate.Minute.ToString()) + ":" + (XMLDate.Second < 10 ? "0" + XMLDate.Second : XMLDate.Second.ToString()) + ".000"; excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" + "<Data ss:Type=\"DateTime\">"); excelDoc.Write(XMLDatetoString); excelDoc.Write("</Data></Cell>"); break; case "System.Boolean": excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" + "<Data ss:Type=\"String\">"); excelDoc.Write(x[y].ToString()); excelDoc.Write("</Data></Cell>"); break; case "System.Int16": case "System.Int32": case "System.Int64": case "System.Byte": excelDoc.Write("<Cell ss:StyleID=\"Integer\">" + "<Data ss:Type=\"Number\">"); excelDoc.Write(x[y].ToString()); excelDoc.Write("</Data></Cell>"); break; case "System.Decimal": case "System.Double": excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" + "<Data ss:Type=\"Number\">"); excelDoc.Write(x[y].ToString()); excelDoc.Write("</Data></Cell>"); break; case "System.DBNull": excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" + "<Data ss:Type=\"String\">"); excelDoc.Write(""); excelDoc.Write("</Data></Cell>"); break; default: throw (new Exception(rowType.ToString() + " not handled.")); } #endregion } excelDoc.Write("</Row>"); } excelDoc.Write("</Table>"); excelDoc.Write(" </Worksheet>"); sheetCount++; } excelDoc.Write(endExcelXML); excelDoc.Close(); } #endregion #region 将DataTable导出为Excel(OleDb 方式操作) /// <summary> /// 将DataTable导出为Excel(OleDb 方式操作) /// </summary> /// <param name="dataTable">表</param> /// <param name="fileName">导出默认文件名</param> public static void DataSetToExcel(DataTable dataTable, string fileName) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "xls files (*.xls)|*.xls"; saveFileDialog.FileName = fileName; if (saveFileDialog.ShowDialog() == DialogResult.OK) { fileName = saveFileDialog.FileName; if (File.Exists(fileName)) { try { File.Delete(fileName); } catch { MessageBox.Show("该文件正在使用中,关闭文件或重新命名导出文件再试!"); return; } } OleDbConnection oleDbConn = new OleDbConnection(); OleDbCommand oleDbCmd = new OleDbCommand(); string sSql = ""; try { oleDbConn.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + fileName + @";Extended ProPerties=""Excel 8.0;HDR=Yes;"""; oleDbConn.Open(); oleDbCmd.CommandType = CommandType.Text; oleDbCmd.Connection = oleDbConn; sSql = "CREATE TABLE sheet1 ("; for (int i = 0; i < dataTable.Columns.Count; i++) { // 字段名称出现关键字会导致错误。 if (i < dataTable.Columns.Count - 1) sSql += "[" + dataTable.Columns[i].Caption + "] TEXT(100) ,"; else sSql += "[" + dataTable.Columns[i].Caption + "] TEXT(200) )"; } oleDbCmd.CommandText = sSql; oleDbCmd.ExecuteNonQuery(); for (int j = 0; j < dataTable.Rows.Count; j++) { sSql = "INSERT INTO sheet1 VALUES('"; for (int i = 0; i < dataTable.Columns.Count; i++) { if (i < dataTable.Columns.Count - 1) sSql += dataTable.Rows[j][i].ToString() + " ','"; else sSql += dataTable.Rows[j][i].ToString() + " ')"; } oleDbCmd.CommandText = sSql; oleDbCmd.ExecuteNonQuery(); } MessageBox.Show("导出EXCEL成功"); } catch (Exception ex) { MessageBox.Show("导出EXCEL失败:" + ex.Message); } finally { oleDbCmd.Dispose(); oleDbConn.Close(); oleDbConn.Dispose(); } } } #endregion #region 导出Excel文件,自动返回可下载的文件流 /// <summary> /// 导出Excel文件,自动返回可下载的文件流 /// </summary> public static void DataTable1Excel(DataTable dtData) { GridView gvExport = null; HttpContext curContext = HttpContext.Current; StringWriter strWriter = null; HtmlTextWriter htmlWriter = null; if (dtData != null) { curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); curContext.Response.Charset = "utf-8"; strWriter = new StringWriter(); htmlWriter = new HtmlTextWriter(strWriter); gvExport = new GridView(); gvExport.DataSource = dtData.DefaultView; gvExport.AllowPaging = false; gvExport.DataBind(); gvExport.RenderControl(htmlWriter); curContext.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=gb2312\"/>" + strWriter.ToString()); curContext.Response.End(); } } #endregion #region 导出Excel文件,转换为可读模式 /// <summary> /// 导出Excel文件,转换为可读模式 /// </summary> public static void DataTable2Excel(DataTable dtData) { System.Web.UI.WebControls.DataGrid dgExport = null; HttpContext curContext = HttpContext.Current; StringWriter strWriter = null; HtmlTextWriter htmlWriter = null; if (dtData != null) { curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; curContext.Response.Charset = ""; strWriter = new StringWriter(); htmlWriter = new HtmlTextWriter(strWriter); dgExport = new System.Web.UI.WebControls.DataGrid(); dgExport.DataSource = dtData.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); dgExport.RenderControl(htmlWriter); curContext.Response.Write(strWriter.ToString()); curContext.Response.End(); } } #endregion #region 导出Excel文件,并自定义文件名 /// <summary> /// 导出Excel文件,并自定义文件名 /// </summary> public static void DataTable3Excel(DataTable dtData, String FileName) { GridView dgExport = null; HttpContext curContext = HttpContext.Current; StringWriter strWriter = null; HtmlTextWriter htmlWriter = null; if (dtData != null) { HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8); curContext.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls"); curContext.Response.ContentType = "application nd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; curContext.Response.Charset = "GB2312"; strWriter = new StringWriter(); htmlWriter = new HtmlTextWriter(strWriter); dgExport = new GridView(); dgExport.DataSource = dtData.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); dgExport.RenderControl(htmlWriter); curContext.Response.Write(strWriter.ToString()); curContext.Response.End(); } } #endregion #region 将数据导出至Excel文件 /// <summary> /// 将数据导出至Excel文件 /// </summary> /// <param name="Table">DataTable对象</param> /// <param name="ExcelFilePath">Excel文件路径</param> public static bool OutputToExcel(DataTable Table, string ExcelFilePath) { if (File.Exists(ExcelFilePath)) { throw new Exception("该文件已经存在!"); } if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table")) { Table.TableName = "Sheet1"; } //数据表的列数 int ColCount = Table.Columns.Count; //用于记数,实例化参数时的序号 int i = 0; //创建参数 OleDbParameter[] para = new OleDbParameter[ColCount]; //创建表结构的SQL语句 string TableStructStr = @"Create Table " + Table.TableName + "("; //连接字符串 string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;"; OleDbConnection objConn = new OleDbConnection(connString); //创建表结构 OleDbCommand objCmd = new OleDbCommand(); //数据类型集合 ArrayList DataTypeList = new ArrayList(); DataTypeList.Add("System.Decimal"); DataTypeList.Add("System.Double"); DataTypeList.Add("System.Int16"); DataTypeList.Add("System.Int32"); DataTypeList.Add("System.Int64"); DataTypeList.Add("System.Single"); //遍历数据表的所有列,用于创建表结构 foreach (DataColumn col in Table.Columns) { //如果列属于数字列,则设置该列的数据类型为double if (DataTypeList.IndexOf(col.DataType.ToString()) >= 0) { para[i] = new OleDbParameter("@" + col.ColumnName, OleDbType.Double); objCmd.Parameters.Add(para[i]); //如果是最后一列 if (i + 1 == ColCount) { TableStructStr += col.ColumnName + " double)"; } else { TableStructStr += col.ColumnName + " double,"; } } else { para[i] = new OleDbParameter("@" + col.ColumnName, OleDbType.VarChar); objCmd.Parameters.Add(para[i]); //如果是最后一列 if (i + 1 == ColCount) { TableStructStr += col.ColumnName + " varchar)"; } else { TableStructStr += col.ColumnName + " varchar,"; } } i++; } //创建Excel文件及文件结构 try { objCmd.Connection = objConn; objCmd.CommandText = TableStructStr; if (objConn.State == ConnectionState.Closed) { objConn.Open(); } objCmd.ExecuteNonQuery(); } catch (Exception exp) { throw exp; } //插入记录的SQL语句 string InsertSql_1 = "Insert into " + Table.TableName + " ("; string InsertSql_2 = " Values ("; string InsertSql = ""; //遍历所有列,用于插入记录,在此创建插入记录的SQL语句 for (int colID = 0; colID < ColCount; colID++) { if (colID + 1 == ColCount) //最后一列 { InsertSql_1 += Table.Columns[colID].ColumnName + ")"; InsertSql_2 += "@" + Table.Columns[colID].ColumnName + ")"; } else { InsertSql_1 += Table.Columns[colID].ColumnName + ","; InsertSql_2 += "@" + Table.Columns[colID].ColumnName + ","; } } InsertSql = InsertSql_1 + InsertSql_2; //遍历数据表的所有数据行 for (int rowID = 0; rowID < Table.Rows.Count; rowID++) { for (int colID = 0; colID < ColCount; colID++) { if (para[colID].DbType == DbType.Double && Table.Rows[rowID][colID].ToString().Trim() == "") { para[colID].Value = 0; } else { para[colID].Value = Table.Rows[rowID][colID].ToString().Trim(); } } try { objCmd.CommandText = InsertSql; objCmd.ExecuteNonQuery(); } catch (Exception exp) { string str = exp.Message; } } try { if (objConn.State == ConnectionState.Open) { objConn.Close(); } } catch (Exception exp) { throw exp; } return true; } #endregion #region 将数据导出至Excel文件 /// <summary> /// 将数据导出至Excel文件 /// </summary> /// <param name="Table">DataTable对象</param> /// <param name="Columns">要导出的数据列集合</param> /// <param name="ExcelFilePath">Excel文件路径</param> public static bool OutputToExcel(DataTable Table, ArrayList Columns, string ExcelFilePath) { if (File.Exists(ExcelFilePath)) { throw new Exception("该文件已经存在!"); } //如果数据列数大于表的列数,取数据表的所有列 if (Columns.Count > Table.Columns.Count) { for (int s = Table.Columns.Count + 1; s <= Columns.Count; s++) { Columns.RemoveAt(s); //移除数据表列数后的所有列 } } //遍历所有的数据列,如果有数据列的数据类型不是 DataColumn,则将它移除 DataColumn column = new DataColumn(); for (int j = 0; j < Columns.Count; j++) { try { column = (DataColumn)Columns[j]; } catch (Exception) { Columns.RemoveAt(j); } } if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table")) { Table.TableName = "Sheet1"; } //数据表的列数 int ColCount = Columns.Count; //创建参数 OleDbParameter[] para = new OleDbParameter[ColCount]; //创建表结构的SQL语句 string TableStructStr = @"Create Table " + Table.TableName + "("; //连接字符串 string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;"; OleDbConnection objConn = new OleDbConnection(connString); //创建表结构 OleDbCommand objCmd = new OleDbCommand(); //数据类型集合 ArrayList DataTypeList = new ArrayList(); DataTypeList.Add("System.Decimal"); DataTypeList.Add("System.Double"); DataTypeList.Add("System.Int16"); DataTypeList.Add("System.Int32"); DataTypeList.Add("System.Int64"); DataTypeList.Add("System.Single"); DataColumn col = new DataColumn(); //遍历数据表的所有列,用于创建表结构 for (int k = 0; k < ColCount; k++) { col = (DataColumn)Columns[k]; //列的数据类型是数字型 if (DataTypeList.IndexOf(col.DataType.ToString().Trim()) >= 0) { para[k] = new OleDbParameter("@" + col.Caption.Trim(), OleDbType.Double); objCmd.Parameters.Add(para[k]); //如果是最后一列 if (k + 1 == ColCount) { TableStructStr += col.Caption.Trim() + " Double)"; } else { TableStructStr += col.Caption.Trim() + " Double,"; } } else { para[k] = new OleDbParameter("@" + col.Caption.Trim(), OleDbType.VarChar); objCmd.Parameters.Add(para[k]); //如果是最后一列 if (k + 1 == ColCount) { TableStructStr += col.Caption.Trim() + " VarChar)"; } else { TableStructStr += col.Caption.Trim() + " VarChar,"; } } } //创建Excel文件及文件结构 try { objCmd.Connection = objConn; objCmd.CommandText = TableStructStr; if (objConn.State == ConnectionState.Closed) { objConn.Open(); } objCmd.ExecuteNonQuery(); } catch (Exception exp) { throw exp; } //插入记录的SQL语句 string InsertSql_1 = "Insert into " + Table.TableName + " ("; string InsertSql_2 = " Values ("; string InsertSql = ""; //遍历所有列,用于插入记录,在此创建插入记录的SQL语句 for (int colID = 0; colID < ColCount; colID++) { if (colID + 1 == ColCount) //最后一列 { InsertSql_1 += Columns[colID].ToString().Trim() + ")"; InsertSql_2 += "@" + Columns[colID].ToString().Trim() + ")"; } else { InsertSql_1 += Columns[colID].ToString().Trim() + ","; InsertSql_2 += "@" + Columns[colID].ToString().Trim() + ","; } } InsertSql = InsertSql_1 + InsertSql_2; //遍历数据表的所有数据行 DataColumn DataCol = new DataColumn(); for (int rowID = 0; rowID < Table.Rows.Count; rowID++) { for (int colID = 0; colID < ColCount; colID++) { //因为列不连续,所以在取得单元格时不能用行列编号,列需得用列的名称 DataCol = (DataColumn)Columns[colID]; if (para[colID].DbType == DbType.Double && Table.Rows[rowID][DataCol.Caption].ToString().Trim() == "") { para[colID].Value = 0; } else { para[colID].Value = Table.Rows[rowID][DataCol.Caption].ToString().Trim(); } } try { objCmd.CommandText = InsertSql; objCmd.ExecuteNonQuery(); } catch (Exception exp) { string str = exp.Message; } } try { if (objConn.State == ConnectionState.Open) { objConn.Close(); } } catch (Exception exp) { throw exp; } return true; } #endregion #endregion #region 获取Excel文件数据表列表 /// <summary> /// 获取Excel文件数据表列表 /// </summary> public static ArrayList GetExcelTables(string ExcelFileName) { DataTable dt = new DataTable(); ArrayList TablesList = new ArrayList(); if (File.Exists(ExcelFileName)) { using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + ExcelFileName)) { try { conn.Open(); dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); } catch (Exception exp) { throw exp; } //获取数据表个数 int tablecount = dt.Rows.Count; for (int i = 0; i < tablecount; i++) { string tablename = dt.Rows[i][2].ToString().Trim().TrimEnd('$'); if (TablesList.IndexOf(tablename) < 0) { TablesList.Add(tablename); } } } } return TablesList; } #endregion #region 将Excel文件导出至DataTable(第一行作为表头) /// <summary> /// 将Excel文件导出至DataTable(第一行作为表头) /// </summary> /// <param name="ExcelFilePath">Excel文件路径</param> /// <param name="TableName">数据表名,如果数据表名错误,默认为第一个数据表名</param> public static DataTable InputFromExcel(string ExcelFilePath, string TableName) { if (!File.Exists(ExcelFilePath)) { throw new Exception("Excel文件不存在!"); } //如果数据表名不存在,则数据表名为Excel文件的第一个数据表 ArrayList TableList = new ArrayList(); TableList = GetExcelTables(ExcelFilePath); if (TableName.IndexOf(TableName) < 0) { TableName = TableList[0].ToString().Trim(); } DataTable table = new DataTable(); OleDbConnection dbcon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0"); OleDbCommand cmd = new OleDbCommand("select * from [" + TableName + "$]", dbcon); OleDbDataAdapter adapter = new OleDbDataAdapter(cmd); try { if (dbcon.State == ConnectionState.Closed) { dbcon.Open(); } adapter.Fill(table); } catch (Exception exp) { throw exp; } finally { if (dbcon.State == ConnectionState.Open) { dbcon.Close(); } } return table; } #endregion #region 获取Excel文件指定数据表的数据列表 /// <summary> /// 获取Excel文件指定数据表的数据列表 /// </summary> /// <param name="ExcelFileName">Excel文件名</param> /// <param name="TableName">数据表名</param> public static ArrayList GetExcelTableColumns(string ExcelFileName, string TableName) { DataTable dt = new DataTable(); ArrayList ColsList = new ArrayList(); if (File.Exists(ExcelFileName)) { using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + ExcelFileName)) { conn.Open(); dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, TableName, null }); //获取列个数 int colcount = dt.Rows.Count; for (int i = 0; i < colcount; i++) { string colname = dt.Rows[i]["Column_Name"].ToString().Trim(); ColsList.Add(colname); } } } return ColsList; } #endregion #region 清理过时的Excel文件 private void ClearFile(string FilePath) { String[] Files = System.IO.Directory.GetFiles(FilePath); if (Files.Length > 10) { for (int i = 0; i < 10; i++) { try { System.IO.File.Delete(Files[i]); } catch { } } } } #endregion #region 将数据转换为指定类型 /// <summary> /// 将数据转换为指定类型 /// </summary> /// <param name="data">转换的数据</param> /// <param name="targetType">转换的目标类型</param> public static object ConvertTo(object data, Type targetType) { if (data == null || Convert.IsDBNull(data)) { return null; } Type type2 = data.GetType(); if (targetType == type2) { return data; } if (((targetType == typeof(Guid)) || (targetType == typeof(Guid?))) && (type2 == typeof(string))) { if (string.IsNullOrEmpty(data.ToString())) { return null; } return new Guid(data.ToString()); } if (targetType.IsEnum) { try { return Enum.Parse(targetType, data.ToString(), true); } catch { return Enum.ToObject(targetType, data); } } if (targetType.IsGenericType) { targetType = targetType.GetGenericArguments()[0]; } return Convert.ChangeType(data, targetType); } /// <summary> /// 将数据转换为指定类型 /// </summary> /// <typeparam name="T">转换的目标类型</typeparam> /// <param name="data">转换的数据</param> public static T ConvertTo<T>(object data) { if (data == null || Convert.IsDBNull(data)) return default(T); object obj = ConvertTo(data, typeof(T)); if (obj == null) { return default(T); } return (T)obj; } #endregion } }
9.ImageHelper
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace Core.Drawing
{
class ImageHelper
{
/// <summary>
/// 改变原图片的格式,使其成为后缀名为strFormat的图片
/// path是图片的地址
/// </summary>
/// <param name="path">原图片的地址</param>
/// <param name="strFormat">修改后图片的格式</param>
/// <param name="isDelSourcefile">是否删除源文件</param>
public static void ChangeFormat(string path, string strFormat, bool isDelSourcefile)
{
if (isAPicFile(path) == false)
{
MessageBox.Show("非图片文件,请确定路径");
return;
}
Image img = null;
bool canGoOn = true;
try
{
img = Image.FromFile(path);
}
catch (Exception)
{
MessageBox.Show("文件" + path + "未找到,请确认路径是否正确");
canGoOn = false;
}
if (canGoOn)////已经打开成功
{
try
{
img.Save(getDirectory(path) + "." + strFormat); //CAN
}
catch (Exception)
{
canGoOn = false;
}
if (canGoOn)//修改格式成功
{
try
{
img.Dispose();
if (isDelSourcefile)
{
File.Delete(path);
}
}
catch (Exception efail)
{
MessageBox.Show("文件" + path + "删除失败,错误原因:" + efail.Message);
}
}
}
}
/// <summary>
/// 改变图片尺寸的函数,原则上不会有变大的可能性,所以我会将其减小
/// 而且会保存图片,并且决定时候删除原文件,否则保存时文件名要改动
/// </summary>
/// <param name="path">文件的路径</param>
/// <param name="width">要修改的宽度</param>
/// <param name="height">要修改的高度</param>
/// <param name="isDelSourceFile">是否删除原文件</param>
public static void ChangeSize(string path, int width, int height, bool isDelSourceFile)
{
if (isAPicFile(path) == false)
{
MessageBox.Show("非图片文件,请确定路径");
return;
}
Image img = null;
bool canGoOn = true;
if (width <= 0 || height <= 0)
{
MessageBox.Show("尺寸错误,请不要使用非正整数尺寸!");
return;
}
try
{
img = Image.FromFile(path);
}
catch (Exception)
{
MessageBox.Show("文件" + path + "未找到,请确认路径是否正确");
canGoOn = false;
}
if (canGoOn)////已经打开成功
{
if (width > img.Width)
{
width = img.Width;
}
if (height > img.Height)
{
height = img.Height;
}
Bitmap bmp = new Bitmap(width, height);////Empty Bitmap
Bitmap pic = (Bitmap)img;
///
/// 缩小图片算法:
/// 1,拿原长度比上要求的长度,得到一个double类型的比值 bi
/// 2,依次将这个比值 bi 加 要求的长度次,每次得到的值取整,则这个整数就是要求的点!
/// 3,将这些点填充到bmp变量里面,再将该变量强制转换成image格式,保存...
///
double biOfWidth = ((double)pic.Width) / width;
double biOfHeight = ((double)pic.Height) / height;
int y = 0, x;
double dy = 0, dx;
for (int i = 0; i < height; i++)
{
dy += biOfHeight;
y = (int)dy;
x = 0;
dx = 0;
for (int j = 0; j < width; j++)
{
dx += biOfWidth;
x = (int)dx;
try
{
bmp.SetPixel(j, i, pic.GetPixel(x - 1, y - 1));
//MessageBox.Show("" + j + " " + i + " " + x + " " + y);
}
catch (Exception) { MessageBox.Show("x=" + pic.Width); }
}
}
// img = (Image)pic;
if (isDelSourceFile == true)
{
img.Dispose();
File.Delete(path);
img = (Image)bmp;
img.Save(path);
MessageBox.Show("saved");
}
else
{
img = (Image)bmp;
img.Save(getDirectory(path) + "_." + getLast(path));
}
pic.Dispose();
bmp.Dispose();
img.Dispose();
}
}
/// <summary>
/// 得到路径包含文件名但不包含后缀名的部分
/// </summary>
/// <param name="path">图片文件路径</param>
/// <returns></returns>
public static string getDirectory(string path)
{
for (int i = path.Length - 1; i >= 0; i--)
{
if (path[i] == '.')
{
return path.Substring(0, i);
}
}
return null;
}
/// <summary>
/// 得到文件路径的后缀名
/// </summary>
/// <param name="path">图片文件的路径</param>
/// <returns></returns>
public static string getLast(string path)
{
for (int i = path.Length - 1; i >= 0; i--)
{
if (path[i] == '.')
{
return path.Substring(i + 1, path.Length - i - 1);
}
}
return null;
}
/// <summary>
/// 判断是否是否是一个图片文件
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool isAPicFile(string path)
{
string last = getLast(path);
last = last.Trim();
if (last.Equals("jpg") || last.Equals("jpeg") || last.Equals("png") || last.Equals("bmp"))
{
return true;
}
return false;
}
}
}
10.Color Helper类
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace Core.Drawing
{
#region Public Structs
public struct MyColor
{
public RGB RGB;
public HSB HSB;
public CMYK CMYK;
public MyColor(Color color)
{
this.RGB = color;
this.HSB = color;
this.CMYK = color;
}
public static implicit operator MyColor(Color color)
{
return new MyColor(color);
}
public static implicit operator Color(MyColor color)
{
return color.RGB;
}
public static bool operator ==(MyColor left, MyColor right)
{
return (left.RGB == right.RGB) && (left.HSB == right.HSB) && (left.CMYK == right.CMYK);
}
public static bool operator !=(MyColor left, MyColor right)
{
return !(left == right);
}
public void RGBUpdate()
{
this.HSB = this.RGB;
this.CMYK = this.RGB;
}
public void HSBUpdate()
{
this.RGB = this.HSB;
this.CMYK = this.HSB;
}
public void CMYKUpdate()
{
this.RGB = this.CMYK;
this.HSB = this.CMYK;
}
public override string ToString()
{
return String.Format("{0}\r\n{1}\r\n{2}", RGB, HSB, CMYK);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
}
public struct RGB
{
private int red;
private int green;
private int blue;
public int Red
{
get { return red; }
set { red = ColorHelper.CheckColor(value); }
}
public int Green
{
get { return green; }
set { green = ColorHelper.CheckColor(value); }
}
public int Blue
{
get { return blue; }
set { blue = ColorHelper.CheckColor(value); }
}
public RGB(int red, int green, int blue)
: this()
{
this.Red = red;
this.Green = green;
this.Blue = blue;
}
public RGB(Color color)
{
this = new RGB(color.R, color.G, color.B);
}
public static implicit operator RGB(Color color)
{
return new RGB(color.R, color.G, color.B);
}
public static implicit operator Color(RGB color)
{
return color.ToColor();
}
public static implicit operator HSB(RGB color)
{
return color.ToHSB();
}
public static implicit operator CMYK(RGB color)
{
return color.ToCMYK();
}
public static bool operator ==(RGB left, RGB right)
{
return (left.Red == right.Red) && (left.Green == right.Green) && (left.Blue == right.Blue);
}
public static bool operator !=(RGB left, RGB right)
{
return !(left == right);
}
public override string ToString()
{
return String.Format("Red: {0}, Green: {1}, Blue: {2}", Red, Green, Blue);
}
public static Color ToColor(int red, int green, int blue)
{
return Color.FromArgb(red, green, blue);
}
public Color ToColor()
{
return ToColor(Red, Green, Blue);
}
public static HSB ToHSB(Color color)
{
HSB hsb = new HSB();
int Max, Min;
if (color.R > color.G) { Max = color.R; Min = color.G; }
else { Max = color.G; Min = color.R; }
if (color.B > Max) Max = color.B;
else if (color.B < Min) Min = color.B;
int Diff = Max - Min;
hsb.Brightness = (double)Max / 255;
if (Max == 0) hsb.Saturation = 0;
else hsb.Saturation = (double)Diff / Max;
double q;
if (Diff == 0) q = 0;
else q = (double)60 / Diff;
if (Max == color.R)
{
if (color.G < color.B) hsb.Hue = (360 + q * (color.G - color.B)) / 360;
else hsb.Hue = q * (color.G - color.B) / 360;
}
else if (Max == color.G) hsb.Hue = (120 + q * (color.B - color.R)) / 360;
else if (Max == color.B) hsb.Hue = (240 + q * (color.R - color.G)) / 360;
else hsb.Hue = 0.0;
return hsb;
}
public HSB ToHSB()
{
return ToHSB(this);
}
public static CMYK ToCMYK(Color color)
{
CMYK cmyk = new CMYK();
double low = 1.0;
cmyk.Cyan = (double)(255 - color.R) / 255;
if (low > cmyk.Cyan)
low = cmyk.Cyan;
cmyk.Magenta = (double)(255 - color.G) / 255;
if (low > cmyk.Magenta)
low = cmyk.Magenta;
cmyk.Yellow = (double)(255 - color.B) / 255;
if (low > cmyk.Yellow)
low = cmyk.Yellow;
if (low > 0.0)
{
cmyk.Key = low;
}
return cmyk;
}
public CMYK ToCMYK()
{
return ToCMYK(this);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
}
public struct HSB
{
private double hue;
private double saturation;
private double brightness;
public double Hue
{
get { return hue; }
set { hue = ColorHelper.CheckColor(value); }
}
public double Hue360
{
get { return hue * 360; }
set { hue = ColorHelper.CheckColor(value / 360); }
}
public double Saturation
{
get { return saturation; }
set { saturation = ColorHelper.CheckColor(value); }
}
public double Saturation100
{
get { return saturation * 100; }
set { saturation = ColorHelper.CheckColor(value / 100); }
}
public double Brightness
{
get { return brightness; }
set { brightness = ColorHelper.CheckColor(value); }
}
public double Brightness100
{
get { return brightness * 100; }
set { brightness = ColorHelper.CheckColor(value / 100); }
}
public HSB(double hue, double saturation, double brightness)
: this()
{
this.Hue = hue;
this.Saturation = saturation;
this.Brightness = brightness;
}
public HSB(int hue, int saturation, int brightness)
: this()
{
this.Hue360 = hue;
this.Saturation100 = saturation;
this.Brightness100 = brightness;
}
public HSB(Color color)
{
this = RGB.ToHSB(color);
}
public static implicit operator HSB(Color color)
{
return RGB.ToHSB(color);
}
public static implicit operator Color(HSB color)
{
return color.ToColor();
}
public static implicit operator RGB(HSB color)
{
return color.ToColor();
}
public static implicit operator CMYK(HSB color)
{
return color.ToColor();
}
public static bool operator ==(HSB left, HSB right)
{
return (left.Hue == right.Hue) && (left.Saturation == right.Saturation) && (left.Brightness == right.Brightness);
}
public static bool operator !=(HSB left, HSB right)
{
return !(left == right);
}
public override string ToString()
{
return String.Format("Hue: {0}, Saturation: {1}, Brightness: {2}", ColorHelper.Round(Hue360),
ColorHelper.Round(Saturation100), ColorHelper.Round(Brightness100));
}
public static Color ToColor(HSB hsb)
{
int Mid;
int Max = ColorHelper.Round(hsb.Brightness * 255);
int Min = ColorHelper.Round((1.0 - hsb.Saturation) * (hsb.Brightness / 1.0) * 255);
double q = (double)(Max - Min) / 255;
if (hsb.Hue >= 0 && hsb.Hue <= (double)1 / 6)
{
Mid = ColorHelper.Round(((hsb.Hue - 0) * q) * 1530 + Min);
return Color.FromArgb(Max, Mid, Min);
}
if (hsb.Hue <= (double)1 / 3)
{
Mid = ColorHelper.Round(-((hsb.Hue - (double)1 / 6) * q) * 1530 + Max);
return Color.FromArgb(Mid, Max, Min);
}
if (hsb.Hue <= 0.5)
{
Mid = ColorHelper.Round(((hsb.Hue - (double)1 / 3) * q) * 1530 + Min);
return Color.FromArgb(Min, Max, Mid);
}
if (hsb.Hue <= (double)2 / 3)
{
Mid = ColorHelper.Round(-((hsb.Hue - 0.5) * q) * 1530 + Max);
return Color.FromArgb(Min, Mid, Max);
}
if (hsb.Hue <= (double)5 / 6)
{
Mid = ColorHelper.Round(((hsb.Hue - (double)2 / 3) * q) * 1530 + Min);
return Color.FromArgb(Mid, Min, Max);
}
if (hsb.Hue <= 1.0)
{
Mid = ColorHelper.Round(-((hsb.Hue - (double)5 / 6) * q) * 1530 + Max);
return Color.FromArgb(Max, Min, Mid);
}
return Color.FromArgb(0, 0, 0);
}
public static Color ToColor(double hue, double saturation, double brightness)
{
return ToColor(new HSB(hue, saturation, brightness));
}
public Color ToColor()
{
return ToColor(this);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
}
public struct CMYK
{
private double cyan;
private double magenta;
private double yellow;
private double key;
public double Cyan
{
get { return cyan; }
set { cyan = ColorHelper.CheckColor(value); }
}
public double Cyan100
{
get { return cyan * 100; }
set { cyan = ColorHelper.CheckColor(value / 100); }
}
public double Magenta
{
get { return magenta; }
set { magenta = ColorHelper.CheckColor(value); }
}
public double Magenta100
{
get { return magenta * 100; }
set { magenta = ColorHelper.CheckColor(value / 100); }
}
public double Yellow
{
get { return yellow; }
set { yellow = ColorHelper.CheckColor(value); }
}
public double Yellow100
{
get { return yellow * 100; }
set { yellow = ColorHelper.CheckColor(value / 100); }
}
public double Key
{
get { return key; }
set { key = ColorHelper.CheckColor(value); }
}
public double Key100
{
get { return key * 100; }
set { key = ColorHelper.CheckColor(value / 100); }
}
public CMYK(double cyan, double magenta, double yellow, double key)
: this()
{
this.Cyan = cyan;
this.Magenta = magenta;
this.Yellow = yellow;
this.Key = key;
}
public CMYK(int cyan, int magenta, int yellow, int key)
: this()
{
this.Cyan100 = cyan;
this.Magenta100 = magenta;
this.Yellow100 = yellow;
this.Key100 = key;
}
public CMYK(Color color)
{
this = RGB.ToCMYK(color);
}
public static implicit operator CMYK(Color color)
{
return RGB.ToCMYK(color);
}
public static implicit operator Color(CMYK color)
{
return color.ToColor();
}
public static implicit operator RGB(CMYK color)
{
return color.ToColor();
}
public static implicit operator HSB(CMYK color)
{
return color.ToColor();
}
public static bool operator ==(CMYK left, CMYK right)
{
return (left.Cyan == right.Cyan) && (left.Magenta == right.Magenta) && (left.Yellow == right.Yellow) &&
(left.Key == right.Key);
}
public static bool operator !=(CMYK left, CMYK right)
{
return !(left == right);
}
public override string ToString()
{
return String.Format("Cyan: {0}, Magenta: {1}, Yellow: {2}, Key: {3}", ColorHelper.Round(Cyan100),
ColorHelper.Round(Magenta100), ColorHelper.Round(Yellow100), ColorHelper.Round(Key100));
}
public static Color ToColor(CMYK cmyk)
{
int red = ColorHelper.Round(255 - (255 * cmyk.Cyan));
int green = ColorHelper.Round(255 - (255 * cmyk.Magenta));
int blue = ColorHelper.Round(255 - (255 * cmyk.Yellow));
return Color.FromArgb(red, green, blue);
}
public static Color ToColor(double cyan, double magenta, double yellow, double key)
{
return ToColor(new CMYK(cyan, magenta, yellow, key));
}
public Color ToColor()
{
return ToColor(this);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
}
#endregion
internal class ColorHelper
{
#region CheckColorHelper
public static double CheckColor(double number)
{
return GetBetween(number, 0, 1);
}
public static int CheckColor(int number)
{
return GetBetween(number, 0, 255);
}
public static int GetBetween(int number, int min, int max)
{
return Math.Max(Math.Min(number, max), min);
}
public static double GetBetween(double value, double min, double max)
{
return Math.Max(Math.Min(value, max), min);
}
public static int Round(double val)
{
int ret_val = (int)val;
int temp = (int)(val * 100);
if ((temp % 100) >= 50)
ret_val += 1;
return ret_val;
}
#endregion
}
/// <summary>
/// RGB颜色操作辅助类
/// </summary>
public static class MyColors
{
public static Color ParseColor(string color)
{
if (color.StartsWith("#"))
{
return MyColors.HexToColor(color);
}
else if (color.Contains(","))
{
string[] colorArray = color.Split(',');
List<int> colorList = new List<int>();
foreach (string strColor in colorArray)
{
colorList.Add(Convert.ToInt32(strColor));
}
int[] colors = colorList.ToArray();
if (colors.Length == 3)
{
return Color.FromArgb(colors[0], colors[1], colors[2]);
}
if (colors.Length == 4)
{
return Color.FromArgb(colors[0], colors[1], colors[2], colors[3]);
}
}
return Color.FromName(color);
}
public static string ColorToHex(Color color)
{
return string.Format("{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
}
public static int ColorToDecimal(Color color)
{
return HexToDecimal(ColorToHex(color));
}
public static Color HexToColor(string hex)
{
if (hex.StartsWith("#"))
{
hex = hex.Substring(1);
}
string a = string.Empty;
if (hex.Length == 8)
{
a = hex.Substring(0, 2);
hex = hex.Substring(2);
}
string r = hex.Substring(0, 2);
string g = hex.Substring(2, 2);
string b = hex.Substring(4, 2);
if (string.IsNullOrEmpty(a))
{
return Color.FromArgb(HexToDecimal(r), HexToDecimal(g), HexToDecimal(b));
}
else
{
return Color.FromArgb(HexToDecimal(a), HexToDecimal(r), HexToDecimal(g), HexToDecimal(b));
}
}
public static int HexToDecimal(string hex)
{
//return int.Parse(hex, System.Globalization.NumberStyles.HexNumber);
return Convert.ToInt32(hex, 16);
}
public static string DecimalToHex(int dec)
{
return dec.ToString("X6");
}
public static Color DecimalToColor(int dec)
{
return Color.FromArgb(dec & 0xFF, (dec & 0xff00) / 256, dec / 65536);
}
public static Color GetPixelColor(Point point)
{
Bitmap bmp = new Bitmap(1, 1);
Graphics.FromImage(bmp).CopyFromScreen(point, new Point(0, 0), new Size(1, 1));
return bmp.GetPixel(0, 0);
}
public static Color SetHue(Color c, double Hue)
{
HSB hsb = RGB.ToHSB(c);
hsb.Hue = Hue;
return hsb.ToColor();
}
public static Color ModifyHue(Color c, double Hue)
{
HSB hsb = RGB.ToHSB(c);
hsb.Hue *= Hue;
return hsb.ToColor();
}
public static Color SetSaturation(Color c, double Saturation)
{
HSB hsb = RGB.ToHSB(c);
hsb.Saturation = Saturation;
return hsb.ToColor();
}
public static Color ModifySaturation(Color c, double Saturation)
{
HSB hsb = RGB.ToHSB(c);
hsb.Saturation *= Saturation;
return hsb.ToColor();
}
public static Color SetBrightness(Color c, double brightness)
{
HSB hsb = RGB.ToHSB(c);
hsb.Brightness = brightness;
return hsb.ToColor();
}
public static Color ModifyBrightness(Color c, double brightness)
{
HSB hsb = RGB.ToHSB(c);
hsb.Brightness *= brightness;
return hsb.ToColor();
}
public static Color RandomColor()
{
Random rand = new Random();
return Color.FromArgb(rand.Next(256), rand.Next(256), rand.Next(256));
}
}
}
11.ImageClass 类
using System;
using System.Collections;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
namespace Core.Drawing
{
public class ImageClass
{
public ImageClass()
{ }
public static string[] postion = new string[] { "WM_TOP_LEFT", "WM_TOP_RIGHT", "WM_TOP_MIDDLE", "WM_BOTTOM_RIGHT", "WM_BOTTOM_LEFT", "WM_BOTTOM_MIDDLE" };
#region 缩略图
/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="originalImagePath">源图路径(物理路径)</param>
/// <param name="thumbnailPath">缩略图路径(物理路径)</param>
/// <param name="width">缩略图宽度</param>
/// <param name="height">缩略图高度</param>
/// <param name="mode">生成缩略图的方式</param>
public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
{
System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
int towidth = width;
int toheight = height;
int x = 0;
int y = 0;
int ow = originalImage.Width;
int oh = originalImage.Height;
switch (mode)
{
case "HW": //指定高宽缩放(可能变形)
break;
case "W": //指定宽,高按比例
toheight = originalImage.Height * width / originalImage.Width;
break;
case "H": //指定高,宽按比例
towidth = originalImage.Width * height / originalImage.Height;
break;
case "Cut": //指定高宽裁减(不变形)
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh = originalImage.Height;
ow = originalImage.Height * towidth / toheight;
y = 0;
x = (originalImage.Width - ow) / 2;
}
else
{
ow = originalImage.Width;
oh = originalImage.Width * height / towidth;
x = 0;
y = (originalImage.Height - oh) / 2;
}
break;
default:
break;
}
//新建一个bmp图片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
//新建一个画板
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
new System.Drawing.Rectangle(x, y, ow, oh),
System.Drawing.GraphicsUnit.Pixel);
try
{
//以jpg格式保存缩略图
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
}
#endregion
#region 图片水印
/// <summary>
/// 图片水印处理方法
/// </summary>
/// <param name="path">需要加载水印的图片路径(绝对路径)</param>
/// <param name="waterpath">水印图片(绝对路径)</param>
/// <param name="location">水印位置(传送正确的代码)</param>
public static string ImageWatermark(string path, string waterpath, string location)
{
string kz_name = Path.GetExtension(path);
if (kz_name == ".jpg" || kz_name == ".bmp" || kz_name == ".jpeg")
{
DateTime time = DateTime.Now;
string filename = "" + time.Year.ToString() + time.Month.ToString() + time.Day.ToString() + time.Hour.ToString() + time.Minute.ToString() + time.Second.ToString() + time.Millisecond.ToString();
Image img = Bitmap.FromFile(path);
Image waterimg = Image.FromFile(waterpath);
Graphics g = Graphics.FromImage(img);
ArrayList loca = GetLocation(location, img, waterimg);
g.DrawImage(waterimg, new Rectangle(int.Parse(loca[0].ToString()), int.Parse(loca[1].ToString()), waterimg.Width, waterimg.Height));
waterimg.Dispose();
g.Dispose();
string newpath = Path.GetDirectoryName(path) + filename + kz_name;
img.Save(newpath);
img.Dispose();
File.Copy(newpath, path, true);
if (File.Exists(newpath))
{
File.Delete(newpath);
}
}
return path;
}
/// <summary>
/// 图片水印位置处理方法
/// </summary>
/// <param name="location">水印位置</param>
/// <param name="img">需要添加水印的图片</param>
/// <param name="waterimg">水印图片</param>
private static ArrayList GetLocation(string location, Image img, Image waterimg)
{
ArrayList loca = new ArrayList();
int x = 0;
int y = 0;
if (location == "LT")
{
x = 10;
y = 10;
}
else if (location == "T")
{
x = img.Width / 2 - waterimg.Width / 2;
y = img.Height - waterimg.Height;
}
else if (location == "RT")
{
x = img.Width - waterimg.Width;
y = 10;
}
else if (location == "LC")
{
x = 10;
y = img.Height / 2 - waterimg.Height / 2;
}
else if (location == "C")
{
x = img.Width / 2 - waterimg.Width / 2;
y = img.Height / 2 - waterimg.Height / 2;
}
else if (location == "RC")
{
x = img.Width - waterimg.Width;
y = img.Height / 2 - waterimg.Height / 2;
}
else if (location == "LB")
{
x = 10;
y = img.Height - waterimg.Height;
}
else if (location == "B")
{
x = img.Width / 2 - waterimg.Width / 2;
y = img.Height - waterimg.Height;
}
else
{
x = img.Width - waterimg.Width;
y = img.Height - waterimg.Height;
}
loca.Add(x);
loca.Add(y);
return loca;
}
/// <summary>
/// 加水印图片
/// </summary>
/// <param name="picture">imge 对象</param>
/// <param name="WaterMarkPicPath">水印图片的地址</param>
/// <param name="_watermarkPosition">水印位置</param>
/// <param name="_width">被加水印图片的宽</param>
/// <param name="_height">被加水印图片的高</param>
public static void addWatermarkImage(Graphics picture, string WaterMarkPicPath, string _watermarkPosition, int _width, int _height)
{
Image watermark = new Bitmap(WaterMarkPicPath);
int xpos = 0;
int ypos = 0;
int w = watermark.Width;
int h = watermark.Height;
switch (_watermarkPosition)
{
case "WM_TOP_LEFT":
xpos = 0 + 10;
ypos = 0 + 10;
break;
case "WM_TOP_RIGHT":
xpos = _width - w - 10;
ypos = 0 + 10;
break;
case "WM_BOTTOM_RIGHT":
xpos = _width - w - 10;
ypos = _height - h - 10;
break;
case "WM_BOTTOM_LEFT":
xpos = 0 + 10;
ypos = _height - h - 10;
break;
case "WM_BOTTOM_MIDDLE":
xpos = _width / 2 - w / 2;
ypos = _height - h - 10;
break;
case "WM_TOP_MIDDLE":
xpos = _width / 2 - w / 2;
ypos = 0 + 10;
break;
}
picture.DrawImage(watermark, xpos, ypos, w, h);
watermark.Dispose();
}
/// <summary>
/// 打水印
/// </summary>
/// <param name="img"></param>
/// <param name="saveFile">保存文件路径</param>
/// <param name="logoFile">LOGO文件地址</param>
public static void MakeLogo(Image img, string saveFile, string logoFile)
{
using (System.Drawing.Image logo = System.Drawing.Image.FromFile(logoFile))
{
if (img.Width < logo.Width || img.Height < logo.Height)
img.Save(saveFile);
else
{
Graphics g = System.Drawing.Graphics.FromImage(img);
Random r = new Random();
g.DrawImage(logo, img.Width - logo.Width - r.Next(img.Width - logo.Width), img.Height - logo.Height - r.Next(img.Height - logo.Height), logo.Width, logo.Height);
g.Save();
img.Save(saveFile);
g.Dispose();
}
logo.Dispose();
}
}
#endregion
#region 文字水印
/// <summary>
/// 文字水印处理方法
/// </summary>
/// <param name="path">图片路径(绝对路径)</param>
/// <param name="size">字体大小</param>
/// <param name="letter">水印文字</param>
/// <param name="color">颜色</param>
/// <param name="location">水印位置</param>
public static string LetterWatermark(string path, int size, string letter, Color color, string location)
{
#region
string kz_name = Path.GetExtension(path);
if (kz_name == ".jpg" || kz_name == ".bmp" || kz_name == ".jpeg")
{
DateTime time = DateTime.Now;
string filename = "" + time.Year.ToString() + time.Month.ToString() + time.Day.ToString() + time.Hour.ToString() + time.Minute.ToString() + time.Second.ToString() + time.Millisecond.ToString();
Image img = Bitmap.FromFile(path);
Graphics gs = Graphics.FromImage(img);
ArrayList loca = GetLocation(location, img, size, letter.Length);
Font font = new Font("宋体", size);
Brush br = new SolidBrush(color);
gs.DrawString(letter, font, br, float.Parse(loca[0].ToString()), float.Parse(loca[1].ToString()));
gs.Dispose();
string newpath = Path.GetDirectoryName(path) + filename + kz_name;
img.Save(newpath);
img.Dispose();
File.Copy(newpath, path, true);
if (File.Exists(newpath))
{
File.Delete(newpath);
}
}
return path;
#endregion
}
/// <summary>
/// 文字水印位置的方法
/// </summary>
/// <param name="location">位置代码</param>
/// <param name="img">图片对象</param>
/// <param name="width">宽(当水印类型为文字时,传过来的就是字体的大小)</param>
/// <param name="height">高(当水印类型为文字时,传过来的就是字符的长度)</param>
private static ArrayList GetLocation(string location, Image img, int width, int height)
{
#region
ArrayList loca = new ArrayList(); //定义数组存储位置
float x = 10;
float y = 10;
if (location == "LT")
{
loca.Add(x);
loca.Add(y);
}
else if (location == "T")
{
x = img.Width / 2 - (width * height) / 2;
loca.Add(x);
loca.Add(y);
}
else if (location == "RT")
{
x = img.Width - width * height;
}
else if (location == "LC")
{
y = img.Height / 2;
}
else if (location == "C")
{
x = img.Width / 2 - (width * height) / 2;
y = img.Height / 2;
}
else if (location == "RC")
{
x = img.Width - height;
y = img.Height / 2;
}
else if (location == "LB")
{
y = img.Height - width - 5;
}
else if (location == "B")
{
x = img.Width / 2 - (width * height) / 2;
y = img.Height - width - 5;
}
else
{
x = img.Width - width * height;
y = img.Height - width - 5;
}
loca.Add(x);
loca.Add(y);
return loca;
#endregion
}
#endregion
#region 调整光暗
/// <summary>
/// 调整光暗
/// </summary>
/// <param name="mybm">原始图片</param>
/// <param name="width">原始图片的长度</param>
/// <param name="height">原始图片的高度</param>
/// <param name="val">增加或减少的光暗值</param>
public Bitmap LDPic(Bitmap mybm, int width, int height, int val)
{
Bitmap bm = new Bitmap(width, height);//初始化一个记录经过处理后的图片对象
int x, y, resultR, resultG, resultB;//x、y是循环次数,后面三个是记录红绿蓝三个值的
Color pixel;
for (x = 0; x < width; x++)
{
for (y = 0; y < height; y++)
{
pixel = mybm.GetPixel(x, y);//获取当前像素的值
resultR = pixel.R + val;//检查红色值会不会超出[0, 255]
resultG = pixel.G + val;//检查绿色值会不会超出[0, 255]
resultB = pixel.B + val;//检查蓝色值会不会超出[0, 255]
bm.SetPixel(x, y, Color.FromArgb(resultR, resultG, resultB));//绘图
}
}
return bm;
}
#endregion
#region 反色处理
/// <summary>
/// 反色处理
/// </summary>
/// <param name="mybm">原始图片</param>
/// <param name="width">原始图片的长度</param>
/// <param name="height">原始图片的高度</param>
public Bitmap RePic(Bitmap mybm, int width, int height)
{
Bitmap bm = new Bitmap(width, height);//初始化一个记录处理后的图片的对象
int x, y, resultR, resultG, resultB;
Color pixel;
for (x = 0; x < width; x++)
{
for (y = 0; y < height; y++)
{
pixel = mybm.GetPixel(x, y);//获取当前坐标的像素值
resultR = 255 - pixel.R;//反红
resultG = 255 - pixel.G;//反绿
resultB = 255 - pixel.B;//反蓝
bm.SetPixel(x, y, Color.FromArgb(resultR, resultG, resultB));//绘图
}
}
return bm;
}
#endregion
#region 浮雕处理
/// <summary>
/// 浮雕处理
/// </summary>
/// <param name="oldBitmap">原始图片</param>
/// <param name="Width">原始图片的长度</param>
/// <param name="Height">原始图片的高度</param>
public Bitmap FD(Bitmap oldBitmap, int Width, int Height)
{
Bitmap newBitmap = new Bitmap(Width, Height);
Color color1, color2;
for (int x = 0; x < Width - 1; x++)
{
for (int y = 0; y < Height - 1; y++)
{
int r = 0, g = 0, b = 0;
color1 = oldBitmap.GetPixel(x, y);
color2 = oldBitmap.GetPixel(x + 1, y + 1);
r = Math.Abs(color1.R - color2.R + 128);
g = Math.Abs(color1.G - color2.G + 128);
b = Math.Abs(color1.B - color2.B + 128);
if (r > 255) r = 255;
if (r < 0) r = 0;
if (g > 255) g = 255;
if (g < 0) g = 0;
if (b > 255) b = 255;
if (b < 0) b = 0;
newBitmap.SetPixel(x, y, Color.FromArgb(r, g, b));
}
}
return newBitmap;
}
#endregion
#region 拉伸图片
/// <summary>
/// 拉伸图片
/// </summary>
/// <param name="bmp">原始图片</param>
/// <param name="newW">新的宽度</param>
/// <param name="newH">新的高度</param>
public static Bitmap ResizeImage(Bitmap bmp, int newW, int newH)
{
try
{
Bitmap bap = new Bitmap(newW, newH);
Graphics g = Graphics.FromImage(bap);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(bap, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bap.Width, bap.Height), GraphicsUnit.Pixel);
g.Dispose();
return bap;
}
catch
{
return null;
}
}
#endregion
#region 滤色处理
/// <summary>
/// 滤色处理
/// </summary>
/// <param name="mybm">原始图片</param>
/// <param name="width">原始图片的长度</param>
/// <param name="height">原始图片的高度</param>
public Bitmap FilPic(Bitmap mybm, int width, int height)
{
Bitmap bm = new Bitmap(width, height);//初始化一个记录滤色效果的图片对象
int x, y;
Color pixel;
for (x = 0; x < width; x++)
{
for (y = 0; y < height; y++)
{
pixel = mybm.GetPixel(x, y);//获取当前坐标的像素值
bm.SetPixel(x, y, Color.FromArgb(0, pixel.G, pixel.B));//绘图
}
}
return bm;
}
#endregion
#region 左右翻转
/// <summary>
/// 左右翻转
/// </summary>
/// <param name="mybm">原始图片</param>
/// <param name="width">原始图片的长度</param>
/// <param name="height">原始图片的高度</param>
public Bitmap RevPicLR(Bitmap mybm, int width, int height)
{
Bitmap bm = new Bitmap(width, height);
int x, y, z; //x,y是循环次数,z是用来记录像素点的x坐标的变化的
Color pixel;
for (y = height - 1; y >= 0; y--)
{
for (x = width - 1, z = 0; x >= 0; x--)
{
pixel = mybm.GetPixel(x, y);//获取当前像素的值
bm.SetPixel(z++, y, Color.FromArgb(pixel.R, pixel.G, pixel.B));//绘图
}
}
return bm;
}
#endregion
#region 上下翻转
/// <summary>
/// 上下翻转
/// </summary>
/// <param name="mybm">原始图片</param>
/// <param name="width">原始图片的长度</param>
/// <param name="height">原始图片的高度</param>
public Bitmap RevPicUD(Bitmap mybm, int width, int height)
{
Bitmap bm = new Bitmap(width, height);
int x, y, z;
Color pixel;
for (x = 0; x < width; x++)
{
for (y = height - 1, z = 0; y >= 0; y--)
{
pixel = mybm.GetPixel(x, y);//获取当前像素的值
bm.SetPixel(x, z++, Color.FromArgb(pixel.R, pixel.G, pixel.B));//绘图
}
}
return bm;
}
#endregion
#region 压缩图片
/// <summary>
/// 压缩到指定尺寸
/// </summary>
/// <param name="oldfile">原文件</param>
/// <param name="newfile">新文件</param>
public bool Compress(string oldfile, string newfile)
{
try
{
Image img = Image.FromFile(oldfile);
ImageFormat thisFormat = img.RawFormat;
Size newSize = new Size(100, 125);
Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);
Graphics g = Graphics.FromImage(outBmp);
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
g.Dispose();
EncoderParameters encoderParams = new EncoderParameters();
long[] quality = new long[1];
quality[0] = 100;
EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
encoderParams.Param[0] = encoderParam;
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICI = null;
for (int x = 0; x < arrayICI.Length; x++)
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICI = arrayICI[x]; //设置JPEG编码
break;
}
img.Dispose();
if (jpegICI != null) outBmp.Save(newfile, System.Drawing.Imaging.ImageFormat.Jpeg);
outBmp.Dispose();
return true;
}
catch
{
return false;
}
}
#region 图片压缩(降低质量)Compress
private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
/// <summary>
/// 图片压缩(降低质量以减小文件的大小)
/// </summary>
/// <param name="srcBitmap">传入的Bitmap对象</param>
/// <param name="destStream">压缩后的Stream对象</param>
/// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
public static void Compress(Bitmap srcBitmap, Stream destStream, long level)
{
ImageCodecInfo myImageCodecInfo;
Encoder myEncoder;
EncoderParameter myEncoderParameter;
EncoderParameters myEncoderParameters;
myImageCodecInfo = GetEncoderInfo("image/jpeg");
myEncoder = Encoder.Quality;
myEncoderParameters = new EncoderParameters(1);
myEncoderParameter = new EncoderParameter(myEncoder, level);
myEncoderParameters.Param[0] = myEncoderParameter;
srcBitmap.Save(destStream, myImageCodecInfo, myEncoderParameters);
}
/// <summary>
/// 图片压缩(降低质量以减小文件的大小)
/// </summary>
/// <param name="srcBitMap">传入的Bitmap对象</param>
/// <param name="destFile">压缩后的图片保存路径</param>
/// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
public static void Compress(Bitmap srcBitMap, string destFile, long level)
{
Stream s = new FileStream(destFile, FileMode.Create);
Compress(srcBitMap, s, level);
s.Close();
}
/// <summary>
/// 图片压缩(降低质量以减小文件的大小)
/// </summary>
/// <param name="srcFile">传入的Stream对象</param>
/// <param name="destFile">压缩后的图片保存路径</param>
/// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
public static void Compress(Stream srcStream, string destFile, long level)
{
Bitmap bm = new Bitmap(srcStream);
Compress(bm, destFile, level);
bm.Dispose();
}
/// <summary>
/// 图片压缩(降低质量以减小文件的大小)
/// </summary>
/// <param name="srcFile">传入的Image对象</param>
/// <param name="destFile">压缩后的图片保存路径</param>
/// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
public static void Compress(Image srcImg, string destFile, long level)
{
Bitmap bm = new Bitmap(srcImg);
Compress(bm, destFile, level);
bm.Dispose();
}
/// <summary>
/// 图片压缩(降低质量以减小文件的大小)
/// </summary>
/// <param name="srcFile">待压缩的BMP文件名</param>
/// <param name="destFile">压缩后的图片保存路径</param>
/// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
public static void Compress(string srcFile, string destFile, long level)
{
// Create a Bitmap object based on a BMP file.
Bitmap bm = new Bitmap(srcFile);
Compress(bm, destFile, level);
bm.Dispose();
}
#endregion 图片压缩(降低质量)
#endregion
#region 图片灰度化
public Color Gray(Color c)
{
int rgb = Convert.ToInt32((double)(((0.3 * c.R) + (0.59 * c.G)) + (0.11 * c.B)));
return Color.FromArgb(rgb, rgb, rgb);
}
#endregion
#region 转换为黑白图片
/// <summary>
/// 转换为黑白图片
/// </summary>
/// <param name="mybt">要进行处理的图片</param>
/// <param name="width">图片的长度</param>
/// <param name="height">图片的高度</param>
public Bitmap BWPic(Bitmap mybm, int width, int height)
{
Bitmap bm = new Bitmap(width, height);
int x, y, result; //x,y是循环次数,result是记录处理后的像素值
Color pixel;
for (x = 0; x < width; x++)
{
for (y = 0; y < height; y++)
{
pixel = mybm.GetPixel(x, y);//获取当前坐标的像素值
result = (pixel.R + pixel.G + pixel.B) / 3;//取红绿蓝三色的平均值
bm.SetPixel(x, y, Color.FromArgb(result, result, result));
}
}
return bm;
}
#endregion
#region 获取图片中的各帧
/// <summary>
/// 获取图片中的各帧
/// </summary>
/// <param name="pPath">图片路径</param>
/// <param name="pSavePath">保存路径</param>
public void GetFrames(string pPath, string pSavedPath)
{
Image gif = Image.FromFile(pPath);
FrameDimension fd = new FrameDimension(gif.FrameDimensionsList[0]);
int count = gif.GetFrameCount(fd); //获取帧数(gif图片可能包含多帧,其它格式图片一般仅一帧)
for (int i = 0; i < count; i++) //以Jpeg格式保存各帧
{
gif.SelectActiveFrame(fd, i);
gif.Save(pSavedPath + "\\frame_" + i + ".jpg", ImageFormat.Jpeg);
}
}
#endregion
}
}
12.ImageDown 图片下载类
using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
namespace Core.Drawing
{
/// <summary>
/// 图片下载
/// </summary>
public class ImageDown
{
public ImageDown()
{ }
#region 私有方法
/// <summary>
/// 获取图片标志
/// </summary>
private string[] GetImgTag(string htmlStr)
{
Regex regObj = new Regex("<img.+?>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
string[] strAry = new string[regObj.Matches(htmlStr).Count];
int i = 0;
foreach (Match matchItem in regObj.Matches(htmlStr))
{
strAry[i] = GetImgUrl(matchItem.Value);
i++;
}
return strAry;
}
/// <summary>
/// 获取图片URL地址
/// </summary>
private string GetImgUrl(string imgTagStr)
{
string str = "";
Regex regObj = new Regex("http://.+.(?:jpg|gif|bmp|png)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
foreach (Match matchItem in regObj.Matches(imgTagStr))
{
str = matchItem.Value;
}
return str;
}
#endregion
/// <summary>
/// 下载图片到本地
/// </summary>
/// <param name="strHTML">HTML</param>
/// <param name="path">路径</param>
/// <param name="nowyymm">年月</param>
/// <param name="nowdd">日</param>
public string SaveUrlPics(string strHTML, string path)
{
string nowym = DateTime.Now.ToString("yyyy-MM"); //当前年月
string nowdd = DateTime.Now.ToString("dd"); //当天号数
path = path + nowym + "/" + nowdd;
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
string[] imgurlAry = GetImgTag(strHTML);
try
{
for (int i = 0; i < imgurlAry.Length; i++)
{
string preStr = System.DateTime.Now.ToString() + "_";
preStr = preStr.Replace("-", "");
preStr = preStr.Replace(":", "");
preStr = preStr.Replace(" ", "");
WebClient wc = new WebClient();
wc.DownloadFile(imgurlAry[i], path + "/" + preStr + imgurlAry[i].Substring(imgurlAry[i].LastIndexOf("/") + 1));
}
}
catch (Exception ex)
{
return ex.Message;
}
return strHTML;
}
}
}
13. imageUpload 图片上传类
using System;
using System.IO;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Drawing;
namespace Core.Drawing
{
/// <summary>
/// 文件类型
/// </summary>
public enum FileExtension
{
JPG = 255216,
GIF = 7173,
BMP = 6677,
PNG = 13780,
RAR = 8297,
jpg = 255216,
exe = 7790,
xml = 6063,
html = 6033,
aspx = 239187,
cs = 117115,
js = 119105,
txt = 210187,
sql = 255254
}
/// <summary>
/// 图片检测类
/// </summary>
public static class FileValidation
{
#region 上传图片检测类
/// <summary>
/// 是否允许
/// </summary>
public static bool IsAllowedExtension(HttpPostedFile oFile, FileExtension[] fileEx)
{
int fileLen = oFile.ContentLength;
byte[] imgArray = new byte[fileLen];
oFile.InputStream.Read(imgArray, 0, fileLen);
MemoryStream ms = new MemoryStream(imgArray);
System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
string fileclass = "";
byte buffer;
try
{
buffer = br.ReadByte();
fileclass = buffer.ToString();
buffer = br.ReadByte();
fileclass += buffer.ToString();
}
catch { }
br.Close();
ms.Close();
foreach (FileExtension fe in fileEx)
{
if (Int32.Parse(fileclass) == (int)fe) return true;
}
return false;
}
/// <summary>
/// 上传前的图片是否可靠
/// </summary>
public static bool IsSecureUploadPhoto(HttpPostedFile oFile)
{
bool isPhoto = false;
string fileExtension = System.IO.Path.GetExtension(oFile.FileName).ToLower();
string[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg", ".bmp" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
isPhoto = true;
break;
}
}
if (!isPhoto)
{
return true;
}
FileExtension[] fe = { FileExtension.BMP, FileExtension.GIF, FileExtension.JPG, FileExtension.PNG };
if (IsAllowedExtension(oFile, fe))
return true;
else
return false;
}
/// <summary>
/// 上传后的图片是否安全
/// </summary>
/// <param name="photoFile">物理地址</param>
public static bool IsSecureUpfilePhoto(string photoFile)
{
bool isPhoto = false;
string Img = "Yes";
string fileExtension = System.IO.Path.GetExtension(photoFile).ToLower();
string[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg", ".bmp" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
isPhoto = true;
break;
}
}
if (!isPhoto)
{
return true;
}
StreamReader sr = new StreamReader(photoFile, System.Text.Encoding.Default);
string strContent = sr.ReadToEnd();
sr.Close();
string str = "request|<script|.getfolder|.createfolder|.deletefolder|.createdirectory|.deletedirectory|.saveas|wscript.shell|script.encode|server.|.createobject|execute|activexobject|language=";
foreach (string s in str.Split('|'))
{
if (strContent.ToLower().IndexOf(s) != -1)
{
File.Delete(photoFile);
Img = "No";
break;
}
}
return (Img == "Yes");
}
#endregion
}
/// <summary>
/// 图片上传类
/// </summary>
//----------------调用-------------------
//imageUpload iu = new imageUpload();
//iu.AddText = "";
//iu.CopyIamgePath = "";
//iu.DrawString_x = ;
//iu.DrawString_y = ;
//iu.DrawStyle = ;
//iu.Font = "";
//iu.FontSize = ;
//iu.FormFile = File1;
//iu.IsCreateImg =;
//iu.IsDraw = ;
//iu.OutFileName = "";
//iu.OutThumbFileName = "";
//iu.SavePath = @"~/image/";
//iu.SaveType = ;
//iu.sHeight = ;
//iu.sWidth = ;
//iu.Upload();
//--------------------------------------
public class ImageUpload
{
#region 私有成员
private int _Error = 0;//返回上传状态。
private int _MaxSize = 1024 * 1024;//最大单个上传文件 (默认)
private string _FileType = "jpg;gif;bmp;png";//所支持的上传类型用"/"隔开
private string _SavePath = System.Web.HttpContext.Current.Server.MapPath(".") + "\\";//保存文件的实际路径
private int _SaveType = 0;//上传文件的类型,0代表自动生成文件名
private HtmlInputFile _FormFile;//上传控件。
private string _InFileName = "";//非自动生成文件名设置。
private string _OutFileName = "";//输出文件名。
private bool _IsCreateImg = true;//是否生成缩略图。
private bool _Iss = false;//是否有缩略图生成.
private int _Height = 0;//获取上传图片的高度
private int _Width = 0;//获取上传图片的宽度
private int _sHeight = 120;//设置生成缩略图的高度
private int _sWidth = 120;//设置生成缩略图的宽度
private bool _IsDraw = false;//设置是否加水印
private int _DrawStyle = 0;//设置加水印的方式0:文字水印模式,1:图片水印模式,2:不加
private int _DrawString_x = 10;//绘制文本的X坐标(左上角)
private int _DrawString_y = 10;//绘制文本的Y坐标(左上角)
private string _AddText = "GlobalNatureCrafts";//设置水印内容
private string _Font = "宋体";//设置水印字体
private int _FontSize = 12;//设置水印字大小
private int _FileSize = 0;//获取已经上传文件的大小
private string _CopyIamgePath = System.Web.HttpContext.Current.Server.MapPath(".") + "/images/5dm_new.jpg";//图片水印模式下的覆盖图片的实际地址
#endregion
#region 公有属性
/// <summary>
/// Error返回值
/// 1、没有上传的文件
/// 2、类型不允许
/// 3、大小超限
/// 4、未知错误
/// 0、上传成功。
/// </summary>
public int Error
{
get { return _Error; }
}
/// <summary>
/// 最大单个上传文件
/// </summary>
public int MaxSize
{
set { _MaxSize = value; }
}
/// <summary>
/// 所支持的上传类型用";"隔开
/// </summary>
public string FileType
{
set { _FileType = value; }
}
/// <summary>
/// 保存文件的实际路径
/// </summary>
public string SavePath
{
set { _SavePath = System.Web.HttpContext.Current.Server.MapPath(value); }
get { return _SavePath; }
}
/// <summary>
/// 上传文件的类型,0代表自动生成文件名
/// </summary>
public int SaveType
{
set { _SaveType = value; }
}
/// <summary>
/// 上传控件
/// </summary>
public HtmlInputFile FormFile
{
set { _FormFile = value; }
}
/// <summary>
/// 非自动生成文件名设置。
/// </summary>
public string InFileName
{
set { _InFileName = value; }
}
/// <summary>
/// 输出文件名
/// </summary>
public string OutFileName
{
get { return _OutFileName; }
set { _OutFileName = value; }
}
/// <summary>
/// 输出的缩略图文件名
/// </summary>
public string OutThumbFileName
{
get;
set;
}
/// <summary>
/// 是否有缩略图生成.
/// </summary>
public bool Iss
{
get { return _Iss; }
}
/// <summary>
/// 获取上传图片的宽度
/// </summary>
public int Width
{
get { return _Width; }
}
/// <summary>
/// 获取上传图片的高度
/// </summary>
public int Height
{
get { return _Height; }
}
/// <summary>
/// 设置缩略图的宽度
/// </summary>
public int sWidth
{
get { return _sWidth; }
set { _sWidth = value; }
}
/// <summary>
/// 设置缩略图的高度
/// </summary>
public int sHeight
{
get { return _sHeight; }
set { _sHeight = value; }
}
/// <summary>
/// 是否生成缩略图
/// </summary>
public bool IsCreateImg
{
get { return _IsCreateImg; }
set { _IsCreateImg = value; }
}
/// <summary>
/// 是否加水印
/// </summary>
public bool IsDraw
{
get { return _IsDraw; }
set { _IsDraw = value; }
}
/// <summary>
/// 设置加水印的方式
/// 0:文字水印模式
/// 1:图片水印模式
/// 2:不加
/// </summary>
public int DrawStyle
{
get { return _DrawStyle; }
set { _DrawStyle = value; }
}
/// <summary>
/// 绘制文本的X坐标(左上角)
/// </summary>
public int DrawString_x
{
get { return _DrawString_x; }
set { _DrawString_x = value; }
}
/// <summary>
/// 绘制文本的Y坐标(左上角)
/// </summary>
public int DrawString_y
{
get { return _DrawString_y; }
set { _DrawString_y = value; }
}
/// <summary>
/// 设置文字水印内容
/// </summary>
public string AddText
{
get { return _AddText; }
set { _AddText = value; }
}
/// <summary>
/// 设置文字水印字体
/// </summary>
public string Font
{
get { return _Font; }
set { _Font = value; }
}
/// <summary>
/// 设置文字水印字的大小
/// </summary>
public int FontSize
{
get { return _FontSize; }
set { _FontSize = value; }
}
/// <summary>
/// 文件大小
/// </summary>
public int FileSize
{
get { return _FileSize; }
set { _FileSize = value; }
}
/// <summary>
/// 图片水印模式下的覆盖图片的实际地址
/// </summary>
public string CopyIamgePath
{
set { _CopyIamgePath = System.Web.HttpContext.Current.Server.MapPath(value); }
}
#endregion
#region 私有方法
/// <summary>
/// 获取文件的后缀名
/// </summary>
private string GetExt(string path)
{
return Path.GetExtension(path);
}
/// <summary>
/// 获取输出文件的文件名
/// </summary>
private string FileName(string Ext)
{
if (_SaveType == 0 || _InFileName.Trim() == "")
return DateTime.Now.ToString("yyyyMMddHHmmssfff") + Ext;
else
return _InFileName;
}
/// <summary>
/// 检查上传的文件的类型,是否允许上传。
/// </summary>
private bool IsUpload(string Ext)
{
Ext = Ext.Replace(".", "");
bool b = false;
string[] arrFileType = _FileType.Split(';');
foreach (string str in arrFileType)
{
if (str.ToLower() == Ext.ToLower())
{
b = true;
break;
}
}
return b;
}
#endregion
#region 上传图片
public void Upload()
{
HttpPostedFile hpFile = _FormFile.PostedFile;
if (hpFile == null || hpFile.FileName.Trim() == "")
{
_Error = 1;
return;
}
string Ext = GetExt(hpFile.FileName);
if (!IsUpload(Ext))
{
_Error = 2;
return;
}
int iLen = hpFile.ContentLength;
if (iLen > _MaxSize)
{
_Error = 3;
return;
}
try
{
if (!Directory.Exists(_SavePath)) Directory.CreateDirectory(_SavePath);
byte[] bData = new byte[iLen];
hpFile.InputStream.Read(bData, 0, iLen);
string FName;
FName = FileName(Ext);
string TempFile = "";
if (_IsDraw)
{
TempFile = FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString();
}
else
{
TempFile = FName;
}
FileStream newFile = new FileStream(_SavePath + TempFile, FileMode.Create);
newFile.Write(bData, 0, bData.Length);
newFile.Flush();
int _FileSizeTemp = hpFile.ContentLength;
string ImageFilePath = _SavePath + FName;
if (_IsDraw)
{
if (_DrawStyle == 0)
{
System.Drawing.Image Img1 = System.Drawing.Image.FromStream(newFile);
Graphics g = Graphics.FromImage(Img1);
g.DrawImage(Img1, 100, 100, Img1.Width, Img1.Height);
Font f = new Font(_Font, _FontSize);
Brush b = new SolidBrush(Color.Red);
string addtext = _AddText;
g.DrawString(addtext, f, b, _DrawString_x, _DrawString_y);
g.Dispose();
Img1.Save(ImageFilePath);
Img1.Dispose();
}
else
{
System.Drawing.Image image = System.Drawing.Image.FromStream(newFile);
System.Drawing.Image copyImage = System.Drawing.Image.FromFile(_CopyIamgePath);
Graphics g = Graphics.FromImage(image);
g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width - 5, image.Height - copyImage.Height - 5, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
g.Dispose();
image.Save(ImageFilePath);
image.Dispose();
}
}
//获取图片的高度和宽度
System.Drawing.Image Img = System.Drawing.Image.FromStream(newFile);
_Width = Img.Width;
_Height = Img.Height;
//生成缩略图部分
if (_IsCreateImg)
{
#region 缩略图大小只设置了最大范围,并不是实际大小
float realbili = (float)_Width / (float)_Height;
float wishbili = (float)_sWidth / (float)_sHeight;
//实际图比缩略图最大尺寸更宽矮,以宽为准
if (realbili > wishbili)
{
_sHeight = (int)((float)_sWidth / realbili);
}
//实际图比缩略图最大尺寸更高长,以高为准
else
{
_sWidth = (int)((float)_sHeight * realbili);
}
#endregion
this.OutThumbFileName = FName.Split('.').GetValue(0).ToString() + "_s." + FName.Split('.').GetValue(1).ToString();
string ImgFilePath = _SavePath + this.OutThumbFileName;
System.Drawing.Image newImg = Img.GetThumbnailImage(_sWidth, _sHeight, null, System.IntPtr.Zero);
newImg.Save(ImgFilePath);
newImg.Dispose();
_Iss = true;
}
if (_IsDraw)
{
if (File.Exists(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString()))
{
newFile.Dispose();
File.Delete(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString());
}
}
newFile.Close();
newFile.Dispose();
_OutFileName = FName;
_FileSize = _FileSizeTemp;
_Error = 0;
return;
}
catch (Exception ex)
{
_Error = 4;
return;
}
}
#endregion
}
}
14. gif 可变长度压缩算法类
using System.IO;
/// <summary>
/// Gif使用的可变长度的LZW压缩算法解码器
/// </summary>
public class LZWDecoder
{
#region 变量
/// <summary>
/// GIF规定编码最大为12bit,最大值即为4096
/// </summary>
protected static readonly int MaxStackSize = 4096;
protected Stream stream;
#endregion
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
public LZWDecoder(Stream stream)
{
this.stream = stream;
}
#endregion
#region 私有方法
/// <summary>
/// 读取数据段
/// </summary>
byte[] ReadData()
{
int blockSize = Read();
return ReadByte(blockSize);
}
/// <summary>
/// 读取指定长度的字节字节
/// </summary>
byte[] ReadByte(int len)
{
byte[] buffer = new byte[len];
stream.Read(buffer, 0, len);
return buffer;
}
/// <summary>
/// 读取一个字节
/// </summary>
int Read()
{
return stream.ReadByte();
}
#endregion
#region 调用方法
/// <summary>
/// LZW压缩算法解码器
/// </summary>
/// <param name="width">长度</param>
/// <param name="height">高度</param>
/// <param name="stream">包含编码流的数据流</param>
/// <returns>原始数据流</returns>
public byte[] DecodeImageData(int width, int height, Stream stream)
{
int NullCode = -1;
int pixelCount = width * height;//获取原图像的像素数,公式为 像素数 = 图像长度*图像高度
byte[] pixels = new byte[pixelCount];
int dataSize = Read(); //图像编码流的第一个字节(byte)存放的是数据位大小,在gif通常为1,4,8
int codeSize = dataSize + 1; //编码位大小,根据lzw算法的要求,编码位的大小 = 数据位大小+1 ,针对gif,有如下对应关系 1->3 4->5 ->9,而最大的codeSize为12
int clearFlag = 1 << dataSize; //在lzw算法有两个特殊标记,clearFlag为其中的清除标记,此后的编码将重头再来,这样做可以防止编码位无限增大
int endFlag = clearFlag + 1; //lzw算法两个特殊标记之一,endFlag为结束标记,表示一次编码的结束 endFlag=clearFlag+1
int available = endFlag + 1; //初始的可用编码大小,因为0-(clear-1)为元数据,所以均可用,不必研究,此处从能形成压缩的编码开始算起
int code = NullCode; //用于存储当前的编码值
int old_code = NullCode; //用于存储上一次的编码值
int code_mask = (1 << codeSize) - 1;//表示编码的最大值,如果codeSize=5,则code_mask=31
int bits = 0;//在编码流中数据的保存形式为byte,而实际编码过程中是找实际编码位来存储的,比如当codeSize=5的时候,那么实际上5bit的数据就应该可以表示一个编码,这样取出来的1个字节就富余了3个bit,这3个bit用于和第二个字节的后两个bit进行组合,再次形成编码值,如此类推
int[] prefix = new int[MaxStackSize]; //用于保存前缀的集合
int[] suffix = new int[MaxStackSize]; //用于保存后缀
int[] pixelStatck = new int[MaxStackSize + 1]; //用于临时保存数据流
int top = 0;
int count = 0; //在下面的循环中,每次会获取一定量的编码的字节数组,而处理这些数组的时候需要1个个字节来处理,count就是表示还要处理的字节数目
int bi = 0; //count表示还剩多少字节需要处理,而bi则表示本次已经处理的个数
int i = 0; //i代表当前处理得到像素数
int data = 0; //表示当前处理的数据的值
int first = 0; //一个字符串重的第一个字节
int inCode = NullCode; //在lzw中,如果认识了一个编码所代表的数据entry,则将编码作为下一次的prefix,此处inCode代表传递给下一次作为前缀的编码值
//先生成元数据的前缀集合和后缀集合,元数据的前缀均为0,而后缀与元数据相等,同时编码也与元数据相等
for (code = 0; code < clearFlag; code++)
{
//前缀初始为0
prefix[code] = 0;
//后缀=元数据=编码
suffix[code] = (byte)code;
}
byte[] buffer = null;
while (i < pixelCount)
{
//最大像素数已经确定为pixelCount = width * width
if (top == 0)
{
if (bits < codeSize)
{
//如果当前的要处理的bit数小于编码位大小,则需要加载数据
if (count == 0)
{
//如果count为0,表示要从编码流中读一个数据段来进行分析
buffer = ReadData();
count = buffer.Length;
if (count == 0)
{
//再次想读取数据段,却没有读到数据,此时就表明已经处理完了
break;
}
//重新读取一个数据段后,应该将已经处理的个数置0
bi = 0;
}
//获取本次要处理的数据的值
data += buffer[bi] << bits;//此处为何要移位呢,比如第一次处理了1个字节为176,第一次只要处理5bit就够了,剩下3bit留给下个字节进行组合。也就是第二个字节的后两位+第一个字节的前三位组成第二次输出值
bits += 8; //本次又处理了一个字节,所以需要+8
bi++; //将处理下一个字节
count--; //已经处理过的字节数+1
continue;
}
//如果已经有足够的bit数可供处理,下面就是处理过程
code = data & code_mask; //获取data数据的编码位大小bit的数据
data >>= codeSize; //将编码数据截取后,原来的数据就剩下几个bit了,此时将这些bit右移,为下次作准备
bits -= codeSize; //同时需要将当前数据的bit数减去编码位长,因为已经得到了处理。
//下面根据获取的code值来进行处理
if (code > available || code == endFlag)
{
//当编码值大于最大编码值或者为结束标记的时候,停止处理
break;
}
if (code == clearFlag)
{
//如果当前是清除标记,则重新初始化变量,好重新再来
codeSize = dataSize + 1;
//重新初始化最大编码值
code_mask = (1 << codeSize) - 1;
//初始化下一步应该处理得编码值
available = clearFlag + 2;
//将保存到old_code中的值清除,以便重头再来
old_code = NullCode;
continue;
}
//下面是code属于能压缩的编码范围内的的处理过程
if (old_code == NullCode)
{
//如果当前编码值为空,表示是第一次获取编码
pixelStatck[top++] = suffix[code];//获取到1个数据流的数据
//本次编码处理完成,将编码值保存到old_code中
old_code = code;
//第一个字符为当前编码
first = code;
continue;
}
inCode = code;
if (code == available)
{
//如果当前编码和本次应该生成的编码相同
pixelStatck[top++] = (byte)first;//那么下一个数据字节就等于当前处理字符串的第一个字节
code = old_code; //回溯到上一个编码
}
while (code > clearFlag)
{
//如果当前编码大于清除标记,表示编码值是能压缩数据的
pixelStatck[top++] = suffix[code];
code = prefix[code];//回溯到上一个编码
}
first = suffix[code];
if (available > MaxStackSize)
{
//当编码最大值大于gif所允许的编码(4096)最大值的时候停止处理
break;
}
//获取下一个数据
pixelStatck[top++] = suffix[code];
//设置当前应该编码位置的前缀
prefix[available] = old_code;
//设置当前应该编码位置的后缀
suffix[available] = first;
//下次应该得到的编码值
available++;
if (available == code_mask + 1 && available < MaxStackSize)
{
//增加编码位数
codeSize++;
//重设最大编码值
code_mask = (1 << codeSize) - 1;
}
//还原old_code
old_code = inCode;
}
//回溯到上一个处理位置
top--;
//获取元数据
pixels[i++] = (byte)pixelStatck[top];
}
return pixels;
}
#endregion
}
//LZW数据压缩算法的原理分析:http://www.cnblogs.com/jillzhang/archive/2006/11/06/551298.html