Asp.Netファイルアップロードクラス(ファイル接尾辞名を取得し、ファイルを保存し、文字透かしを加える)
4723 ワード
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
namespace EC
{
///
///
///
public class UploadObj
{
public UploadObj()
{
//
// TODO:
//
}
///
///
///
public enum FileType
{
jpg,gif,bmp,png
}
#region
///
///
///
///
///
public static string GetFileExtends(string filename)
{
string ext = null;
if (filename.IndexOf('.') > 0)
{
string[] fs = filename.Split('.');
ext = fs[fs.Length - 1];
}
return ext;
}
#endregion
#region
///
///
///
///
///
public static bool CheckFileExtends(string fileExtends)
{
bool status = false;
fileExtends = fileExtends.ToLower();
string[] fe = Enum.GetNames(typeof(FileType));
for (int i = 0; i < fe.Length; i++)
{
if (fe[i].ToLower() == fileExtends)
{
status = true;
break;
}
}
return status;
}
#endregion
#region
///
///
///
/// ,Server.MapPath()
///
///
public static string PhotoSave(string fpath,FileUpload myFileUpload)
{
string s = "";
string fileExtends = "";
string fileName = myFileUpload.FileName;
if (fileName != "")
{
//
fileExtends = EC.UploadObj.GetFileExtends(fileName);
if (!EC.UploadObj.CheckFileExtends(fileExtends))
{
EC.MessageObject.ShowPre(" ");
}
Random rd = new Random();
s = EC.RandomObject.DateRndName(rd) + "." + fileExtends;
string file = fpath + "\\" + s;
try
{
myFileUpload.SaveAs(file);
}
catch (Exception ee)
{
throw new Exception(ee.ToString());
}
}
return s;
}
#endregion
#region
///
///
///
/// ( )
///
public void AddTextToImg(string fileName, string text)
{
if (!File.Exists(fileName))
{
throw new FileNotFoundException(" ");
}
if (text == string.Empty)
{
return;
}
//
System.Drawing.Image image = System.Drawing.Image.FromFile(fileName);
Bitmap bitmap = new Bitmap(image, image.Width, image.Height);
Graphics g = Graphics.FromImage(bitmap);
float fontSize = 12.0f;//
float textWidth = text.Length * fontSize;//
// ,
float rectX = 0;
float rectY = 0;
float rectWidth = text.Length * (fontSize + 8);
float rectHeight = fontSize + 8;
//
RectangleF textArea = new RectangleF(rectX, rectY, rectWidth, rectHeight);
Font font = new Font(" ", fontSize);//
Brush whiteBrush = new SolidBrush(Color.White);// ,
Brush blackBrush = new SolidBrush(Color.Black);// ,
g.FillRectangle(blackBrush, rectX, rectY, rectWidth, rectHeight);
g.DrawString(text, font, whiteBrush, textArea);
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Jpeg);
// , ,
//Response.Clear();
//Response.ContentType = "image/jpeg";
//Response.BinaryWrite(ms.ToArray());
g.Dispose();
bitmap.Dispose();
image.Dispose();
}
#endregion
}
}