C# (winform) 图片缩略图的显示与缩略图另行保存功能

时间:2022-11-28 23:05:59
        private int NumOfFiles;
        private string[] imgName;//存储图片的路径
        private string[] imgExtension;
        /// <summary>
        /// 存储图片的路径
        /// </summary>
        private void ImagesInFolder()
        {
            FileInfo FInfo;
            // Fill the array (imgName) with all images in any folder 
            imgName = Directory.GetFiles(Application.StartupPath + @"\Images");
            // How many Picture files in this folder
            NumOfFiles = imgName.Length;
            imgExtension = new string[NumOfFiles];
            for (int i = 0; i < NumOfFiles; i++)
            {
                FInfo = new FileInfo(imgName[i]);
                imgExtension[i] = FInfo.Extension; // We need to know the Extension
            }
        }
        /// <summary>
        /// 缩略图函数调用
        /// </summary>
        private void SuoLueTu_HuoDe()
        {
            ImagesInFolder();
            for (int i = 0; i < NumOfFiles; i++)
            {
                string oldfile = imgName[i];
                string newfile = imgName[i];
                newfile = oldfile.Replace("Images\\", "image\\");
                int h = 500;
                int w = 500;
                ShowThumbnail(oldfile, newfile, h, w);
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            SuoLueTu_HuoDe();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="oldfile">需要生成缩略图的图片的路径</param>
        /// <param name="newfile">缩略图保存路径</param>
        /// <param name="h">图片高度</param>
        /// <param name="w">图片宽度</param>
        public  void ShowThumbnail(string oldfile, string newfile, int h, int w)
        {
            System.Drawing.Image img = System.Drawing.Image.FromFile(oldfile);
            System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            int oldh = img.Height;
            int oldw = img.Width;
            int newh, neww;
            double h1 = oldh * 1.0 / h;
            double w1 = oldw * 1.0 / w;
            double f = (h1 > w1) ? h1 : w1;
            if (f < 1.0)
            {
                newh = oldh;
                neww = oldw;
            }
            else
            {
                newh = (int)(oldh / f);
                neww = (int)(oldw / f);
            }
            System.Drawing.Image myThumbnail = img.GetThumbnailImage(neww, newh, myCallback, IntPtr.Zero);
            myThumbnail.Save(newfile, System.Drawing.Imaging.ImageFormat.Jpeg);
            pictureBox1.Image = Image.FromFile(newfile);
            img.Dispose();
            myThumbnail.Dispose();
        }
        private static bool ThumbnailCallback()
        {
            return false;
        }