C#影像處理類(網上程式碼、還未使用)

weixin_34391854發表於2011-08-02
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;
 
namespace Silent.Web.Controllers.Common
{
    /**////  <summary>
    /// ASPJpegBase
    /// Author : Jolly
    ///  </summary>
    public class ASPJpegBase : IDisposable
    {
        /**////  <summary>
        /// 會產生graphics異常的PixelFormat
        ///  </summary>
        private static PixelFormat[] indexedPixelFormats = { PixelFormat.Undefined, PixelFormat.DontCare, PixelFormat.Format16bppArgb1555, PixelFormat.Format1bppIndexed, PixelFormat.Format4bppIndexed, PixelFormat.Format8bppIndexed };
 
        /**////  <summary>
        /// 圖片寬度--生成縮圖時使用
        ///  </summary>
        public int Width { get; set; }
        /**////  <summary>
        /// 圖片高度--生成縮圖時使用
        ///  </summary>
        public int Height { get; set; }
 
        /**////  <summary>
        /// Bitmap物件
        ///  </summary>
        public Bitmap CurrentBitmap
        {
            get { if (oCurrentImage == null) throw new NullReferenceException("CurrentBitmap is null!"); return oCurrentImage; }
        }
 
        private Bitmap oCurrentImage;
 
        private ASPJpegEffect etASPJpegEffect;
 
        /**////  <summary>
        /// 圖片特效處理
        ///  </summary>
        public ASPJpegEffect Effect
        {
            get
            {
                etASPJpegEffect = new ASPJpegEffect();
                etASPJpegEffect.CurrentBitmap = this.CurrentBitmap;
                return etASPJpegEffect;
            }
        }
 
        /**////  <summary>
        /// 預設建構函式
        ///  </summary>
        public ASPJpegBase()
        {
 
        }
 
        /**////  <summary>
        /// 建構函式
        ///  </summary>
        ///  <param name="sImagePath">圖片路徑 </param>
        public ASPJpegBase(string sImagePath)
        {
            oCurrentImage = new Bitmap(sImagePath);
            //如果原圖片是索引畫素格式之列的,則需要轉換
            if (IsPixelFormatIndexed(oCurrentImage.PixelFormat))
            {
                using(Bitmap bmp = new Bitmap(oCurrentImage.Width, oCurrentImage.Height, PixelFormat.Format32bppArgb))
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.DrawImage(oCurrentImage, 0, 0);
                    }
                    oCurrentImage = (Bitmap)bmp.Clone();
                }
            }
        }
 
        /**////  <summary>
        /// 建構函式
        ///  </summary>
        ///  <param name="oImage">Image物件 </param>
        public ASPJpegBase(Image oImage)
        {
            oCurrentImage = new Bitmap(oImage);
        }
 
        /**////  <summary>
        /// 例項化Bitmap物件
        ///  </summary>
        ///  <param name="sImagePath">圖片路徑 </param>
        public void Open(string sImagePath)
        {
            oCurrentImage = new Bitmap(sImagePath);
        }
 
        /**////  <summary>
        /// 判斷圖片的PixelFormat 是否在 引發異常的 PixelFormat 之中
        /// 無法從帶有索引畫素格式的影像建立graphics物件
        ///  </summary>
        ///  <param name="imgPixelFormat">原圖片的PixelFormat </param>
        ///  <returns> </returns>
        private static bool IsPixelFormatIndexed(PixelFormat imgPixelFormat)
        {
            foreach (PixelFormat pf in indexedPixelFormats)
            {
                if (pf.Equals(imgPixelFormat)) return true;
            }
 
            return false;
        }
 
        /**////  <summary>
        /// 新增文字水印
        ///  </summary>
        ///  <param name="text"> </param>
        ///  <param name="p"> </param>
        ///  <param name="fontcolor"> </param>
        ///  <param name="font"> </param>
        public void DrawText(string sText, Font font, Color fontcolor, Point p, float rotate)
        {
            using (Graphics graphics = Graphics.FromImage(this.CurrentBitmap))
            {
                if (rotate != 0)
                    graphics.RotateTransform(rotate);
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.DrawString(sText, font, new SolidBrush(fontcolor), (float)p.X, (float)p.Y);
            }
        }
 
        /**////  <summary>
        /// 新增文字水印-文字帶背景
        ///  </summary>
        ///  <param name="text"> </param>
        ///  <param name="p"> </param>
        ///  <param name="fontcolor"> </param>
        ///  <param name="font"> </param>
        public void DrawText(string sText, Font font, Color fontcolor, Point p, float rotate, string sImagePath)
        {
            TextureBrush tb = new TextureBrush(Image.FromFile(sImagePath));
            using (Graphics graphics = Graphics.FromImage(this.CurrentBitmap))
            {
                if (rotate != 0)
                    graphics.RotateTransform(rotate);
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.DrawString(sText, font, tb, (float)p.X, (float)p.Y);
            }
        }
 
        /**////  <summary>
        /// 繪製邊框
        ///  </summary>
        ///  <param name="frameColor">邊框顏色 </param>
        ///  <param name="frameWidth">邊框寬度 </param>
        public void DrawFrame(Color frameColor, int frameWidth)
        {
            double iNewframeWidth = (Convert.ToDouble(frameWidth) / Convert.ToDouble(2));
            using (Bitmap newBitmap = new Bitmap(this.CurrentBitmap.Width + (2 * frameWidth), this.CurrentBitmap.Height + (2 * frameWidth)))
            {
                using (Graphics graphics = Graphics.FromImage(newBitmap))
                {
                    graphics.Clear(Color.White);
                    Pen pen = new Pen(frameColor, frameWidth);
                    graphics.DrawRectangle(pen, (float)iNewframeWidth, (float)iNewframeWidth, newBitmap.Width - frameWidth, newBitmap.Height - frameWidth);
                    graphics.DrawImage(this.CurrentBitmap, new Rectangle(frameWidth, frameWidth,this.CurrentBitmap.Width,this.CurrentBitmap.Height));
 
                    this.oCurrentImage = ((Bitmap)newBitmap.Clone());
                }
            }
        }
 
        /**////  <summary>
        /// 繪製3D邊框
        ///  </summary>
        ///  <param name="frameColor">邊框顏色 </param>
        ///  <param name="frameWidth">邊框寬度 </param>
        public void Draw3DFrame(Color frameColor, int frameWidth)
        {
            double iNewframeWidth = (Convert.ToDouble(frameWidth) / Convert.ToDouble(2));
            using (Bitmap newBitmap = new Bitmap(this.CurrentBitmap.Width + (2 * frameWidth), this.CurrentBitmap.Height + (2 * frameWidth)))
            {
                using (Graphics graphics = Graphics.FromImage(newBitmap))
                {
                    graphics.Clear(Color.White);
                    Pen pen = new Pen(frameColor, (float)iNewframeWidth);
                    Pen pen1 = new Pen(Color.FromArgb(frameColor.ToArgb() - 10), (float)iNewframeWidth);
                    graphics.DrawRectangle(pen, (float)iNewframeWidth / 2, (float)iNewframeWidth / 2, newBitmap.Width - (float)iNewframeWidth, newBitmap.Height - (float)iNewframeWidth);
                    graphics.DrawRectangle(pen1, 3 * (float)iNewframeWidth / 2, 3 * (float)iNewframeWidth / 2, newBitmap.Width - 3 * (float)iNewframeWidth, newBitmap.Height - 3 * (float)iNewframeWidth);
 
                    graphics.DrawImage(this.CurrentBitmap, 2 * (float)iNewframeWidth, 2 * (float)iNewframeWidth, (float)this.CurrentBitmap.Width, (float)this.CurrentBitmap.Height);
 
                    this.oCurrentImage = (Bitmap)newBitmap.Clone();
                }
            }
        }
 
        /**////  <summary>
        /// 圖片切割功能
        ///  </summary>
        ///  <param name="left">left </param>
        ///  <param name="top">top </param>
        ///  <param name="right">right </param>
        ///  <param name="bottom">bottom </param>
        public void Crop(int left, int top, int right, int bottom)
        {
            int num;
            int num2;
            if ((this.CurrentBitmap.Width - left)  < right)
            {
                num = this.CurrentBitmap.Width - right;
            }
            else
            {
                num = right;
            }
            if ((this.CurrentBitmap.Height - top)  < bottom)
            {
                num2 = this.CurrentBitmap.Height - top;
            }
            else
            {
                num2 = bottom;
            }
            using (Bitmap image = new Bitmap(num, num2))
            {
                image.SetResolution(this.CurrentBitmap.HorizontalResolution, this.CurrentBitmap.VerticalResolution);
                using (Graphics graphics = Graphics.FromImage(image))
                {
                    graphics.Clear(Color.White);
                    graphics.SmoothingMode = SmoothingMode.HighQuality;
                    graphics.DrawImage(this.CurrentBitmap, new Rectangle(0, 0, num, num2), new Rectangle(left, top, num, num2), GraphicsUnit.Pixel);
                    oCurrentImage = (Bitmap)image.Clone();
                }
            }
        }
/**//// <summary>
       
/// 圖片移動
       
/// </summary>
       
/// <param name="lefttopx"></param>
       
/// <param name="lefttopy"></param>
       
/// <param name="rightbottomx"></param>
       
/// <param name="rightbottomy"></param>
       
/// <param name="tox"></param>
       
/// <param name="toy"></param>
        public void Move(int lefttopx, int lefttopy, int rightbottomx, int rightbottomy, int tox, int toy)
        {
           
using (Bitmap image = this.Copy(lefttopx, lefttopy, rightbottomx, rightbottomy))
            {
                Rectangle rect
= GetRectangle(lefttopx, lefttopy, rightbottomx, rightbottomy);
               
using (Graphics graphics = Graphics.FromImage(this.CurrentBitmap))
                {
                    graphics.Clear(Color.White);
                    graphics.FillRectangle(
new SolidBrush(Color.White), rect);
                    graphics.DrawImage(image, tox, toy);
                    oCurrentImage
= (Bitmap)image.Clone();
                }
            }
        }

       
/**//// <summary>
       
/// 調整圖片大小
       
/// </summary>
       
/// <param name="width"></param>
       
/// <param name="height"></param>
        public void ResizeTo(int width, int height)
        {
           
this.oCurrentImage = new Bitmap(this.CurrentBitmap, width, height);
        }

       
/**//// <summary>
       
/// 生成縮圖
       
/// </summary>
        public void CreateThumbnail(int iWidth, int iHeight)
        {
           
//用指定的大小和格式初始化 Bitmap 類的新例項
            using (Bitmap bitmap = (Bitmap)oCurrentImage.Clone())
            {
                ResizeTo(iWidth, iHeight);
               
//在指定位置並且按指定大小繪製 原圖片 物件
                Graphics.FromImage(oCurrentImage).DrawImage(bitmap, new Rectangle(0, 0, iWidth, iHeight));
            }
        }

       
/**//// <summary>
       
/// 生成縮圖
       
/// </summary>
       
/// <param name="sThumbnailPath">縮圖儲存路徑</param>
        public void CreateThumbnail(string sThumbnailPath)
        {
           
if (Width > 0 && Height > 0 && (Width < oCurrentImage.Width || Height < oCurrentImage.Height))
            {
               
int width = Width;
               
int height = Height;
               
double factor = 1;

               
if (oCurrentImage.Width > oCurrentImage.Height)
                {
                    factor
= Convert.ToDouble(width) / Convert.ToDouble(oCurrentImage.Width);
                    height
= Convert.ToInt32(oCurrentImage.Height * factor);
                }
               
else
                {
                    factor
= Convert.ToDouble(height) / Convert.ToDouble(oCurrentImage.Height);
                    width
= Convert.ToInt32(oCurrentImage.Width * factor);
                }
               
//用指定的大小和格式初始化 Bitmap 類的新例項
                Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
               
//從指定的 Image 物件建立新 Graphics 物件
                Graphics graphics = Graphics.FromImage(bitmap);
               
//清除整個繪圖面並以透明背景色填充
                graphics.Clear(Color.Transparent);
               
//在指定位置並且按指定大小繪製 原圖片 物件
                graphics.DrawImage(oCurrentImage, new Rectangle(0, 0, width, height));
               
try
                {
                    bitmap.Save(sThumbnailPath);
                }
               
catch (System.Exception e)
                {
                   
throw e;
                }
               
finally
                {
                    bitmap.Dispose();
                    graphics.Dispose();
                }
            }
        }

       
/**//// <summary>
       
/// 圖片垂直翻轉
       
/// </summary>
        public void FlipV()
        {
           
this.CurrentBitmap.RotateFlip(RotateFlipType.RotateNoneFlipX);
        }

       
/**//// <summary>
       
/// 圖片水平翻轉
       
/// </summary>
        public void FlipH()
        {
           
this.CurrentBitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
        }

       
/**//// <summary>
       
/// 圖片旋轉
       
/// </summary>
       
/// <param name="angle">旋轉度數</param>
        public void Rotate(int angle)
        {
            angle
= angle % 360;
           
if (angle < 0)
            {
                angle
+= 360;
            }
           
if (angle >= 270)
            {
               
this.CurrentBitmap.RotateFlip(RotateFlipType.Rotate270FlipNone);
                angle
-= 270;
            }
           
else if (angle >= 180)
            {
               
this.CurrentBitmap.RotateFlip(RotateFlipType.Rotate180FlipNone);
                angle
-= 180;
            }
           
else if (angle >= 90)
            {
               
this.CurrentBitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
                angle
-= 90;
            }
           
if (angle > 0)
            {
               
double a = (angle * 3.1415926535897931) / 180.0;
               
int width = Convert.ToInt32((double)((this.CurrentBitmap.Height * Math.Sin(a)) + (this.CurrentBitmap.Width * Math.Cos(a))));
               
int height = Convert.ToInt32((double)((this.CurrentBitmap.Width * Math.Sin(a)) + (this.CurrentBitmap.Height * Math.Cos(a))));
                Bitmap image
= new Bitmap(width, height * 2);
                image.SetResolution(
this.CurrentBitmap.HorizontalResolution, this.CurrentBitmap.VerticalResolution);
                Graphics graphics
= Graphics.FromImage(image);
                graphics.Clear(Color.White);
                Matrix matrix
= new Matrix(1f, 0f, 0f, -1f, 0f, 0f);
                matrix.Translate(0f, (
float)this.CurrentBitmap.Height, MatrixOrder.Append);
                graphics.Transform
= matrix;
                Matrix matrix2
= new Matrix();
                matrix2.RotateAt((
float)-angle, (PointF)new Point(0, 0), MatrixOrder.Append);
                matrix2.Translate(0f, 0f, MatrixOrder.Append);
                GraphicsPath path
= new GraphicsPath();
                Point[] points
= new Point[] { new Point(0, this.CurrentBitmap.Height), new Point(this.CurrentBitmap.Width, this.CurrentBitmap.Height), new Point(0, 0) };
                path.AddPolygon(points);
                path.Transform(matrix2);
                PointF[] pathPoints
= path.PathPoints;
                graphics.DrawImage(
this.CurrentBitmap, pathPoints);
                graphics.ResetTransform();
               
int num4 = this.CurrentBitmap.Height;
               
this.oCurrentImage = new Bitmap(width, height);
               
this.CurrentBitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution);
               
using (Graphics newGraphics = Graphics.FromImage(this.CurrentBitmap))
                {
                    newGraphics.Clear(Color.White);
                    newGraphics.DrawImage(image,
new Rectangle(0, 0, width, height), new Rectangle(0, Convert.ToInt32((double)(num4 * (1.0 - Math.Cos(a)))), width, height), GraphicsUnit.Pixel);
                    image.Dispose();
                    graphics.Dispose();
                    path.Dispose();
                }
            }
        }

       
/**//// <summary>
       
/// 畫弧形
       
/// </summary>
       
/// <param name="r"></param>
       
/// <param name="linewidth"></param>
       
/// <param name="linecolor"></param>
       
/// <param name="startangle"></param>
       
/// <param name="sweepAngle"></param>
        public void DrawArc(Rectangle r, int linewidth, Color linecolor, float startangle, float sweepAngle)
        {
           
using (Graphics graphics = Graphics.FromImage(this.CurrentBitmap))
            {
                Pen pen
= new Pen(linecolor, (float)linewidth);
                graphics.DrawArc(pen, r, startangle, sweepAngle);
            }
        }

       
/**//// <summary>
       
/// 畫橢圓
       
/// </summary>
       
/// <param name="r"></param>
       
/// <param name="linewidth"></param>
       
/// <param name="linecolor"></param>
       
/// <param name="fillcolor"></param>
        public void DrawEllipse(Rectangle r, int linewidth, Color linecolor, Color fillcolor)
        {
           
using (Graphics graphics = Graphics.FromImage(this.CurrentBitmap))
            {
                Pen pen
= new Pen(linecolor, (float)linewidth);
                graphics.DrawEllipse(pen, r);
               
if (fillcolor != Color.Empty)
                {
                    graphics.FillEllipse(
new SolidBrush(fillcolor), r);
                }
            }
        }

       
/**//// <summary>
       
/// 畫橢圓
       
/// </summary>
       
/// <param name="lefttop"></param>
       
/// <param name="rightbottom"></param>
       
/// <param name="linewidth"></param>
       
/// <param name="linecolor"></param>
       
/// <param name="fillcolor"></param>
        public void DrawEllipse(Point lefttop, Point rightbottom, int linewidth, Color linecolor, Color fillcolor)
        {
           
this.DrawEllipse(new Rectangle(lefttop.X, lefttop.Y, rightbottom.X - lefttop.X, rightbottom.Y - lefttop.Y), linewidth, linecolor, fillcolor);
        }

/**//// <summary>
       
/// 畫橢圓
       
/// </summary>
       
/// <param name="lefttopx"></param>
       
/// <param name="lefttopy"></param>
       
/// <param name="rightbottomx"></param>
       
/// <param name="rightbottomy"></param>
       
/// <param name="linewidth"></param>
       
/// <param name="linecolor"></param>
       
/// <param name="fillcolor"></param>
        public void DrawEllipse(int lefttopx, int lefttopy, int rightbottomx, int rightbottomy, int linewidth, Color linecolor, Color fillcolor)
        {
           
this.DrawEllipse(new Rectangle(lefttopx, lefttopy, rightbottomx - lefttopx, rightbottomy - lefttopy), linewidth, linecolor, fillcolor);
        }

       
/**//// <summary>
       
/// 畫圖上圖
       
/// </summary>
       
/// <param name="img"></param>
       
/// <param name="r"></param>
        public void DrawImage(System.Drawing.Image img, Rectangle r)
        {
            Graphics.FromImage(
this.CurrentBitmap).DrawImage(img, r);
        }

       
/**//// <summary>
       
/// 畫線
       
/// </summary>
       
/// <param name="pFrom"></param>
       
/// <param name="pTo"></param>
       
/// <param name="linewidth"></param>
       
/// <param name="linecolor"></param>
        public void DrawLine(Point pFrom, Point pTo, int linewidth, Color linecolor)
        {
           
using (Graphics graphics = Graphics.FromImage(this.CurrentBitmap))
            {
                Pen pen
= new Pen(linecolor, (float)linewidth);
                graphics.DrawLine(pen, pFrom, pTo);
            }
        }

       
/**//// <summary>
       
/// 畫線
       
/// </summary>
       
/// <param name="fromx"></param>
       
/// <param name="fromy"></param>
       
/// <param name="tox"></param>
       
/// <param name="toy"></param>
       
/// <param name="linewidth"></param>
       
/// <param name="linecolor"></param>
        public void DrawLine(int fromx, int fromy, int tox, int toy, int linewidth, Color linecolor)
        {
           
this.DrawLine(new Point(fromx, fromy), new Point(tox, toy), linewidth, linecolor);
        }

       
/**//// <summary>
       
/// 畫多條線
       
/// </summary>
       
/// <param name="points"></param>
       
/// <param name="linewidth"></param>
       
/// <param name="linecolor"></param>
        public void DrawLines(Point[] points, int linewidth, Color linecolor)
        {
           
using (Graphics graphics = Graphics.FromImage(this.CurrentBitmap))
            {
                Pen pen
= new Pen(linecolor, (float)linewidth);
                graphics.DrawLines(pen, points);
            }
        }

       
/**//// <summary>
       
/// 畫長方形
       
/// </summary>
       
/// <param name="r"></param>
       
/// <param name="linewidth"></param>
       
/// <param name="linecolor"></param>
       
/// <param name="fillcolor"></param>
        public void DrawRectangle(Rectangle r, int linewidth, Color linecolor, Color fillcolor)
        {
           
using (Graphics graphics = Graphics.FromImage(this.CurrentBitmap))
            {
                Pen pen
= new Pen(linecolor, (float)linewidth);
                graphics.DrawRectangle(pen, r);
               
if (fillcolor != Color.Empty)
                {
                    graphics.FillRectangle(
new SolidBrush(fillcolor), r);
                }
            }
        }

       
/**//// <summary>
       
/// 畫長方形
       
/// </summary>
       
/// <param name="lefttop"></param>
       
/// <param name="rightbottom"></param>
       
/// <param name="linewidth"></param>
       
/// <param name="linecolor"></param>
       
/// <param name="fillcolor"></param>
        public void DrawRectangle(Point lefttop, Point rightbottom, int linewidth, Color linecolor, Color fillcolor)
        {
           
this.DrawRectangle(new Rectangle(lefttop.X, lefttop.Y, rightbottom.X - lefttop.X, rightbottom.Y - lefttop.Y), linewidth, linecolor, fillcolor);
        }

       
/**//// <summary>
       
/// 畫長方形
       
/// </summary>
       
/// <param name="lefttopx"></param>
       
/// <param name="lefttopy"></param>
       
/// <param name="rightbottomx"></param>
       
/// <param name="rightbottomy"></param>
       
/// <param name="linewidth"></param>
       
/// <param name="linecolor"></param>
       
/// <param name="fillcolor"></param>
        public void DrawRectangle(int lefttopx, int lefttopy, int rightbottomx, int rightbottomy, int linewidth, Color linecolor, Color fillcolor)
        {
           
this.DrawRectangle(GetRectangle(lefttopx, lefttopy, rightbottomx, rightbottomy), linewidth, linecolor, fillcolor);
        }

       
/**//// <summary>
       
/// 儲存圖片到記憶體中
       
/// </summary>
       
/// <param name="mms"></param>
       
/// <param name="RawFormat"></param>
        public void Save(MemoryStream mms, ImageFormat RawFormat)
        {
           
this.CurrentBitmap.Save(mms, RawFormat);
        }

       
/**//// <summary>
       
/// 儲存圖片到檔案流中
       
/// </summary>
       
/// <param name="mms"></param>
       
/// <param name="RawFormat"></param>
        public void Save(Stream mms, ImageFormat RawFormat)
        {
           
this.CurrentBitmap.Save(mms, RawFormat);
        }

       
/**//// <summary>
       
/// 儲存為Gif圖片
       
/// </summary>
       
/// <param name="sSavePath"></param>
        public void SaveGif(string sSavePath)
        {
           
this.CurrentBitmap.Save(sSavePath, ImageFormat.Gif);
        }

       
/**//// <summary>
       
/// 儲存為jpg圖片
       
/// </summary>
       
/// <param name="sSavePath"></param>
       
/// <param name="iQuantity">圖片質量</param>
        public void SaveJpeg(string sSavePath, int iQuantity)
        {
            ImageCodecInfo encoderInfo
= GetEncoderInfo("image/jpeg");
            EncoderParameters encoderParams
= new EncoderParameters(1);
            encoderParams
= new EncoderParameters();
            encoderParams.Param[
0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)iQuantity);

           
this.CurrentBitmap.Save(sSavePath, encoderInfo, encoderParams);
            encoderParams.Dispose();
        }
}

相關文章