图片处理类

代码
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Threading;

namespace CropZoom_in_Net
{
    
/// <summary>
    
/// Summary description for $codebehindclassname$
    
/// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo 
= WsiProfiles.BasicProfile1_1)]
    
public class ProcessImage : IHttpHandler
    {

        
public void ProcessRequest(HttpContext context)
        {
            Thread.CurrentThread.CurrentUICulture 
= new System.Globalization.CultureInfo("en-US");
            Thread.CurrentThread.CurrentCulture 
= new System.Globalization.CultureInfo("en-US");

            context.Response.ContentType 
= "text/plain";
            
int ID = Convert.ToInt32(context.Request["ID"]);
            
float imageH = float.Parse(context.Request["imageH"]);
            
float imageW = float.Parse(context.Request["imageW"]);
            
float angle = float.Parse(context.Request["imageRotate"]);
            
string img_source = context.Request["imageSource"];
            
float imageX = float.Parse(context.Request["imageX"]);
            
float imageY = float.Parse(context.Request["imageY"]);
            
float selectorH = float.Parse(context.Request["selectorH"]);
            
float selectorW = float.Parse(context.Request["selectorW"]);
            
float selectorX = float.Parse(context.Request["selectorX"]);
            
float selectorY = float.Parse(context.Request["selectorY"]);
            
float viewPortH = float.Parse(context.Request["viewPortH"]);
            
float viewPortW = float.Parse(context.Request["viewPortW"]);

            
//To Values
            float pWidth = imageW;
            
float pHeight = imageH;

            Bitmap img 
= (Bitmap)Bitmap.FromFile(context.Server.MapPath(img_source));
            
//Original Values
            int _width = img.Width;
            
int _height = img.Height;

            
//Resize
            Bitmap image_p = ResizeImage(img, Convert.ToInt32(pWidth), Convert.ToInt32(pHeight));

            
int widthR = image_p.Width;
            
int heightR = image_p.Height;
            
//Rotate if angle is not 0.00 or 360
            if (angle > 0.0F && angle < 360.00F)
            {
                image_p 
= (Bitmap)RotateImage(image_p, (double)angle);
                pWidth 
= image_p.Width;
                pHeight 
= image_p.Height;
            }

            
//Calculate Coords of the Image into the ViewPort
            float src_x = 0;
            
float dst_x = 0;
            
float src_y = 0;
            
float dst_y = 0;

            
if (pWidth > viewPortW)
            {
                src_x 
= (float)Math.Abs(imageX - Math.Abs((imageW - pWidth) / 2));
                dst_x 
= 0;
            }
            
else
            {
                src_x 
= 0;
                dst_x 
= (float)(imageX + ((imageW - pWidth) / 2));
            }
            
if (pHeight > viewPortH)
            {
                src_y 
= (float)Math.Abs(imageY - Math.Abs((imageH - pHeight) / 2));
                dst_y 
= 0;
            }
            
else
            {
                src_y 
= 0;
                dst_y 
= (float)(imageY + ((imageH - pHeight) / 2));
            }


            
//Get Image viewed into the ViewPort
            image_p = ImageCopy(image_p, dst_x, dst_y, src_x, src_y, viewPortW, viewPortH, pWidth, pHeight);
            
//image_p.Save(context.Server.MapPath("test_viewport.jpg"));
            
//Get Selector Portion
            image_p = ImageCopy(image_p, 00, selectorX, selectorY, selectorW, selectorH, viewPortW, viewPortH);
            
string FileName = String.Format("test{0}.jpg", DateTime.Now.Ticks.ToString());
            image_p.Save(context.Server.MapPath(FileName));


            image_p.Dispose();
            img.Dispose();
            
//imgSelector.Dispose();
            context.Response.Write(FileName);
        }

        
private Bitmap ImageCopy(Bitmap srcBitmap, float dst_x, float dst_y, float src_x, float src_y, float dst_width, float dst_height, float src_width, float src_height)
        {
            
// Create the new bitmap and associated graphics object
            RectangleF SourceRec = new RectangleF(src_x, src_y, dst_width, dst_height);
            RectangleF DestRec 
= new RectangleF(dst_x, dst_y, dst_width, dst_height);
            Bitmap bmp 
= new Bitmap(Convert.ToInt32(dst_width),Convert.ToInt32(dst_height));
            Graphics g 
= Graphics.FromImage(bmp);
            
// Draw the specified section of the source bitmap to the new one
            g.DrawImage(srcBitmap, DestRec, SourceRec, GraphicsUnit.Pixel);
            
// Clean up
            g.Dispose();

            
// Return the bitmap
            return bmp;

        }

        
        
private Bitmap ResizeImage(Bitmap img, int width, int height)
        {
            Image.GetThumbnailImageAbort callback 
= new Image.GetThumbnailImageAbort(GetThumbAbort);
            
return (Bitmap)img.GetThumbnailImage(width, height,callback, System.IntPtr.Zero);

        }

        
public bool GetThumbAbort() {
            
return false;
        }

        
/// <summary>
        
/// method to rotate an image either clockwise or counter-clockwise
        
/// </summary>
        
/// <param name="img">the image to be rotated</param>
        
/// <param name="rotationAngle">the angle (in degrees).
        
/// NOTE: 
        
/// Positive values will rotate clockwise
        
/// negative values will rotate counter-clockwise
        
/// </param>
        
/// <returns></returns>
        private Image RotateImage(Bitmap img, double rotationAngle)
        {
            
//create an empty Bitmap image
            Bitmap bmp = new Bitmap(img.Width, img.Height);

            
//turn the Bitmap into a Graphics object
            Graphics gfx = Graphics.FromImage(bmp);

            
//now we set the rotation point to the center of our image
            gfx.TranslateTransform((float)bmp.Width / 2, (float)bmp.Height / 2);

            
//now rotate the image
            gfx.RotateTransform((float)rotationAngle);

            gfx.TranslateTransform(
-(float)bmp.Width / 2-(float)bmp.Height / 2);

            
//set the InterpolationMode to HighQualityBicubic so to ensure a high
            
//quality image once it is transformed to the specified size
            gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;

            
//now draw our new image onto the graphics object
            gfx.DrawImage(img, new Point(00));

            
//dispose of our Graphics object
            gfx.Dispose();

            
//return the image
            return bmp;
        }

        
public bool IsReusable
        {
            
get
            {
                
return false;
            }
        }
    }
}

 

 

 

 

代码
//----------------------------------------------------------------
// <copyright file="ImageHelp.cs" >
//    Copyright (c) www.Ftodo.com , All rights reserved.
//    author:brightwang E-Mail:brightwang1984@gmail.com  MyBlog:http://brightwang.cnblogs.com/
//    All rights reserved.
// </copyright>
//----------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
    
public class ImageHelp
    {
        
/// <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]);

            
//获取帧数(gif图片可能包含多帧,其它格式图片一般仅一帧)
            int count = gif.GetFrameCount(fd);

            
//以Jpeg格式保存各帧
            for (int i = 0; i < count; i++)
            {
                gif.SelectActiveFrame(fd, i);
                gif.Save(pSavedPath 
+ "\\frame_" + i + ".jpg", ImageFormat.Jpeg);
            }
        }

        
/**/
        
/// <summary>
        
/// 获取图片缩略图
        
/// </summary>
        
/// <param name="pPath">图片路径</param>
        
/// <param name="pSavePath">保存路径</param>
        
/// <param name="pWidth">缩略图宽度</param>
        
/// <param name="pHeight">缩略图高度</param>
        
/// <param name="pFormat">保存格式,通常可以是jpeg</param>
        public void GetSmaller(string pPath, string pSavedPath, int pWidth, int pHeight)
        {
            
string fileSaveUrl = pSavedPath + "\\smaller.jpg";

            
using (FileStream fs = new FileStream(pPath, FileMode.Open))
            {

                MakeSmallImg(fs, fileSaveUrl, pWidth, pHeight);
            }

        }


        
//按模版比例生成缩略图(以流的方式获取源文件)  
        
//生成缩略图函数  
        
//顺序参数:源图文件流、缩略图存放地址、模版宽、模版高  
        
//注:缩略图大小控制在模版区域内  
        public static void MakeSmallImg(System.IO.Stream fromFileStream, string fileSaveUrl, System.Double templateWidth, System.Double templateHeight)
        {
            
//从文件取得图片对象,并使用流中嵌入的颜色管理信息  
            System.Drawing.Image myImage = System.Drawing.Image.FromStream(fromFileStream, true);

            
//缩略图宽、高  
            System.Double newWidth = myImage.Width, newHeight = myImage.Height;
            
//宽大于模版的横图  
            if (myImage.Width > myImage.Height || myImage.Width == myImage.Height)
            {
                
if (myImage.Width > templateWidth)
                {
                    
//宽按模版,高按比例缩放  
                    newWidth = templateWidth;
                    newHeight 
= myImage.Height * (newWidth / myImage.Width);
                }
            }
            
//高大于模版的竖图  
            else
            {
                
if (myImage.Height > templateHeight)
                {
                    
//高按模版,宽按比例缩放  
                    newHeight = templateHeight;
                    newWidth 
= myImage.Width * (newHeight / myImage.Height);
                }
            }

            
//取得图片大小  
            System.Drawing.Size mySize = new Size((int)newWidth, (int)newHeight);
            
//新建一个bmp图片  
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(mySize.Width, mySize.Height);
            
//新建一个画板  
            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(Color.White);
            
//在指定位置画图  
            g.DrawImage(myImage, new System.Drawing.Rectangle(00, bitmap.Width, bitmap.Height),
            
new System.Drawing.Rectangle(00, myImage.Width, myImage.Height),
            System.Drawing.GraphicsUnit.Pixel);

            
///文字水印  
            System.Drawing.Graphics G = System.Drawing.Graphics.FromImage(bitmap);
            System.Drawing.Font f 
= new Font("Lucida Grande"6);
            System.Drawing.Brush b 
= new SolidBrush(Color.Gray);
            G.DrawString(
"Ftodo.com", f, b, 00);
            G.Dispose();

            
///图片水印  
            //System.Drawing.Image   copyImage   =   System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("pic/1.gif"));  
            
//Graphics   a   =   Graphics.FromImage(bitmap);  
            
//a.DrawImage(copyImage,   new   Rectangle(bitmap.Width-copyImage.Width,bitmap.Height-copyImage.Height,copyImage.Width,   copyImage.Height),0,0,   copyImage.Width,   copyImage.Height,   GraphicsUnit.Pixel);  

            
//copyImage.Dispose();  
            
//a.Dispose();  
            
//copyImage.Dispose();  

            
//保存缩略图  
            if (File.Exists(fileSaveUrl))
            {
                File.SetAttributes(fileSaveUrl, FileAttributes.Normal);
                File.Delete(fileSaveUrl);
            }

            bitmap.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);

            g.Dispose();
            myImage.Dispose();
            bitmap.Dispose();
        }



        
/**/
        
/// <summary>
        
/// 获取图片指定部分
        
/// </summary>
        
/// <param name="pPath">图片路径</param>
        
/// <param name="pSavePath">保存路径</param>
        
/// <param name="pPartStartPointX">目标图片开始绘制处的坐标X值(通常为)</param>
        
/// <param name="pPartStartPointY">目标图片开始绘制处的坐标Y值(通常为)</param>
        
/// <param name="pPartWidth">目标图片的宽度</param>
        
/// <param name="pPartHeight">目标图片的高度</param>
        
/// <param name="pOrigStartPointX">原始图片开始截取处的坐标X值</param>
        
/// <param name="pOrigStartPointY">原始图片开始截取处的坐标Y值</param>
        
/// <param name="pFormat">保存格式,通常可以是jpeg</param>
        public void GetPart(string pPath, string pSavedPath, int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY)
        {
            
string normalJpgPath = pSavedPath + "\\normal.jpg";

            
using (Image originalImg = Image.FromFile(pPath))
            {
                Bitmap partImg 
= new Bitmap(pPartWidth, pPartHeight);
                Graphics graphics 
= Graphics.FromImage(partImg);
                Rectangle destRect 
= new Rectangle(new Point(pPartStartPointX, pPartStartPointY), new Size(pPartWidth, pPartHeight));//目标位置
                Rectangle origRect = new Rectangle(new Point(pOrigStartPointX, pOrigStartPointY), new Size(pPartWidth, pPartHeight));//原图位置(默认从原图中截取的图片大小等于目标图片的大小)


                
///文字水印  
                System.Drawing.Graphics G = System.Drawing.Graphics.FromImage(partImg);
                System.Drawing.Font f 
= new Font("Lucida Grande"6);
                System.Drawing.Brush b 
= new SolidBrush(Color.Gray);
                G.Clear(Color.White);
                graphics.DrawImage(originalImg, destRect, origRect, GraphicsUnit.Pixel);
                G.DrawString(
"Ftodo.com", f, b, 00);
                G.Dispose();

                originalImg.Dispose();
                
if (File.Exists(normalJpgPath))
                {
                    File.SetAttributes(normalJpgPath, FileAttributes.Normal);
                    File.Delete(normalJpgPath);
                }
                partImg.Save(normalJpgPath, ImageFormat.Jpeg);
            }
        }
        
/**/
        
/// <summary>
        
/// 获取按比例缩放的图片指定部分
        
/// </summary>
        
/// <param name="pPath">图片路径</param>
        
/// <param name="pSavePath">保存路径</param>
        
/// <param name="pPartStartPointX">目标图片开始绘制处的坐标X值(通常为)</param>
        
/// <param name="pPartStartPointY">目标图片开始绘制处的坐标Y值(通常为)</param>
        
/// <param name="pPartWidth">目标图片的宽度</param>
        
/// <param name="pPartHeight">目标图片的高度</param>
        
/// <param name="pOrigStartPointX">原始图片开始截取处的坐标X值</param>
        
/// <param name="pOrigStartPointY">原始图片开始截取处的坐标Y值</param>
        
/// <param name="imageWidth">缩放后的宽度</param>
        
/// <param name="imageHeight">缩放后的高度</param>
        public void GetPart(string pPath, string pSavedPath, int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY, int imageWidth, int imageHeight)
        {
            
string normalJpgPath = pSavedPath + "\\normal.jpg";
            
using (Image originalImg = Image.FromFile(pPath))
            {
                
if (originalImg.Width == imageWidth && originalImg.Height == imageHeight)
                {
                    GetPart(pPath, pSavedPath, pPartStartPointX, pPartStartPointY, pPartWidth, pPartHeight, pOrigStartPointX, pOrigStartPointY);
                    
return;
                }

                Image.GetThumbnailImageAbort callback 
= new Image.GetThumbnailImageAbort(ThumbnailCallback);
                Image zoomImg 
= originalImg.GetThumbnailImage(imageWidth, imageHeight, callback, IntPtr.Zero);//缩放
                Bitmap partImg = new Bitmap(pPartWidth, pPartHeight);

                Graphics graphics 
= Graphics.FromImage(partImg);
                Rectangle destRect 
= new Rectangle(new Point(pPartStartPointX, pPartStartPointY), new Size(pPartWidth, pPartHeight));//目标位置
                Rectangle origRect = new Rectangle(new Point(pOrigStartPointX, pOrigStartPointY), new Size(pPartWidth, pPartHeight));//原图位置(默认从原图中截取的图片大小等于目标图片的大小)

                
///文字水印  
                System.Drawing.Graphics G = System.Drawing.Graphics.FromImage(partImg);
                System.Drawing.Font f 
= new Font("Lucida Grande"6);
                System.Drawing.Brush b 
= new SolidBrush(Color.Gray);
                G.Clear(Color.White);

                graphics.DrawImage(zoomImg, destRect, origRect, GraphicsUnit.Pixel);
                G.DrawString(
"Ftodo.com", f, b, 00);
                G.Dispose();

                originalImg.Dispose();
                
if (File.Exists(normalJpgPath))
                {
                    File.SetAttributes(normalJpgPath, FileAttributes.Normal);
                    File.Delete(normalJpgPath);
                }
                partImg.Save(normalJpgPath, ImageFormat.Jpeg);
            }
        }

        
/// <summary>
        
/// 获得图像高宽信息
        
/// </summary>
        
/// <param name="path"></param>
        
/// <returns></returns>
        public ImageInformation GetImageInfo(string path)
        {
            
using (Image image = Image.FromFile(path))
            {
                ImageInformation imageInfo
=new ImageInformation();
                imageInfo.Width 
= image.Width;
                imageInfo.Height 
= image.Height;
                
return imageInfo;
            }
        }
        
public bool ThumbnailCallback()
        {
            
return false;
        }

    }
    
public struct ImageInformation
    {
        
private int width;

        
public int Width
        {
            
get { return width; }
            
set { width = value; }
        }
        
private int height;

        
public int Height
        {
            
get { return height; }
            
set { height = value; }
        }
    }

 

 

posted on 2010-07-05 15:02  viste_happy  阅读(222)  评论(0)    收藏  举报