zoukankan      html  css  js  c++  java
  • .NET图片处理

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Diagnostics;

    namespace ImageCompressTool
    {
        class Program
        {
            static void Main(string[] args)
            {
                DateTime start = DateTime.Now;

                ImageDealTool dealtool = new ImageDealTool();
                //获得exe文件所在的路径(包含了exe文件的名称)
                string filelocation = Process.GetCurrentProcess().MainModule.FileName;
                //获得当前执行的exe文件的名称
                string exefilename =Process.GetCurrentProcess().MainModule.ModuleName;
                //要获取子字符串的长度
                int index =filelocation.IndexOf(exefilename);
                //获得当前的文件夹路径,以//结尾,下面直接放文件夹即可
                string aimlocation = filelocation.Substring(0, index);
                //读取待处理图片的名称
                DirectoryInfo info = new DirectoryInfo(aimlocation);
                //在当前文件夹下获得图片名称,这里必须做成一个集合,因为图片会有很多张
                FileInfo[] filesimages = info.GetFiles("*.jpg", SearchOption.TopDirectoryOnly);
                //遍历循环获得每一张图片
                foreach (FileInfo fileinfoimage in filesimages)
                {
                    //获得每一张图片的名称
                    string foundimagename = fileinfoimage.Name;
                    //建立一个与图片同名称的文件夹
                    //获得需要建立文件夹的名称

                    //处理图片的名称,从后往前寻找字符,只要后面发现. 就可以确定文件夹的名称,这样可以防止bug
                    int foundpointlocation = foundimagename.LastIndexOf('.');
                    string foundedfoldername = foundimagename.Substring(0, foundpointlocation);
                   //此时我们遍历一次就为一个文件夹进行命名
                    //在当前的文件夹下面创建一个文件夹

                    //首先获得新建文件夹的路径
                    string cutimagepathpath = aimlocation + foundedfoldername;
                    //创建新的文件夹用以保存图片
                    Directory.CreateDirectory(cutimagepathpath);
                    DirectoryInfo infoinfo = new DirectoryInfo(cutimagepathpath);
                    //在对应的创建好的文件夹下面存放切好的图片和压缩好的图片
                    //ImageDealTool dealtool = new ImageDealTool();
                   
                    //1.压缩图片,比较节省时间
                    //设置压缩图片的名称,这里都是固定的
                    string compreesedimagenamename = "snapshot.jpg";
                    //执行压缩操作
                    //观察压缩操作传递的参数
                    //dealtool.ImageCompress(aimlocation+imagenamename, aimlocation+dealimagename, "jpg");
                    dealtool.ImageCompress(foundimagename, infoinfo + "\\" + compreesedimagenamename, "jpg");
                    //imgtool.ImageCompress(@"D:\张开发\百花谷场景(高质量).jpg", @"D:\新建文件夹 (2)\hds.jpg", "jpg");
                    //2.切割图片
                    //观察切割操作需要传递的参数
                    //cutimg.Cut(@"D:\张开发\百花谷场景(高质量).jpg", 200, 200, @"D:", "jpg");
                    //切图操作将切割好的图片保存时传递的参数比较特殊,需要注意
                    dealtool.Cut(foundimagename, 200, 200, infoinfo + "\\", "jpg");
                }
                DateTime end = DateTime.Now;
                TimeSpan timewaste = end - start;
                Console.WriteLine("计算耗时:"+timewaste.TotalSeconds.ToString());
                //string imagenamename = filesimage[0].Name;
                //设置压缩完成之后文件夹的名称
                //string dealimagename = string.Format("{0}" + imagenamename, "被压缩的");
                //切割图片的操作,切割完成之后放入exe所在文件夹的子文件夹

                //设置切割完毕之后图片存放的文件夹路径,在当前的文件夹下新建一个文件夹
                //文件夹名称
                //string foldernamename = "cutimage";
               
                //获得图片要存到哪个文件夹下的路径
               // string aimdiretorypath = infoinfo + "\\";

                //dealtool.Cut(aimlocation + imagenamename, 200, 200, aimdiretorypath, "jpg");
                //cutimg.Cut(@"D:\张开发\百花谷场景(高质量).jpg", 200, 200, @"D:", "jpg");
                //压缩图片的操作
                //dealtool.ImageCompress(aimlocation+imagenamename, aimlocation+dealimagename, "jpg");
               
                //imgtool.ImageCompress(@"D:\张开发\百花谷场景(高质量).jpg", @"D:\新建文件夹 (2)\hds.jpg", "jpg");


                //Console.ReadLine();

                //Console.WriteLine("欢迎进入图片转换系统,请选择要执行的操作:选择的操作代号为:1,2,3   以下为1,2,3操作的解释说明");
                //Console.WriteLine("1.将指定像素的图片转换成指定200*200像素的图片");
                //Console.WriteLine("2.将指定将指定像素的图片转换成最大像素(宽或高其一均可)为500pixel的图片");
                //Console.WriteLine("3.退出系统");
                //string operselection = Console.ReadLine();
                //switch (operselection.ToLower())
                //{
                //  case "1":
                //找到调用函数
                //cutimg.Cut(@"D:\张开发\百花谷场景(高质量).jpg", 200, 200, @"D:", "jpg");
                //    Console.WriteLine("欢迎进入图片切割系统,输入每一项后按回车键");
                //  Console.WriteLine("输入要处理图片所在的位置:");
                //string inputpath = Console.ReadLine();
                //Console.WriteLine("输入被处理图片的宽度:输入200即可");
                //string inputwidth = Console.ReadLine();
                //Console.WriteLine("输入被处理图片的高度:输入200即可");
                //string inputheight = Console.ReadLine();
                //Console.WriteLine("输入图片要保存的位置:");
                //string outputpath = Console.ReadLine();
                //Console.WriteLine("输入图片切割后保存的格式,支持输入jpg,png,bmp,gif格式");
                //string savetype = Console.ReadLine();
                //参数输入完毕,我们进行方法调用
                //ImageDealTool dealtool = new ImageDealTool();
                //获得exe文件所在的路径
                //string inputpath = "";

                //dealtool.Cut(inputpath, Convert.ToInt32(inputwidth),
    //Convert.ToInt32(inputheight), outputpath, savetype);
                //    Console.WriteLine("请等待");
                //    break;
                //case "2":
                //    Console.WriteLine("欢迎进入图片压缩系统,输入每一项后按回车键");
                //    //找到调用函数
                //    //imgtool.ImageCompress(@"D:\张开发\百花谷场景(高质量).jpg", @"D:\新建文件夹 (2)\hds.jpg", "jpg");
                //    Console.WriteLine("输入要处理图片所在的位置:");
                //    string imagelocation = Console.ReadLine();
                //    Console.WriteLine("输入图片要保存的位置:");
                //    string outputlocation = Console.ReadLine();
                //    Console.WriteLine("输入图片切割后保存的格式,支持输入jpg,png,bmp,gif格式");
                //    string imagetype = Console.ReadLine();
                //参数输入完毕,我们进行方法调用
                //ImageDealTool dealtool1 = new ImageDealTool();
                //dealtool1.ImageCompress(imagelocation, outputlocation, imagetype);
                //Console.WriteLine("请等待");
                //break;
                //case "3":
                //    break;
                // }
                //string imageurl = Console.ReadLine();
                //string createurl = Console.ReadLine();
                //imgtool.ImageCompress(@"D:\张开发\百花谷场景(高质量).jpg", @"D:\新建文件夹 (2)\hds.jpg", "jpg");
            }
        }
        public class ImageDealTool
        {
            //操作需求可能改变,开发出面向对象的代码


            /// <summary>
            /// 图片等比例压缩方法
            /// </summary>
            /// <param name="url">图片所在的文件夹</param>
            /// <param name="savepath">压缩后图片所在的文件夹</param>
            /// <param name="fileExt">压缩后图片的保存格式,例如jpg,gif等</param>
            public void ImageCompress(string url, string savepath, string fileExt)
            {
                //读取一张图片
                Bitmap myImage = new Bitmap(url);
                //原来图片的宽和高(以像素为单位)
                int widthPre = myImage.Width;
                int heightPre = myImage.Height;
                //设置压缩以后图片的宽和高
                int widthNex = 1;
                int heightNex = 1;
                //计算压缩后图片的宽和高
                if (widthPre == heightPre)
                {
                    //如果宽和高相等,就设置成500px
                    widthNex = 500;
                    heightNex = 500;
                }
                else if (widthPre > heightPre)
                {
                    //如果宽大于高,则将较大的设置成为500px
                    widthNex = 500;
                    //较小的数按比例去计算
                    heightNex = ((widthNex * heightPre) / widthPre);
                }
                else
                {
                    heightNex = 500;
                    widthNex = ((widthPre * heightNex) / heightPre);
                }
                //取得图片大小
                Size mySize = new Size(widthNex, heightNex);
                //新建一张bmp图片
                System.Drawing.Image bitmap = new System.Drawing.Bitmap(mySize.Width, mySize.Height);
                //新建一张画板
                Graphics g = 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(0, 0, bitmap.Width, bitmap.Height),
                new System.Drawing.Rectangle(0, 0, myImage.Width, myImage.Height),
                System.Drawing.GraphicsUnit.Pixel);
                //画图完毕后可以设置保存图片的格式
                ImageFormat format = ImageFormat.Jpeg;
                switch (fileExt.ToLower())
                {
                    case "jpg":
                        format = ImageFormat.Jpeg;
                        break;
                    case "png":
                        format = ImageFormat.Png;
                        break;
                    case "bmp":
                        format = ImageFormat.Bmp;
                        break;
                    case "gif":
                        format = ImageFormat.Gif;
                        break;
                    default:
                        break;
                }
                //保存缩略图
                bitmap.Save(savepath, System.Drawing.Imaging.ImageFormat.Jpeg);
                g.Dispose();
                myImage.Dispose();
                bitmap.Dispose();
            }
            /// <summary>
            /// 图片按指定像素切割成字图片的方法
            /// </summary>
            /// <param name="url">要切割图片的存放位置</param>
            /// <param name="width">切割后图片的宽度</param>
            /// <param name="height">切割后图片的高度</param>
            /// <param name="savepath">切割后图片的保存路径</param>
            /// <param name="fileExt">切割后图片的保存格式</param>
            public void Cut(string url, int width, int height, string savepath, string fileExt)
            {
                //这里需要考虑像素不能整除的情况,需要将剩下的像素点进行补齐

                //创建一张图片
                Bitmap bitmap = new Bitmap(url);
                //纵向能切成多少张
                Decimal MaxRow = Math.Ceiling((Decimal)bitmap.Height / height);
                //Decimal MaxColumn = Math.Ceiling((Decimal)bitmap.Height / height);
                //算出纵向切割完成之后最后一张图片剩余的像素点,对处理结果进行求于操作
                //精确到一像素
                int Columnleft = (int)(bitmap.Height % height);
                //横向能切成多少张
                Decimal MaxColumn = Math.Ceiling((Decimal)bitmap.Width / width);
                //Decimal MaxRow = Math.Ceiling((Decimal)bitmap.Width / width);
                //算出横向切割完成之后剩余的像素点
                int Rowleft = (int)(bitmap.Width % width);

                //外层两个循环是为了图片的命名
                for (Decimal i = 0; i < MaxRow; i++)
                {
                    for (Decimal j = 0; j < MaxColumn; j++)
                    {
                        //设置文件名称
                        string filename = j.ToString() + "_" + i.ToString() + "." + fileExt;
                        //切割成小图片的宽度和高度,参数为用户输入的宽度和高度
                        Bitmap bmp = new Bitmap(width, height);

                        //画图这里是核心操作

                        //画图
                        for (int offsetX = 0; offsetX < width; offsetX++)
                        {
                            for (int offsetY = 0; offsetY < height; offsetY++)
                            {
                                //如果没有超越边界
                                if (((j * width + offsetX) < bitmap.Width) && ((i * height + offsetY) < bitmap.Height))
                                {
                                    //这一步是核心的操作
                                    //按照每一像素绘制图片
                                    bmp.SetPixel(offsetX, offsetY, bitmap.GetPixel((int)(j * width + offsetX), (int)(i * height + offsetY)));
                                }
                            }
                        }


                        //Graphics g = Graphics.FromImage(bmp);
                        //加水印
                        //g.DrawString(
                        //  "a", new Font("黑体", 20), new SolidBrush(Color.FromArgb(70, Color.WhiteSmoke)), 60, height / 2);

                        ImageFormat format = ImageFormat.Jpeg;
                        switch (fileExt.ToLower())
                        {
                            case "jpg":
                                format = ImageFormat.Jpeg;
                                break;
                            case "png":
                                format = ImageFormat.Png;
                                break;
                            case "bmp":
                                format = ImageFormat.Bmp;
                                break;
                            case "gif":
                                format = ImageFormat.Gif;
                                break;
                            default:
                                break;
                        }
                        bmp.Save(savepath + "\\" + filename, format);
                        bmp.Dispose();
                    }
                }
            }

        }
    }

  • 相关阅读:
    私藏实用免费软件备份
    JavaScript03-基本概念一
    JavaScript02-js使用
    JavaScript第一回-来龙去脉
    初读时间简史的零星杂想
    读《死亡诗社》
    读《生死疲劳》
    js的预解析
    浏览器事件捕获冒泡以及阻止冒泡
    http初探
  • 原文地址:https://www.cnblogs.com/lovehappy/p/1954322.html
Copyright © 2011-2022 走看看