C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# Winform图片预览器

C#使用Winform编写一个图片预览器管理

作者:搬砖的诗人Z

这篇文章主要为大家详细介绍了C#如何使用Winform编写一个通用图片预览器管理,包含滚轮放大缩小,剪切,下一页,方向变化等,需要的可以参考下

效果图

实现代码

using MetroFramework.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using XinShiYun_ScanReader.Common;
using XinShiYun_ScanReader.Model;

namespace XinShiYun_ScanReader
{
    public partial class ImageForm : MetroForm
    {
        /// <summary>
        /// 当前图片
        /// </summary>
        Image myImage;

        /// <summary>
        /// 图片集合,用于翻页浏览
        /// </summary>
        //public static List<Bitmap> myImages = new List<Bitmap>();

        List<ImageStateModel> ImageStateModels;

        /// <summary>
        /// 当前浏览的项
        /// </summary>
        int myIndex;

        /// <summary>
        /// 变更的图片
        /// </summary>
        public static List<int> ChangeImageIndexs = new List<int>();

        /// <summary>
        /// 剪切距离左边 默认左右剪切5px
        /// </summary>
        public int _cutLeft = 5;
        /// <summary>
        /// 剪切距离右边 默认左右剪切5px
        /// </summary>
        public int _cutRight = 5;
        /// <summary>
        /// 剪切距离上边
        /// </summary>
        public int _cutTop = 0;
        /// <summary>
        /// 剪切距离下边
        /// </summary>
        public int _cutBottom = 0;

        /// <summary>
        /// 缓存上次裁剪图片的地址
        /// </summary>
        public string BaseCutPath = Environment.CurrentDirectory + "\\CutPic\\";

        /// <summary>
        /// 缓存上次裁剪的图片名称
        /// </summary>
        public List<string> CutPathList = null;

        public ImageForm(List<ImageStateModel> imageStateModels, int index)
        {
            InitializeComponent();

            this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint, true);
            this.UpdateStyles();

            CreateCutPic();

            ImageStateModels = imageStateModels;
            string path = ImageStateModels[index].tempPicUrl;
            Image img = Image.FromFile(path);
            myImage = img;

            myIndex = index;
            this.MouseWheel += new MouseEventHandler(CandidateForm_MouseWheel);

            Init();
            ChangeImageIndexs = new List<int>();
        }

        /// <summary>
        /// 剪切图片存储
        /// </summary>
        private void CreateCutPic()
        {
            try
            {
                if (!Directory.Exists(BaseCutPath))
                {
                    Directory.CreateDirectory(BaseCutPath);
                }
                CutPathList = new List<string>();
                DirectoryInfo dir = new DirectoryInfo(BaseCutPath);
                FileSystemInfo[] fileinfo = dir.GetFiles();
                if (fileinfo == null)
                    return;
                foreach (FileSystemInfo i in fileinfo)
                {
                    File.Delete(i.FullName);      //删除指定文件
                }
            }
            catch (Exception ex)
            {
                log4netHelper.Error("---报错方法-ImageForm-CreateCutPic");
                log4netHelper.Error(ex.Message);
                log4netHelper.Error(ex.StackTrace);
                log4netHelper.Error("---end---");
            }

        }

        /// <summary>
        /// 添加剪切文件
        /// </summary>
        private void AddCutPic(Image img)
        {
            try
            {
                string name = Guid.NewGuid().ToString("N") +".jpg";
                string path = BaseCutPath + name;
                CutPathList.Add(path);
                img.Save(path);
            }
            catch (Exception ex)
            {
                log4netHelper.Error("---报错方法-ImageForm-AddCutPic");
                log4netHelper.Error(ex.Message);
                log4netHelper.Error(ex.StackTrace);
                log4netHelper.Error("---end---");
            }
        }

        /// <summary>
        /// 恢复上一步图片
        /// </summary>
        private void RevCutPic(string savePath)
        {
            if (CutPathList == null)
                return;
            int lastIndex = CutPathList.Count();//最后一步
            if (lastIndex <= 0)
                return;

            try
            {
                string path = CutPathList[lastIndex - 1];
                Image img = Image.FromFile(path);
                pic_Image.Image = img;
                myImage = img;
                img.Save(savePath, ImageFormat.Jpeg);
                CutPathList.RemoveAt(lastIndex - 1);
                pic_Image.Refresh();
                GC.Collect();
              
            }
            catch (Exception ex)
            {
                log4netHelper.Error("---报错方法-ImageForm-RevCutPic");
                log4netHelper.Error(ex.Message);
                log4netHelper.Error(ex.StackTrace);
                log4netHelper.Error("---end---");
            }



        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            try
            {
                string cutValue = ConfigHelper.ReadConfigPath("cut.txt");
                string[] destWidth = cutValue.Split(',');
                foreach (var item in destWidth)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        string[] width = item.Split(':');
                        if (width[0] == "L")
                        {
                            _cutLeft = Convert.ToInt32(width[1]);
                        }
                        if (width[0] == "R")
                        {
                            _cutRight = Convert.ToInt32(width[1]);
                        }
                        if (width[0] == "T")
                        {
                            _cutTop = Convert.ToInt32(width[1]);
                        }
                        if (width[0] == "B")
                        {
                            _cutBottom = Convert.ToInt32(width[1]);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log4netHelper.Error("---报错方法-ImageForm-Init");
                log4netHelper.Error(ex.Message);
                log4netHelper.Error(ex.StackTrace);
                log4netHelper.Error("---end---");
            }
        }

        private void ImageForm_Load(object sender, EventArgs e)
        {
            try
            {
                this.Width = 1000;
                this.Height = 1000;
                this.pic_Image.Dock = DockStyle.None;
                this.pic_Image.SizeMode = PictureBoxSizeMode.Zoom;
                this.pic_Image.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                pic_Image.Image = myImage;

                //pic_left.Location = new Point(this.Width / 2 - pic_left.Width, pic_left.Location.Y);
                //pic_right.Location = new Point(this.Width / 2 + pic_right.Width, pic_right.Location.Y);
                //pic_cut.Location = new Point(this.Width / 2 + pic_right.Width + pic_cut.Width + 10, pic_cut.Location.Y);
                panel_bottom.Location = new Point(this.Width / 2 - panel_bottom.Width / 2, panel_bottom.Location.Y);

                pic_goleft.Location = new Point(pic_goleft.Location.X, this.Height / 2);
                pic_goright.Location = new Point(pic_goright.Location.X, this.Height / 2);
            }
            catch (Exception ex)
            {
                log4netHelper.Error("---报错方法--ImageForm_Load");
                log4netHelper.Error(ex.Message);
                log4netHelper.Error(ex.StackTrace);
                log4netHelper.Error("---end---");
            }

        }


        /// <summary>
        /// 鼠标滚动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CandidateForm_MouseWheel(object sender, MouseEventArgs e)
        {
            try
            {
                this.pic_Image.Dock = DockStyle.None;
                this.pic_Image.SizeMode = PictureBoxSizeMode.Zoom;
                this.pic_Image.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                Size size = this.pic_Image.Size;
                size.Width += e.Delta;
                if (size.Width > pic_Image.Image.Width)
                {
                    pic_Image.Width = pic_Image.Image.Width;
                    pic_Image.Height = pic_Image.Image.Height;
                }
                //else if (size.Width * pic_Image.Image.Height / pic_Image.Image.Width < pic_Image.Parent.Height - 200)
                //{
                //    return;
                //}
                else
                {
                    pic_Image.Width = size.Width;
                    pic_Image.Height = size.Width * pic_Image.Image.Height / pic_Image.Image.Width;
                }
                pic_Image.Left = (pic_Image.Parent.Width - pic_Image.Width) / 2;
                pic_Image.Top = (pic_Image.Parent.Height - pic_Image.Height) / 2;
            }
            catch (Exception ex)
            {
                log4netHelper.Error("---报错方法--CandidateForm_MouseWheel");
                log4netHelper.Error(ex.Message);
                log4netHelper.Error(ex.StackTrace);
                log4netHelper.Error("---end---");
            }
        }


        private void panel_Image_Paint(object sender, PaintEventArgs e)
        {
        }

        private void metroButton1_Click(object sender, EventArgs e)
        {

        }

        private void metroButton2_Click(object sender, EventArgs e)
        {

        }

        bool canDrag = false;
        int pic_w = 0;
        int pic_h = 0;

        private void pic_Image_MouseDown(object sender, MouseEventArgs e)
        {
            pic_w = e.Location.X;
            pic_h = e.Location.Y;
            canDrag = true;
        }

        private void pic_Image_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                if (canDrag)
                {
                    pic_Image.Location = new Point(pic_Image.Left + e.X - pic_w, pic_Image.Top + e.Y - pic_h);
                }
            }
            catch (Exception ex)
            {
                log4netHelper.Error("---报错方法--pic_Image_MouseMove");
                log4netHelper.Error(ex.Message);
                log4netHelper.Error(ex.StackTrace);
                log4netHelper.Error("---end---");
            }

        }

        private void pic_Image_MouseUp(object sender, MouseEventArgs e)
        {
            canDrag = false;
        }

        private void pic_left_Click(object sender, EventArgs e)
        {
            try
            {
                Bitmap bitmap = (Bitmap)myImage;
                bitmap.RotateFlip(RotateFlipType.Rotate90FlipXY);

                if (!ChangeImageIndexs.Contains(myIndex))
                {
                    ChangeImageIndexs.Add(myIndex);
                }
                myImage = bitmap;
                this.pic_Image.Image = bitmap;
                pic_Image.Refresh();

                string path = ImageStateModels[myIndex].tempPicUrl;
                pic_Image.Image.Save(path, ImageFormat.Jpeg);
                GC.Collect();
            }
            catch (Exception ex)
            {
                log4netHelper.Error("---报错方法--pic_left_Click");
                log4netHelper.Error(ex.Message);
                log4netHelper.Error(ex.StackTrace);
                log4netHelper.Error("---end---");
            }
        }

        private void pic_right_Click(object sender, EventArgs e)
        {
            try
            {
                Bitmap bitmap = (Bitmap)myImage;
                bitmap.RotateFlip(RotateFlipType.Rotate270FlipXY);

                if (!ChangeImageIndexs.Contains(myIndex))
                {
                    ChangeImageIndexs.Add(myIndex);
                }
                myImage = bitmap;
                this.pic_Image.Image = myImage;
                pic_Image.Refresh();

                string path = ImageStateModels[myIndex].tempPicUrl;
                pic_Image.Image.Save(path, ImageFormat.Jpeg);
                GC.Collect();
            }
            catch (Exception ex)
            {
                log4netHelper.Error("---报错方法--pic_right_Click");
                log4netHelper.Error(ex.Message);
                log4netHelper.Error(ex.StackTrace);
                log4netHelper.Error("---end---");
            }

        }

        private void ImageForm_SizeChanged(object sender, EventArgs e)
        {
            try
            {
                panel_bottom.Location = new Point(this.Width / 2 - panel_bottom.Width / 2, this.Height - panel_bottom.Height - 20);

                pic_goleft.Location = new Point(pic_goleft.Location.X, this.Height / 2);
                pic_goright.Location = new Point(pic_goright.Location.X, this.Height / 2);

            }
            catch (Exception ex)
            {
                log4netHelper.Error("---报错方法--ImageForm_SizeChanged");
                log4netHelper.Error(ex.Message);
                log4netHelper.Error(ex.StackTrace);
                log4netHelper.Error("---end---");
            }
        }

        private void pic_goleft_Click(object sender, EventArgs e)
        {
            try
            {
                if (myIndex <= 0)
                    return;
                myIndex--;

                this.pic_Image.Dock = DockStyle.None;
                this.pic_Image.SizeMode = PictureBoxSizeMode.Zoom;
                this.pic_Image.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

                string path = ImageStateModels[myIndex].tempPicUrl;
                myImage = Image.FromFile(path);
                pic_Image.Image = myImage;
                GC.Collect();
            }
            catch (Exception ex)
            {
                log4netHelper.Error("---报错方法--pic_goleft_Click");
                log4netHelper.Error(ex.Message);
                log4netHelper.Error(ex.StackTrace);
                log4netHelper.Error("---end---");
            }

        }

        private void pic_goright_Click(object sender, EventArgs e)
        {
            try
            {
                if (myIndex >= ImageStateModels.Count() - 1)
                    return;
                myIndex++;

                this.pic_Image.Dock = DockStyle.None;
                this.pic_Image.SizeMode = PictureBoxSizeMode.Zoom;
                this.pic_Image.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

                string path = ImageStateModels[myIndex].tempPicUrl;
                myImage = Image.FromFile(path);
                //myImage = img;
                pic_Image.Image = myImage;
                GC.Collect();

            }
            catch (Exception ex)
            {
                log4netHelper.Error("---报错方法--pic_goright_Click");
                log4netHelper.Error(ex.Message);
                log4netHelper.Error(ex.StackTrace);
                log4netHelper.Error("---end---");
            }

        }

        /// <summary>
        /// 剪切图标2边,每次剪切5px 读取配置文件cut.txt 格式 L:50,R:50,T:0,B:0
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pic_cut_Click(object sender, EventArgs e)
        {
            try
            {
                if (myImage.Width <= _cutLeft + _cutRight)
                    return;
                if (myImage.Height <= _cutTop + _cutBottom)
                    return;

                AddCutPic(myImage);

                Bitmap img = ImageHelper.ImageCut(new Bitmap(myImage), _cutLeft, _cutTop, myImage.Width - _cutLeft - _cutRight, myImage.Height - _cutTop - _cutBottom);


                pic_Image.Image = img;
                pic_Image.Refresh();

                if (!ChangeImageIndexs.Contains(myIndex))
                {
                    ChangeImageIndexs.Add(myIndex);
                }
                myImage.Dispose();

                string path = ImageStateModels[myIndex].tempPicUrl;
                pic_Image.Image.Save(path, ImageFormat.Jpeg);

                myImage = img;
                GC.Collect();
            }
            catch (Exception ex)
            {
                log4netHelper.Error("---报错方法--pic_cut_Click");
                log4netHelper.Error(ex.Message);
                log4netHelper.Error(ex.StackTrace);
                log4netHelper.Error("---end---");
            }

        }

        private void pic_CutSelf_Click(object sender, EventArgs e)
        {
            try
            {
                CutSize cutSize = new CutSize();
                cutSize.ShowDialog();

                if (myImage.Width <= CutSize.Cut_Left + CutSize.Cut_Right)
                    return;
                if (myImage.Height <= CutSize.Cut_Top + CutSize.Cut_Bottom)
                    return;

                Bitmap img = ImageHelper.ImageCut(new Bitmap(myImage), CutSize.Cut_Left, CutSize.Cut_Top, myImage.Width - CutSize.Cut_Left - CutSize.Cut_Right, myImage.Height - CutSize.Cut_Top - CutSize.Cut_Bottom);

                pic_Image.Image = img;
                pic_Image.Refresh();

                if (!ChangeImageIndexs.Contains(myIndex))
                {
                    ChangeImageIndexs.Add(myIndex);
                }
                myImage.Dispose();

                string path = ImageStateModels[myIndex].tempPicUrl;
                pic_Image.Image.Save(path, ImageFormat.Jpeg);

                myImage = img;
                GC.Collect();
            }
            catch (Exception ex)
            {
                log4netHelper.Error("---报错方法--pic_cut_Click");
                log4netHelper.Error(ex.Message);
                log4netHelper.Error(ex.StackTrace);
                log4netHelper.Error("---end---");
            }
        }

        private void pic_cut_MouseHover(object sender, EventArgs e)
        {
            toolTip.SetToolTip(pic_cut, "自动裁剪图片");
        }

        private void pic_left_MouseHover(object sender, EventArgs e)
        {
            toolTip.SetToolTip(pic_left, "图片左旋转90度");
        }

        private void pic_right_MouseHover(object sender, EventArgs e)
        {
            toolTip.SetToolTip(pic_right, "图片右旋转90度");
        }

        private void pic_CutSelf_MouseHover(object sender, EventArgs e)
        {
            toolTip.SetToolTip(pic_CutSelf, "自定义裁剪图片");
        }

        private void ImageForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Dispose();
        }

        private void pic_return_MouseHover(object sender, EventArgs e)
        {
            toolTip.SetToolTip(pic_CutSelf, "返回裁剪上一步");
        }

        private void pic_return_Click(object sender, EventArgs e)
        {
            RevCutPic(ImageStateModels[myIndex].tempPicUrl);
        }
    }
}

到此这篇关于C#使用Winform编写一个图片预览器管理的文章就介绍到这了,更多相关C# Winform图片预览器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文