程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> 批量修改圖片以及加水印

批量修改圖片以及加水印

編輯:C#基礎知識

效果如下:

public void plAddSY(object sender, EventArgs e)
        { 
            //C#遍歷指定文件夾中的所有文件
            DirectoryInfo TheFolder = new DirectoryInfo(Request.PhysicalApplicationPath + "images\\Product");
            //DirectoryInfo TheFolder = new DirectoryInfo("D:\\WebFiles\\Newb2c\\images\\Product");
            //遍歷文件夾
            foreach (DirectoryInfo NextFolderfirst in TheFolder.GetDirectories())
            {
                foreach (DirectoryInfo NextFolder in NextFolderfirst.GetDirectories())
                {
                    if (NextFolder.Name == "-2" || NextFolder.Name == "-1" || NextFolder.Name == "0" || NextFolder.Name == "1" || NextFolder.Name == "2" || NextFolder.Name == "3" || NextFolder.Name == "IsBoolImg")
                    {
                        //遍歷文件
                        foreach (FileInfo NextFile in NextFolder.GetFiles())
                        {
                            if (NextFile.Name.Contains("SY800SY"))
                            {
                                File.Delete(NextFile.FullName);
                            }
                            else if (!NextFile.Name.Contains("SY.") && !NextFile.Name.Contains("SY800."))
                            {
                                if (!NextFile.Name.Contains("47-47_")&&!NextFile.Name.Contains("50-50_")&&!NextFile.Name.Contains("80-80_")&&!NextFile.Name.Contains("100-100_")&&!NextFile.Name.Contains("120-120_")&&!NextFile.Name.Contains("140-140_")&&!NextFile.Name.Contains("160-160_")&&!NextFile.Name.Contains("380-380_"))
                                {
                                    MarkWater(NextFile.FullName, Request.PhysicalApplicationPath + "images\\" + "logo-back.png");
                                    //MarkWater(NextFile.FullName, "D:\\WebFiles\\Newb2c\\images\\" + "logo-back.png");
                                }
                            }
                        }
                    }
                }
            }
        }

        /// <summary>   
        /// 給圖片上水印   
        /// </summary>   
        /// <param name="filePath">原圖片地址</param>   
        /// <param name="waterFile">水印圖片地址</param>   
        public void MarkWater(string filePath, string waterFile)
        {
            int i = filePath.LastIndexOf(".");
            string ex = filePath.Substring(i, filePath.Length - i);
            if (string.Compare(ex, ".gif", true) == 0)
            {
                return;
            }
            int newp = filePath.LastIndexOf(".");
            string newpo = filePath.Substring(0, newp);
            string newpolast = filePath.Substring(newp + 1);
            string newlastimg = newpo + "SY800" + "." + newpolast;
            BitmapHelper.MakeThumbnail(filePath, newlastimg, 800, 800, "DB", "JPG");
            string ModifyImagePath = newlastimg;
            int lucencyPercent = 25;
            System.Drawing.Image modifyImage = null;
            System.Drawing.Image drawedImage = null;
            Graphics g = null;
            try
            {
                modifyImage = System.Drawing.Image.FromFile(ModifyImagePath, true);
                drawedImage = System.Drawing.Image.FromFile(waterFile, true);
                g = Graphics.FromImage(modifyImage);
                int x = (modifyImage.Width - drawedImage.Width)/2;
                int y = (modifyImage.Height - drawedImage.Height)/2;
                float[][] matrixItems ={   
                new float[] {1, 0, 0, 0, 0},   
                new float[] {0, 1, 0, 0, 0},   
                new float[] {0, 0, 1, 0, 0},   
                new float[] {0, 0, 0, (float)lucencyPercent/100f, 0},   
                new float[] {0, 0, 0, 0, 1}};

                ColorMatrix colorMatrix = new ColorMatrix(matrixItems);
                ImageAttributes imgAttr = new ImageAttributes();
                imgAttr.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                g.DrawImage(drawedImage, new Rectangle(x, y, drawedImage.Width, drawedImage.Height), 10, 10, drawedImage.Width, drawedImage.Height, GraphicsUnit.Pixel, imgAttr);
                string[] allowImageType = { ".jpg", ".gif", ".png", ".bmp", ".tiff", ".wmf", ".ico" };
                FileInfo fi = new FileInfo(ModifyImagePath);
                ImageFormat imageType = ImageFormat.Gif;
                switch (fi.Extension.ToLower())
                {
                    case ".jpg": imageType = ImageFormat.Jpeg; break;
                    case ".gif": imageType = ImageFormat.Gif; break;
                    case ".png": imageType = ImageFormat.Png; break;
                    case ".bmp": imageType = ImageFormat.Bmp; break;
                    case ".tif": imageType = ImageFormat.Tiff; break;
                    case ".wmf": imageType = ImageFormat.Wmf; break;
                    case ".ico": imageType = ImageFormat.Icon; break;
                    default: break;
                }
                MemoryStream ms = new MemoryStream();
                modifyImage.Save(ms, imageType);
                byte[] imgData = ms.ToArray();
                modifyImage.Dispose();
                drawedImage.Dispose();
                g.Dispose();
                FileStream fs = null;
                fs = new FileStream(ModifyImagePath.Replace("SY800.", "SY."), FileMode.Create, FileAccess.Write);
                if (fs != null)
                {
                    fs.Write(imgData, 0, imgData.Length);
                    fs.Close();
                }
            }
            finally
            {
                try
                {
                    drawedImage.Dispose();
                    modifyImage.Dispose();
                    g.Dispose();
                }
                catch
                {
                }
            }
        }

 

 

public class BitmapHelper
    {
        /// <summary>
        /// 生成縮略圖
        /// </summary>
        /// <param name="originalImagePath">源圖路徑(物理路徑)</param>
        /// <param name="thumbnailPath">縮略圖路徑(物理路徑)</param>
        /// <param name="width">縮略圖寬度</param>
        /// <param name="height">縮略圖高度</param>
        /// <param name="mode">生成縮略圖的方式</param>
        /// <param name="type">縮略圖的圖片類型</param> 
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode, string type)
        {
            Image originalImage = Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高寬縮放(可能變形) 
                    break;
                case "W"://指定寬,高按比例 
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高,寬按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高寬裁減(不變形) 
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                case "DB"://等比縮放(不變形,如果高大按高,寬大按寬縮放) 
                    if ((double)originalImage.Width / (double)towidth < (double)originalImage.Height / (double)toheight)
                    {
                        toheight = height;
                        towidth = originalImage.Width * height / originalImage.Height;
                    }
                    else
                    {
                        towidth = width;
                        toheight = originalImage.Height * width / originalImage.Width;
                    }
                    break;
                default:
                    break;
            }

            //新建一個bmp圖片
            Image bitmap = new Bitmap(towidth, toheight);

            //新建一個畫板
            Graphics g = Graphics.FromImage(bitmap);

            //設置高質量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //設置高質量,低速度呈現平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

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

            //在指定位置並且按指定大小繪制原圖片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
            new Rectangle(x, y, ow, oh),
            GraphicsUnit.Pixel);

            try
            {
                //保存縮略圖
                if (type.ToUpper() == "JPG")
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                if (type.ToUpper() == "BMP")
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp);
                }
                if (type.ToUpper() == "GIF")
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif);
                }
                if (type.ToUpper() == "PNG")
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png);
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }}

  

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved