C#放缩、截取、合并图片并生成高质量新图的类

原文:C#放缩、截取、合并图片并生成高质量新图的类

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;

namespace Framework
{
public class ImageClass
{
        public Image ResourceImage;
        public int Width=0;
        public int Height=0;
        private int ImageWidth;
        private int ImageHeight;
        private ImageFormat imgFormat;
        public string ErrMessage;

        public ImageClass(string ImageFileName)
        {
            ResourceImage = Image.FromFile(ImageFileName);
            Width = ResourceImage.Width;
            Height = ResourceImage.Height;
            imgFormat = ResourceImage.RawFormat;
            ErrMessage = "";
        }
        public ImageClass(byte[] Img)
        {
            MemoryStream imgStream = new MemoryStream(Img);
            try
            {
                ResourceImage = System.Drawing.Image.FromStream(imgStream);
                Width = ResourceImage.Width;
                Height = ResourceImage.Height;
                imgFormat = ResourceImage.RawFormat;
            }
            catch (Exception ex)
            {
                ErrMessage = ex.ToString();
            }
        }

        public bool ThumbnailCallback()
        {
            return false;
        }

        public Image GetReducedImage(int Width, int Height)
        {
            try
            {
                Image ReducedImage;

                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);

                return ReducedImage;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return null;
            }
        }
        public bool GetReducedImage(int Width, int Height, string targetFilePath)
        {
            try
            {
                EncoderParameter p;
                EncoderParameters ps;

                ps = new EncoderParameters(1);

                p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L);
                ps.Param[0] = p;

                Image ReducedImage;

                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);

                Graphics g = System.Drawing.Graphics.FromImage(ReducedImage);
                // 设置画布的描绘质量
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                //清空画布并以透明背景色填充
                g.Clear(Color.Transparent);

                g.DrawImage(ResourceImage, new Rectangle(0, 0, Width, Height), new Rectangle(0, 0, ResourceImage.Width, ResourceImage.Height), GraphicsUnit.Pixel);

                ImageCodecInfo imgCodecInfo = GetCodecInfo(imgFormat.ToString());

                if (imgCodecInfo == null)
                {
                    ReducedImage.Save(targetFilePath, imgFormat);
                }
                else
                {
                    ReducedImage.Save(targetFilePath, GetCodecInfo(targetFilePath), ps);
                }

                ReducedImage.Dispose();
                g.Dispose();

                return true;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return false;
            }
        }

        public Image GetReducedImage(double Percent)
        {
            try
            {
                Image ReducedImage;

                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                ImageWidth = Convert.ToInt32(ResourceImage.Width * Percent);
                ImageHeight = Convert.ToInt32(ResourceImage.Height * Percent);

                ReducedImage = ResourceImage.GetThumbnailImage(ImageWidth, ImageHeight, callb, IntPtr.Zero);

                return ReducedImage;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return null;
            }
        }

        public bool GetReducedImage(double Percent, string targetFilePath)
        {
            try
            {
                EncoderParameter p;
                EncoderParameters ps;

                ps = new EncoderParameters(1);

                p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L);
                ps.Param[0] = p;
                Image ReducedImage;

                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                ImageWidth = Convert.ToInt32(ResourceImage.Width * Percent);
                ImageHeight = Convert.ToInt32(ResourceImage.Height * Percent);

                ReducedImage = ResourceImage.GetThumbnailImage(ImageWidth, ImageHeight, callb, IntPtr.Zero);

                Graphics g = System.Drawing.Graphics.FromImage(ReducedImage);

                // 设置画布的描绘质量
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                //清空画布并以透明背景色填充
                g.Clear(Color.Transparent);

                g.DrawImage(ResourceImage, new Rectangle(0, 0, ImageWidth, ImageHeight), new Rectangle(0, 0, ResourceImage.Width, ResourceImage.Height), GraphicsUnit.Pixel);

                ImageCodecInfo imgCodecInfo = GetCodecInfo(imgFormat.ToString());

                if (imgCodecInfo == null)
                {
                    ReducedImage.Save(targetFilePath, imgFormat);
                }
                else
                {
                    ReducedImage.Save(targetFilePath, GetCodecInfo(targetFilePath), ps);
                }

                ReducedImage.Dispose();
                g.Dispose();

                return true;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return false;
            }
        }

        public bool GetReducedImage(string targetFilePath)
        {
            try
            {
                ResourceImage.Save(targetFilePath, ImageHelper.GetFormat(targetFilePath));

                return true;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return false;
            }
        }

        public bool CaptureImg(string targetFilePath, int width, int height, int spaceX, int spaceY)
        {
            try
            {
                //载入底图  
                int x = 0;   //截取X坐标  
                int y = 0;   //截取Y坐标  
                //原图宽与生成图片宽   之差      
                //当小于0(即原图宽小于要生成的图)时,新图宽度为较小者   即原图宽度   X坐标则为0    
                //当大于0(即原图宽大于要生成的图)时,新图宽度为设置值   即width         X坐标则为   sX与spaceX之间较小者  
                //Y方向同理  
                int sX = ResourceImage.Width - width;
                int sY = ResourceImage.Height - height;
                if (sX > 0)
                {
                    x = sX > spaceX ? spaceX : sX;
                }
                else
                {
                    width = ResourceImage.Width;
                }
                if (sY > 0)
                {
                    y = sY > spaceY ? spaceY : sY;
                }
                else
                {
                    height = ResourceImage.Height;
                }

                EncoderParameter p;
                EncoderParameters ps;

                ps = new EncoderParameters(1);
                p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L);
                ps.Param[0] = p;

                Bitmap ReducedImage = new Bitmap(width, height);
                Graphics g = System.Drawing.Graphics.FromImage(ReducedImage);

                // 设置画布的描绘质量
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                //清空画布并以透明背景色填充
                g.Clear(Color.Transparent);

                g.DrawImage(ResourceImage, 0, 0, new Rectangle(x, y, width, height), GraphicsUnit.Pixel);

                ImageCodecInfo imgCodecInfo = GetCodecInfo(imgFormat.ToString());

                if (imgCodecInfo == null)
                {
                    ReducedImage.Save(targetFilePath, imgFormat);
                }
                else
                {
                    ReducedImage.Save(targetFilePath, GetCodecInfo(targetFilePath), ps);
                }

                //释放资源  
                //saveImage.Dispose();
                ReducedImage.Dispose();
                g.Dispose();
            }
            catch (Exception ex)
            {
                ErrMessage = ex.Message;
                return false;
            }
            return true;
        }

        public bool MergerImg(string targetFilePath, int ImgWidth, int ImgHeight)
        {
            try
            {
                EncoderParameter p;
                EncoderParameters ps;

                ps = new EncoderParameters(1);
                p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L);
                ps.Param[0] = p;

                //创建要显示的图片对象,根据参数的个数设置宽度
                Bitmap ReducedImage = new Bitmap(ImgWidth, ImgHeight);
                Graphics g = Graphics.FromImage(ReducedImage);

                // 设置画布的描绘质量
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                //清空画布并以透明背景色填充
                g.Clear(Color.Transparent);

                int StartX = (ImgWidth - this.Width) / 2;
                int StartY = (ImgHeight - this.Height) / 2;

                g.DrawImage(ResourceImage, StartX, StartY, this.Width, this.Height);

                //保存图象  
                ImageCodecInfo imgCodecInfo = GetCodecInfo(imgFormat.ToString());
                if (imgCodecInfo == null)
                {
                    ReducedImage.Save(targetFilePath, imgFormat);
                }
                else
                {
                    ReducedImage.Save(targetFilePath, GetCodecInfo(targetFilePath), ps);
                }

                //释放资源  
                ReducedImage.Dispose();
                g.Dispose();
            }
            catch (Exception ex)
            {
                ErrMessage = ex.Message;
                return false;
            }
            return true;
        }

        public bool MergerImg(string targetFilePath, System.Drawing.Image image, int ImgWidth, int ImgHeight)
        {
            try
            {
                EncoderParameter p;
                EncoderParameters ps;

                ps = new EncoderParameters(1);
                p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L);
                ps.Param[0] = p;

                //创建要显示的图片对象,根据参数的个数设置宽度
                Bitmap ReducedImage = new Bitmap(ImgWidth, ImgHeight);
                Graphics g = Graphics.FromImage(ReducedImage);

                // 设置画布的描绘质量
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                //清空画布并以透明背景色填充
                g.Clear(Color.Transparent);

                int StartX = (ImgWidth - image.Width) / 2;
                int StartY = (ImgHeight - image.Height) / 2;

                g.DrawImage(image, StartX, StartY, image.Width, image.Height);
                //保存图象  
                ImageCodecInfo imgCodecInfo = GetCodecInfo(imgFormat.ToString());

                if (imgCodecInfo == null)
                {
                    ReducedImage.Save(targetFilePath, imgFormat);
                }
                else
                {
                    ReducedImage.Save(targetFilePath, GetCodecInfo(targetFilePath), ps);
                }

                //释放资源  
                ReducedImage.Dispose();
                g.Dispose();
            }
            catch (Exception ex)
            {
                ErrMessage = ex.Message;
                return false;
            }
            return true;
        }

        //返回图片解码器信息用于jpg图片
        private ImageCodecInfo GetCodecInfo(string str)
        {
            string ext = str.Substring(str.LastIndexOf(".") + 1);
            string mimeType = "";
            switch (ext.ToLower())
            {
                case "jpe":
                case "jpg":
                case "jpeg":
                    mimeType = "image/jpeg";
                    break;
                case "bmp":
                    mimeType = "image/bmp";
                    break;
                case "png":
                    mimeType = "image/png";
                    break;
                case "tif":
                case "tiff":
                    mimeType = "image/tiff";
                    break;
                default:
                    mimeType = "image/jpeg";
                    break;
            }
            ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo ici in CodecInfo)
            {
                if (ici.MimeType == mimeType) return ici;
            }
            return null;
        }

        public void Dispose()
        {
            ResourceImage.Dispose();
        }
}
}

 

 

 

 

 

 

 

 

因为tiff格式的图片,一张可以有多页,所以现在有需求如下:

1. 可以随便添加一张图片(tiff,jpeg,png等格式)的图片到指定的tiff图片中去

2. 可以从tiff图片中抽取出任意张图片出来,可以保存为(tiff,png,jpeg等格式)

 

1   Image img = Image.FromFile("C:\\1.tif");
2   Guid guid = (Guid)img.FrameDimensionsList.GetValue(0);
3   FrameDimension dimension = new FrameDimension(guid);
4   int totalPage = img.GetFrameCount(dimension);
5
6   this.statusBar1.Text = "共"+totalPage+"页";
7
8   for(int i=0;i<totalPage;i++)
9   {
10    img.SelectActiveFrame(dimension,i);
11                img.Save("C:\\Gif"+i+".gif",System.Drawing.Imaging.ImageFormat.Gif);
12   }
13

时间: 2024-12-05 11:50:48

C#放缩、截取、合并图片并生成高质量新图的类的相关文章

C# 生成高质量缩略图程序—终极算法_实用技巧

先看代码: using System; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; /**//// <summary> ///  /// **生成高质量缩略图程序** ///  ///  File: GenerateThumbnail.cs ///  ///  Author: 周振兴 (Zxjay 飘遥) ///  ///  E-Mail: tda7264@163.com

ASP.NET生成高质量缩略图通用函数(c#代码)

asp.net|函数|缩略图 在网站开发时,生成缩略图是一个非常常见和实用的功能.以前在asp里只能借助com组件实现,现在在.net里可以利用框架的强大的类库轻松实现.下面帖出完整的代码(带详细注释),参考了网上的一些文章及.net sdk相关内容.QQROOM网络家园的图片上传用到了所有的4种生成方式.         /// <summary>        /// 生成缩略图        /// </summary>        /// <param name=&

asp.net生成高质量缩略图通用函数(c#代码),支持多种生成方式

asp.net|函数|缩略图 在网站开发时,生成缩略图是一个非常常见和实用的功能.以前在asp里只能借助com组件实现,现在在.net里可以利用框架的强大的类库轻松实现.下面帖出完整的代码(带详细注释),参考了网上的一些文章及.net sdk相关内容.QQROOM网络家园的图片上传用到了所有的4种生成方式.         /**//// <summary>        /// 生成缩略图        /// </summary>        /// <param na

ASP.NET生成高质量缩略图通用函数

在网站开发时,生成缩略图是一个非常常见和实用的功能.以前在asp里只能借助com组件实现,现在在.net里可以利用框架的强大的类库轻松实现.下面帖出完整的代码(带详细注释),参考了网上的一些文章及.net sdk相关内容.QQROOM网络家园的图片上传用到了所有的4种生成方式. /// <summary> /// 生成缩略图 /// </summary> /// <param name="originalImagePath">源图路径(物理路径)&l

争夺战最新攻势:YouTube推大量高质量新内容

谷歌公司旗下的视频分享网站YouTube近日专门为高质量内容开辟出一块新区域,提供数百部完整版的电影.数千集完整版的电视剧.不过,此举只是YouTube与对手Hulu的争夺战中的一波最新攻势. YouTube和Hulu分别占据着网络视频业务的两个领域,YouTube通过用户上传的视频片断建立了庞大的受众群,而Hulu主要提供有一定长度的专业制作内容,比如电视节目和电影等.不过这两家公司正在向对方的地盘进军,例如争夺可以带来最大广告收入的视频编程方法.YouTube发言人说,公司有志成为一个提供从

Highcharts结合PhantomJS在服务端生成高质量的图表图片

项目背景 最近忙着给部门开发一套交互式的报表系统,来替换原有的静态报表系统. 老系统是基于dotnetCHARTING开发的,dotnetCHARTING的优势是图表类型丰富,接口调用简单,使用时只 需绑定数据源即可(指定连接字符和sql语句,简单的配置一下就能出图),支持生成静态图表图片:缺点就 是生成好的图是图片,传到了前台就失去了交互性(当然它还提供了一个jsCharting,不过感觉交互性做的还 是不够好),再有就是这东东是收费的呀,用的话需要折腾破解版本. 我最终选择了Highchar

PHP用GD库生成高质量的缩略图片

以下是PHP源代码(ResizeImage.php). 复制代码 代码如下: <?php $FILENAME="image.thumb"; // 生成图片的宽度 $RESIZEWIDTH=400; // 生成图片的高度 $RESIZEHEIGHT=400; function ResizeImage($im,$maxwidth,$maxheight,$name){ $width = imagesx($im); $height = imagesy($im); if(($maxwidt

ASP.NET 生成高质量缩略图代码

asp.net|缩略图  private static Size NewSize(int maxWidth, int maxHeight, int width, int height)  {   double w = 0.0;   double h = 0.0;   double sw = Convert.ToDouble(width);   double sh = Convert.ToDouble(height);   double mw = Convert.ToDouble(maxWidth

PHP用GD库生成高质量的缩略图片_php技巧

以下是PHP源代码(ResizeImage.php). 复制代码 代码如下: <?php $FILENAME="image.thumb"; // 生成图片的宽度 $RESIZEWIDTH=400; // 生成图片的高度 $RESIZEHEIGHT=400; function ResizeImage($im,$maxwidth,$maxheight,$name){ $width = imagesx($im); $height = imagesy($im); if(($maxwidt