- 积分
- 40165
- 好友
- 记录
- 主题
- 帖子
- 听众
- 收听
|
大家先来看看效果吧
主要是两个Form一个是测试窗体,一个是表情面板
源码下载:
QQFaceDemo.rar
(540.47 KB, 下载次数: 1615)
先来看看Form1的代码吧
[code=csharp]/// <summary>
///更新网站 http://www.sufeinet.com/thread-1789-1-1.html
/// </summary>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Framework.UI.WinForm.Controls.RTF;
namespace QQFaceDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public ImagePopup _faceForm = null;
public ImagePopup FaceForm
{
get
{
if (this._faceForm == null)
{
this._faceForm = new ImagePopup
{
ImagePath = "Face\\",
CustomImagePath = "Face\\Custom\\",
CanManage = true,
ShowDemo=true,
};
this._faceForm.Init(24, 24, 8, 8, 12, 8);
this._faceForm.Selected += this._faceForm_AddFace;
}
return this._faceForm;
}
}
string imgName = "";
void _faceForm_AddFace(object sender, SelectFaceArgs e)
{
this.imgName = e.Img.FullName.Replace(Application.StartupPath + "\\", "");
if (e.Img.Image.Width > this.pictureBox1.Width || e.Img.Image.Height > this.pictureBox1.Height)
{
this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
}
else
{
this.pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
}
pictureBox1.Image = e.Img.Image;
}
private void button1_Click(object sender, EventArgs e)
{
Point pt = this.PointToScreen(new Point(((Button)sender).Left, ((Button)sender).Height+5));
this.FaceForm.Show(pt.X, pt.Y, ((Button)sender).Height);
}
}
}
[/code]
下在同是表情面板的代码如下
[code=csharp]/// <summary>
///更新网站 http://www.sufeinet.com/thread-1789-1-1.html
/// </summary>
#region using
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Windows.Forms;
using Framework.Utility;
#endregion
namespace Framework.UI.WinForm.Controls.RTF
{
public class ImagePopup : Form
{
#region Protected Member Variables
protected Bitmap _Bitmap;
protected int _imageWidth;
protected int _imageHeight;
protected int _nBitmapWidth;
protected int _nBitmapHeight;
protected int _nItemWidth;
protected int _nItemHeight;
protected int _nRows;
protected int _nColumns;
protected int _nHSpace;
protected int _nVSpace;
protected int _nCoordX = -1;
protected int _nCoordY = -1;
protected bool _bIsMouseDown;
protected int offset = 5;
private bool IsShowDialog;
private int PageIndex;
private int PageCount;
private int PageImageCount;
private int imageIndex;
#endregion
#region Public Properties
public Color BackgroundColor = Color.FromArgb(255, 255, 255);
public Color BackgroundOverColor = Color.FromArgb(241, 238, 231);
public Color HLinesColor = Color.FromArgb(222, 222, 222);
public Color VLinesColor = Color.FromArgb(165, 182, 222);
public Color BorderColor = Color.FromArgb(0, 16, 123);
private PictureBox Demo;
private IContainer components;
public bool EnableDragDrop;
private List<ImageEntity> _images = new List<ImageEntity>();
public List<ImageEntity> Images
{
get { return this._images; }
set { this._images = value; }
}
private List<ImageEntity> _drawImages = new List<ImageEntity>();
public List<ImageEntity> DrawImages
{
get { return this._drawImages; }
set { this._drawImages = value; }
}
private string _customImagePath = "";
public string CustomImagePath
{
get { return this._customImagePath; }
set { this._customImagePath = value; }
}
public bool CanManage { get; set; }
private string _imagePath = "";
private ContextMenuStrip ImageMenu;
private ToolStripMenuItem DeleteItem;
private ToolStripMenuItem AddItem;
private RectangleF FaceRect { get; set; }
private Rectangle ClientRect { get; set; }
private RectangleF Rect { get; set; }
private RectangleF PageInfoRect { get; set; }
private RectangleF MemoRect { get; set; }
private RectangleF PageUpRect { get; set; }
private RectangleF PageDownRect { get; set; }
private Color HoveColor { get; set; }
private readonly StringFormat sf = new StringFormat
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
public string ImagePath
{
get { return this._imagePath; }
set { this._imagePath = value; }
}
public bool ShowDemo { get; set; }
private bool HoveUp { get; set; }
private bool HoveDown { get; set; }
public bool IsCustomImage { get; set; }
#endregion
#region Events
public event SelectFaceHnadler Selected = null;
protected virtual void OnSelected(SelectFaceArgs e)
{
if(this.Selected != null)
{
this.Selected(this, e);
}
}
#endregion
public ImagePopup()
{
this.InitializeComponent();
// Window Style
this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Minimized;
this.Show();
this.Hide();
this.WindowState = FormWindowState.Normal;
this.ShowInTaskbar = false;
this.TopMost = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ControlBox = false;
}
#region Public Methods
public bool Init(int imageWidth, int imageHeight, int nHSpace, int nVSpace, int nColumns, int nRows)
{
if (this.DesignMode)
{
return false;
}
try
{
ImageEntity img;
this.Images.Clear();
this.DrawImages.Clear();
try
{
if (!File.Exists(Path.Combine(Application.StartupPath, this.ImagePath + "Images.db")))
{
foreach (string imgPath in Directory.GetFiles(Path.Combine(Application.StartupPath, this.ImagePath)))
{
img = new ImageEntity(imgPath);
if (img.Image != null)
{
this.Images.Add(img);
}
}
try
{
Tools.BinarySerializer(this.Images, Path.Combine(Application.StartupPath, this.ImagePath + "Images.db"));
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
}
else
{
this.Images = Tools.BinaryDeserialize<List<ImageEntity>>(Path.Combine(Application.StartupPath, this.ImagePath + "Images.db"));
try
{
foreach (var item in this.Images)
{
if (!File.Exists(item.FullName))
{
item.IsDelete = true;
}
}
}
catch { }
foreach (var imgItem in this.Images.FindAll(item => item.IsDelete))
{
try
{
File.Delete(imgItem.FullName);
}
catch
{
}
}
}
}
catch
{
this.Images = new List<ImageEntity>();
}
this.DrawImages = this.Images.FindAll(item => !item.IsDelete);
this.Images = this.DrawImages.FindAll(item => !item.IsDelete);
this.Demo.Width = imageWidth * 3 - 10;
this.Demo.Height = imageHeight * 3 - 10;
this._nColumns = nColumns;
this._nRows = nRows;
this._nHSpace = nHSpace;
this._nVSpace = nVSpace;
this._imageWidth = imageWidth;
this._imageHeight = imageHeight;
this._nItemWidth = imageWidth + nHSpace;
this._nItemHeight = imageHeight + nVSpace;
this._nBitmapWidth = this._nColumns * this._nItemWidth + 1;
this._nBitmapHeight = this._nRows * this._nItemHeight + 1;
this.Width = this._nBitmapWidth;
this.Height = this._nBitmapHeight + 20;
Graphics g = this.CreateGraphics();
this.PageIndex = 0;
this.PageImageCount = this._nColumns * this._nRows;
this.UpdatePageCount();
this.ClientRect = new Rectangle(0, 0, this.Width - 1, this.Height - 1);
this.FaceRect = new RectangleF(0f, 0f, this._nBitmapWidth, this._nBitmapHeight);
this.Rect = new RectangleF(1f, 1f, this._nBitmapWidth - 2, this._nBitmapHeight - 2);
SizeF s = g.MeasureString("上一页", this.Font);
SizeF i = g.MeasureString(string.Format("{0}/{1}", this.PageCount, this.PageCount), this.Font);
SizeF z = g.MeasureString("单击右键进行管理!", this.Font);
this.PageInfoRect = new RectangleF(new PointF(this.ClientRect.Width - s.Width * 2 - i.Width-20, this.FaceRect.Height + 3), i);
this.PageDownRect = new RectangleF(new PointF(this.ClientRect.Width - s.Width - 10, this.FaceRect.Height + 3), s);
this.PageUpRect = new RectangleF(new PointF(this.ClientRect.Width - s.Width * 2 - 10, this.FaceRect.Height + 3), s);
this.MemoRect = new RectangleF(new PointF(6, this.FaceRect.Height + 3), z);
this.HoveColor = Color.Blue;
this.DrawBackImage();
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
return true;
}
private void UpdatePageCount()
{
float t = this.DrawImages.Count / (float) this.PageImageCount;
this.PageCount = (t > (int) t) ? (int) t + 1 : (int) t;
if(this.PageCount == 1)
{
this.PageIndex = 0;
}
}
private void DrawBackImage()
{
this._Bitmap = new Bitmap(this._nBitmapWidth, this._nBitmapHeight);
Graphics g = Graphics.FromImage(this._Bitmap);
g.FillRectangle(new SolidBrush(this.BackgroundColor), 0, 0, this._nBitmapWidth, this._nBitmapHeight);
for(int i = 0; i < this._nColumns; i++)
{
g.DrawLine(new Pen(this.VLinesColor), i * this._nItemWidth, 0, i * this._nItemWidth,
this._nBitmapHeight - 1);
}
for(int i = 0; i < this._nRows; i++)
{
g.DrawLine(new Pen(this.HLinesColor), 0, i * this._nItemHeight, this._nBitmapWidth - 1,
i * this._nItemHeight);
}
g.DrawRectangle(new Pen(this.BorderColor), 0, 0, this._nBitmapWidth - 1, this._nBitmapHeight - 1);
for(int i = 0; i < this._nColumns; i++)
{
for(int j = 0; j < this._nRows; j++)
{
if((j * this._nColumns + i) < this.DrawImages.Count - this.PageIndex * this.PageImageCount)
{
g.DrawImage(this.DrawImages[this.PageIndex * this.PageImageCount + j * this._nColumns + i].Image,
i * this._nItemWidth + this._nHSpace / 2,
j * this._nItemHeight + this._nVSpace / 2, this._imageWidth, this._imageHeight);
}
}
}
}
public void Show(int x, int y)
{
this.Show(x, y, 0);
}
public void Show(int x, int y, int offsetHeight)
{
this.Show(x, y, null, offsetHeight);
}
public void Show(int x, int y, Control ctl)
{
this.Show(x, y, ctl, 0);
}
public void Show(int x, int y, Control ctl, int offsetHeight)
{
Point pt = new Point(x, y);
int tmpHeight = 0;
if(ctl != null)
{
tmpHeight = ctl.Top + ctl.Height;
}
if(pt.X < 0)
{
pt = new Point(0, pt.Y);
}
if(pt.Y < 0)
{
pt = new Point(pt.X, 0);
}
if(pt.Y + this.Height > Screen.PrimaryScreen.WorkingArea.Height)
{
pt = new Point(pt.X, pt.Y - this.Height - tmpHeight - offsetHeight);
}
if(pt.X + this.Width > Screen.PrimaryScreen.WorkingArea.Width)
{
pt = new Point(pt.X - (pt.X + this.Width - Screen.PrimaryScreen.WorkingArea.Width), pt.Y);
}
this.Left = pt.X;
this.Top = pt.Y;
this.Demo.Visible = false;
this.IsShowDialog = false;
this.Show();
this.Refresh();
}
#endregion
#region Overrides
protected override void OnMouseLeave(EventArgs ea)
{
base.OnMouseLeave(ea);
this._nCoordX = -1;
this._nCoordY = -1;
this.Invalidate();
}
protected override void OnDeactivate(EventArgs ea)
{
if(this.IsShowDialog)
{
return;
}
this.ImageMenu.Hide();
this.Hide();
}
protected override void OnKeyDown(KeyEventArgs kea)
{
if(this.DrawImages == null || this.DrawImages.Count == 0)
{
return;
}
if(this._nCoordX == -1 || this._nCoordY == -1)
{
this._nCoordX = 0;
this._nCoordY = 0;
this.Invalidate();
}
else
{
switch(kea.KeyCode)
{
case Keys.Down:
if(this._nCoordY < this._nRows - 1)
{
this._nCoordY++;
this.Invalidate();
}
break;
case Keys.Up:
if(this._nCoordY > 0)
{
this._nCoordY--;
this.Invalidate();
}
break;
case Keys.Right:
if(this._nCoordX < this._nColumns - 1)
{
this._nCoordX++;
this.Invalidate();
}
break;
case Keys.Left:
if(this._nCoordX > 0)
{
this._nCoordX--;
this.Invalidate();
}
break;
case Keys.Enter:
case Keys.Space:
this.imageIndex = this.PageIndex * this.PageImageCount + this._nCoordY * this._nColumns + this._nCoordX;
if(this.Selected != null && this.imageIndex >= 0 && this.imageIndex < this.DrawImages.Count)
{
this.OnSelected(new SelectFaceArgs(this.DrawImages[this.imageIndex]));
this._nCoordX = -1;
this._nCoordY = -1;
this.Hide();
}
break;
case Keys.Escape:
this._nCoordX = -1;
this._nCoordY = -1;
this.Hide();
break;
}
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
this.HoveUp = this.PageUpRect.Contains(e.Location);
this.HoveDown = this.PageDownRect.Contains(e.Location);
if(!this.Rect.Contains(e.Location))
{
this._nCoordX = -1;
this._nCoordY = -1;
this.Invalidate();
base.OnMouseMove(e);
return;
}
if (this.DrawImages == null || this.DrawImages.Count == 0)
{
return;
}
Image tmpImg;
if(((e.X / this._nItemWidth) != this._nCoordX) || ((e.Y / this._nItemHeight) != this._nCoordY))
{
this._nCoordX = e.X / this._nItemWidth;
this._nCoordY = e.Y / this._nItemHeight;
this.imageIndex = this.PageIndex * this.PageImageCount + this._nCoordY * this._nColumns + this._nCoordX;
if(this.imageIndex >= 0 && this.imageIndex < this.DrawImages.Count)
{
this.IsShowDialog = false;
this.Demo.Visible = true && ShowDemo;
if(this._nCoordX <= 2)
{
this.Demo.Left = this.Width - this.Demo.Width;
}
else if(this._nColumns - this._nCoordX <= 3)
{
this.Demo.Left = 0;
}
tmpImg = this.DrawImages[this.imageIndex].Image;
if(tmpImg != null)
{
if(tmpImg.Width > this.Demo.Width || tmpImg.Height > this.Demo.Height)
{
this.Demo.SizeMode = PictureBoxSizeMode.Zoom;
}
else
{
this.Demo.SizeMode = PictureBoxSizeMode.CenterImage;
}
this.Demo.Image = tmpImg;
}
}
else
{
this.Demo.Visible = false;
}
this.Invalidate();
}
base.OnMouseMove(e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if(this.Rect.Contains(e.Location))
{
if(e.Button == MouseButtons.Left)
{
this._bIsMouseDown = true;
this.Invalidate();
}
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseDown(e);
if(this.Rect.Contains(e.Location))
{
if(e.Button == MouseButtons.Left)
{
if(this.DrawImages == null)
{
return;
}
this._bIsMouseDown = false;
this.imageIndex = this.PageIndex * this.PageImageCount + this._nCoordY * this._nColumns + this._nCoordX;
if(this.Selected != null && this.imageIndex >= 0 && this.imageIndex < this.DrawImages.Count)
{
this.OnSelected(new SelectFaceArgs(this.DrawImages[this.imageIndex]));
this.Hide();
}
}
}
}
protected override void OnMouseClick(MouseEventArgs e)
{
if(this.Rect.Contains(e.Location))
{
if (CanManage && e.Button == MouseButtons.Right)
{
if(this.imageIndex >= 0 && this.imageIndex < this.DrawImages.Count)
{
this.DeleteItem.Enabled = this.DrawImages[this.imageIndex].IsCustom;
}
else
{
this.DeleteItem.Enabled = false;
}
this.ImageMenu.Show(MousePosition);
}
}
if(this.PageUpRect.Contains(e.Location))
{
if(this.PageIndex > 0)
{
this.Demo.Visible = false;
this.PageIndex--;
this.DrawBackImage();
this.Invalidate();
}
}
if(this.PageDownRect.Contains(e.Location))
{
if(this.PageIndex < this.PageCount - 1)
{
this.Demo.Visible = false;
this.PageIndex++;
this.DrawBackImage();
this.Invalidate();
}
}
base.OnMouseClick(e);
}
protected override void OnPaintBackground(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.PageUnit = GraphicsUnit.Pixel;
g.SmoothingMode = SmoothingMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.Clear(Color.White);
g.DrawRectangle(new Pen(this.BorderColor), this.ClientRect);
using(Bitmap offscreenBitmap = new Bitmap(this._nBitmapWidth, this._nBitmapHeight))
{
using(Graphics offscreenGrfx = Graphics.FromImage(offscreenBitmap))
{
offscreenGrfx.DrawImage(this._Bitmap, this.FaceRect);
if (this.DrawImages != null && this.DrawImages.Count > 0)
{
if (this._nCoordX != -1 && this._nCoordY != -1 &&
(this._nCoordY * this._nColumns + this._nCoordX) <
this.DrawImages.Count - this.PageIndex * this.PageImageCount)
{
offscreenGrfx.FillRectangle(new SolidBrush(this.BackgroundOverColor),
this._nCoordX * this._nItemWidth + 1,
this._nCoordY * this._nItemHeight + 1,
this._nItemWidth - 1, this._nItemHeight - 1);
if (this._bIsMouseDown)
{
offscreenGrfx.DrawImage(
this.DrawImages[
this.PageIndex * this.PageImageCount + this._nCoordY * this._nColumns + this._nCoordX].Image,
this._nCoordX * this._nItemWidth + this._nHSpace / 2 + 1,
this._nCoordY * this._nItemHeight + this._nVSpace / 2 + 1, this._imageWidth,
this._imageHeight);
}
else
{
offscreenGrfx.DrawImage(
this.DrawImages[
this.PageIndex * this.PageImageCount + this._nCoordY * this._nColumns + this._nCoordX].Image,
this._nCoordX * this._nItemWidth + this._nHSpace / 2,
this._nCoordY * this._nItemHeight + this._nVSpace / 2, this._imageWidth,
this._imageHeight);
}
offscreenGrfx.DrawRectangle(new Pen(this.BorderColor), this._nCoordX * this._nItemWidth,
this._nCoordY * this._nItemHeight, this._nItemWidth,
this._nItemHeight);
}
}
}
g.DrawImage(offscreenBitmap, this.FaceRect);
if (CanManage)
{
using (SolidBrush b = new SolidBrush(Color.Black))
{
g.DrawString("单击右键进行管理!", this.Font, b, this.MemoRect, this.sf);
g.DrawString(string.Format("{0}/{1}", this.PageIndex + 1, this.PageCount), this.Font, b,
this.PageInfoRect, this.sf);
}
}
using(SolidBrush b = new SolidBrush(this.HoveUp ? this.HoveColor : Color.Black))
{
g.DrawString("上一页", this.Font, b, this.PageUpRect, this.sf);
}
using(SolidBrush b = new SolidBrush(this.HoveDown ? this.HoveColor : Color.Black))
{
g.DrawString("下一页", this.Font, b, this.PageDownRect, this.sf);
}
}
}
#endregion
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.Demo = new System.Windows.Forms.PictureBox();
this.ImageMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.AddItem = new System.Windows.Forms.ToolStripMenuItem();
this.DeleteItem = new System.Windows.Forms.ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.Demo)).BeginInit();
this.ImageMenu.SuspendLayout();
this.SuspendLayout();
//
// Demo
//
this.Demo.BackColor = System.Drawing.Color.White;
this.Demo.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.Demo.Location = new System.Drawing.Point(0, 0);
this.Demo.Name = "Demo";
this.Demo.Size = new System.Drawing.Size(72, 72);
this.Demo.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
this.Demo.TabIndex = 0;
this.Demo.TabStop = false;
this.Demo.VisibleChanged += new System.EventHandler(this.Demo_VisibleChanged);
this.Demo.MouseEnter += new System.EventHandler(this.Demo_MouseEnter);
//
// ImageMenu
//
this.ImageMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.AddItem,
this.DeleteItem});
this.ImageMenu.Name = "Menu";
this.ImageMenu.Size = new System.Drawing.Size(113, 48);
//
// AddItem
//
this.AddItem.Name = "AddItem";
this.AddItem.Size = new System.Drawing.Size(112, 22);
this.AddItem.Text = "增加(&A)";
this.AddItem.Click += new System.EventHandler(this.AddItem_Click);
//
// DeleteItem
//
this.DeleteItem.Name = "DeleteItem";
this.DeleteItem.Size = new System.Drawing.Size(112, 22);
this.DeleteItem.Text = "删除(&D)";
this.DeleteItem.Click += new System.EventHandler(this.DeleteItem_Click);
//
// ImagePopup
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.ClientSize = new System.Drawing.Size(292, 266);
this.ControlBox = false;
this.Controls.Add(this.Demo);
this.DoubleBuffered = true;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "ImagePopup";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
((System.ComponentModel.ISupportInitialize)(this.Demo)).EndInit();
this.ImageMenu.ResumeLayout(false);
this.ResumeLayout(false);
}
private void Demo_MouseEnter(object sender, EventArgs e)
{
if(this.Demo.Left == 0)
{
this.Demo.Left = this.Width - this.Demo.Width;
}
else
{
this.Demo.Left = 0;
}
}
private void DeleteItem_Click(object sender, EventArgs e)
{
this.IsShowDialog = true;
try
{
if (MessageBox.Show(this, "请您确认删除?", "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) ==
DialogResult.OK)
{
ImageEntity img = this.Images.Find(item => item.MD5 == this.DrawImages[this.imageIndex].MD5);
if (img != null)
{
img.IsDelete = true;
}
this.DrawImages.Clear();
this.DrawImages = this.Images.FindAll(item => !item.IsDelete);
try
{
Tools.BinarySerializer(this.Images, Path.Combine(Application.StartupPath, this.ImagePath + "Images.db"));
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
this.UpdatePageCount();
this.DrawBackImage();
this.Invalidate();
}
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
finally
{
this.IsShowDialog = false;
}
}
private void AddItem_Click(object sender, EventArgs e)
{
if(this.CustomHead())
{
//imageIndex = this.DrawImages.Count - 1;
//this.OnSelected(new SelectFaceArgs(this.DrawImages[imageIndex]));
//this.Hide();
}
}
private bool CustomHead()
{
try
{
this.Demo.Visible = false;
this.IsShowDialog = true;
int count = 0;
int err = 0;
OpenFileDialog dlg = new OpenFileDialog
{
Filter = ("图像文件 (*.jpg;*.png;*.gif;*.bmp)|*.jpg;*.jpeg;*.png;*.gif;*.bmp|" +
"JPEG 文件 (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"PNG 文件 (*.png)|*.png|" +
"GIF 文件 (*.gif)|*.gif|" +
"位图文件 (*.bmp)|*.bmp|" +
"所有文件 (*.*)|*.*"),
FilterIndex = 0,
Title = "选择头像",
RestoreDirectory = true,
Multiselect = true
};
string tmpImgMD5 = "";
if (dlg.ShowDialog() == DialogResult.OK)
{
foreach (string file in dlg.FileNames)
{
if (File.Exists(file))
{
try
{
string shortname = string.Format(this.CustomImagePath + "{0}{1}", Guid.NewGuid(),
Path.GetExtension(file));
string fullname = Path.Combine(Application.StartupPath, shortname);
try
{
Image.FromFile(file);
}
catch
{
err++;
break;
}
Tools.CreateDir(Path.GetDirectoryName(fullname));
if (!Path.GetDirectoryName(file).Equals(Path.GetDirectoryName(fullname)))
{
tmpImgMD5 = SecurityHelper.GetMD5(file);
if (this.DrawImages.Exists(item => item.MD5.ToLower() == tmpImgMD5.ToLower()))
{
count++;
break;
}
File.Copy(file, fullname, true);
}
ImageEntity img = new ImageEntity(fullname) { IsCustom = true };
if (!this.Images.Exists(item => item.MD5.ToLower() == img.MD5.ToLower()))
{
this.Images.Add(img);
}
else
{
ImageEntity tmp = this.Images.Find(item => item.MD5.ToLower() == img.MD5.ToLower());
if(tmp != null)
{
tmp.IsDelete = false;
}
}
this.DrawImages.Clear();
this.DrawImages = this.Images.FindAll(item => !item.IsDelete);
}
catch
{
}
}
}
if (dlg.FileNames.Length > 1)
{
this.DrawBackImage();
this.Invalidate();
MessageBox.Show(this,
string.Format("共选择{0}个表情,{1}个表情己存在,成功添加{2}个表情,添加失败{3}个表情!", dlg.FileNames.Length,
count, dlg.FileNames.Length - count - err, err), "提示信息",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
if (count > 0)
{
MessageBox.Show(this, "表情已存在,请重新选择!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
if (err > 0)
{
MessageBox.Show(this, "表情添加失败,请重新选择!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
this.DrawBackImage();
this.Invalidate();
MessageBox.Show(this, "表情添加成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
try
{
Tools.BinarySerializer(this.Images, Path.Combine(Application.StartupPath, this.ImagePath + "Images.db"));
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
this.UpdatePageCount();
return true;
}
}
catch { }
finally
{
this.IsShowDialog = false;
}
return false;
}
private void Demo_VisibleChanged(object sender, EventArgs e)
{
if(!this.Demo.Visible)
{
this.Demo.Image = null;
this.Demo.Refresh();
}
}
}
public delegate void SelectFaceHnadler(object sender, SelectFaceArgs e);
public class SelectFaceArgs : EventArgs
{
public SelectFaceArgs()
{
}
public SelectFaceArgs(ImageEntity img)
: this()
{
this.Img = img;
}
public SelectFaceArgs(ImageEntity img, object tag)
: this(img)
{
this.Tag = tag;
}
public ImageEntity Img { get; set; }
public object Tag { get; set; }
}
[Serializable]
public class ImageEntity
{
public ImageEntity()
{
}
public ImageEntity(string fullName)
: this()
{
this.FullName = fullName.Replace(Application.StartupPath + "\\", ""); ;
this.FilePath = Path.GetDirectoryName(fullName).Replace(Application.StartupPath + "\\", "");
this.RelativePath = this.FilePath.Replace(Application.StartupPath + "\\", "");
this.FileName = Path.GetFileName(fullName);
try
{
this.Image = Image.FromFile(fullName);
this.MD5 = SecurityHelper.GetMD5(fullName);
}
catch(Exception ex)
{
this.Image = null;
try
{
File.Delete(fullName);
}
catch
{
}
Debug.WriteLine(fullName);
Debug.WriteLine(ex);
}
}
public ImageEntity(string filePath, object tag)
: this(filePath)
{
this.Tag = tag;
}
public string FileName { get; set; }
private string _fullName;
public string FullName
{
get
{
return Path.Combine(Application.StartupPath, this._fullName);
}
set { this._fullName = value; }
}
public string RelativePath { get; set; }
private string _filePath;
public string FilePath
{
get
{
return Path.Combine(Application.StartupPath,this._filePath);
}
set { this._filePath = value; }
}
public bool IsCustom { get; set; }
public Image Image { get; set; }
public string MD5 { get; set; }
public object Tag { get; private set; }
public bool IsDelete { get; set; }
}
}[/code]
下面是一个工具类代码
[code=csharp]/// <summary>
///更新网站 http://www.sufeinet.com/thread-1789-1-1.html
/// </summary>
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace Framework.Utility
{
/// <summary>
/// 工具类定义
/// </summary>
public class Tools
{
/// <summary>
/// 二进制序列化
/// </summary>
/// <typeparam name="T">序列化的类型</typeparam>
/// <param name="obj">序列化的对象</param>
/// <param name="filename">序列化的XML文件名</param>
public static void BinarySerializer<T>(T obj, string filename)
{
using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, obj);
}
catch (SerializationException e)
{
Trace.WriteLine(e);
}
}
}
/// <summary>
/// 二进制反列化
/// </summary>
/// <typeparam name="T">反序列化的类型</typeparam>
/// <param name="filename">反序列化的XML文件名</param>
/// <returns>T类型对象</returns>
public static T BinaryDeserialize<T>(string filename)
{
// 检查文件是否存在
if (!File.Exists(filename))
{
return default(T);
}
T obj = default(T);
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
BinaryFormatter formatter = new BinaryFormatter();
try
{
obj = (T)formatter.Deserialize(fs);
}
catch (SerializationException e)
{
Trace.WriteLine(e);
}
}
return obj;
}
/// <summary>
/// 创建目录
/// </summary>
/// <param name="path">目录名</param>
public static void CreateDir(string path)
{
string[] dirs = path.Split(char.Parse("\\"));
string tmp = "";
if (!Directory.Exists(path))
{
foreach (string item in dirs)
{
tmp += item + "\\";
if (!Directory.Exists(tmp))
{
Directory.CreateDirectory(tmp);
}
}
}
}
}
/// <summary>
/// 安全助手类定义
/// </summary>
public class SecurityHelper
{
/// <summary>
/// 获取字符串的 MD5 值
/// </summary>
/// <param name="text">字符串</param>
/// <returns>MD5 值</returns>
public static string GetStringMD5(string text)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] encryptedBytes = md5.ComputeHash(Encoding.Default.GetBytes(text));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < encryptedBytes.Length; i++)
{
sb.AppendFormat("{0:x2}", encryptedBytes);
}
return sb.ToString();
}
/// <summary>
/// 实现对一个文件md5的读取,path为文件路径
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string GetMD5(string path)
{
try
{
using (Stream file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
return GetMD5(file);
}
}
catch (Exception e)
{
return e.ToString();
}
}
/// <summary>
/// 获取流的 MD5 值
/// </summary>
/// <param name="s">流</param>
/// <returns>MD5 值</returns>
public static string GetMD5(Stream s)
{
byte[] hash_byte;
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
hash_byte = md5.ComputeHash(s);
}
return GetMD5String(hash_byte);
}
/// <summary>
/// 获取数组的 MD5 值
/// </summary>
/// <param name="buffer">数组</param>
/// <returns>MD5 值</returns>
public static string GetMD5(byte[] buffer)
{
byte[] hash_byte;
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
hash_byte = md5.ComputeHash(buffer);
}
return GetMD5String(hash_byte);
}
/// <summary>
/// 获取数组的 MD5 值
/// </summary>
/// <param name="buffer">数组</param>
/// <param name="offset">偏移</param>
/// <param name="count">长度</param>
/// <returns>MD5 值</returns>
public static string GetMD5(byte[] buffer, int offset, int count)
{
byte[] hash_byte;
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
hash_byte = md5.ComputeHash(buffer, offset, count);
}
return GetMD5String(hash_byte);
}
/// <summary>
/// 获取数组的 MD5 值
/// </summary>
/// <param name="hash_byte">数组</param>
/// <returns>MD5 值</returns>
private static string GetMD5String(byte[] hash_byte)
{
string resule = BitConverter.ToString(hash_byte);
resule = resule.Replace("-", "");
return resule;
}
}
}[/code]
大家可以下载下来测试一下
给提提建议
|
|