wpf绘制图片查看器

这几天一直在研究如何用wpf制作类似于windows自带的图片查看器,网上也有些类似的,但功能单一,和windows自带的图片查看器有很大区别,于是自己做了个图片查看器,功能大部分健全,首先是绘制图片展示界面,如图

,下面分别是放大、全屏、左转、右转、恢复原图、下一张以及删除按钮,上面是一个打开文件按钮。首先是绘制界面,这里不多说了,会wpf的,这个界面其实是很简单的。界面绘制好后,我们需要建立一个获取选中图片的文件目录类,如下:

 public class ImageFile
    {
        private string ImageFolderPath;
        public ImageFile(string ImageFolderPath)
        {
            this.ImageFolderPath = ImageFolderPath;
        }
         /// <summary>         
         /// 获取选中文件夹下的所有图片
        /// </summary>
        public List<string> GetImgInfo
        {
            get
           {
                 List<string> imgs = new List<string>();
                 string[] ft = { ".GIF", ".PNG", ".BMP", ".JPG", ".JPEG" };//图片格式
                 DirectoryInfo dt = new DirectoryInfo(ImageFolderPath);
                 FileInfo[] fis = dt.GetFiles();
                if (fis == null)
                {
                    return null;
                }
                else
                {
                    foreach (FileInfo f in fis)
                    {
                        if (ft.Contains<string>(f.Extension.ToUpper()))
                        {
                            imgs.Add(f.FullName);
                        }
                    }
                }
                return imgs;
            }
        }
     }

当点击某一图片进行显示时,我们可以获取该图片目录下的所有图片,以便点击下一张按钮时可以连续的显示图片。

对于图片的放大,这里有一个放大按钮,连续点击可以放大到限定的倍数,这里也可以用鼠标的滚轮来控制,向上滚动是放大,向下滚动是缩小,缩小只能缩小到原图大小。这里对于图片的操作是用矢量图来操作的,以便保持图片不失真。图片的旋转,这个比较好做,只是简单的旋转问题,这里我会附上所有的代码供大家参考

主界面前台逻辑

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="690" Width="980" WindowStyle="None" AllowsTransparency="True" Background="Transparent" Loaded="Window_Loaded" WindowStartupLocation="CenterScreen">
    <Border Name="topbd" Height="670" Width="960" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,10,0,0" MouseLeftButtonDown="topbd_MouseLeftButtonDown">
        <Border.Effect>
            <DropShadowEffect Color="Black" BlurRadius="15" ShadowDepth="0" Opacity="0.5"/>
        </Border.Effect>
        <Grid Height="670" Width="960" Background="White" Name="NormalGd" Visibility="Visible">
            <Grid.RowDefinitions>
                <RowDefinition Height="30"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <Grid Grid.Row="0" Height="30" Background="#3ea1e5">
                <Button  VerticalAlignment="Top" Width="58" Height="28" HorizontalAlignment="Left" Margin="5,0,0,0" Name="openbtn" Click="openbtn_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" Background="#3ea1e5" CornerRadius="3">
                                <TextBlock Text="打开文件" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" FontFamily="微软雅黑" FontSize="12"/>
                            </Border>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter TargetName="closeellipse" Property="Background"  Value="#64bceb"/>
                                </Trigger>
                                <Trigger Property="IsPressed" Value="True">
                                    <Setter TargetName="closeellipse" Property="Background" Value="#3ea1e5"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Height="28" Width="28" HorizontalAlignment="Right" VerticalAlignment="Top" Click="Button_Click" Margin="0,0,5,0">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Canvas  Canvas.Left="0" Canvas.Top="0" Width="28" Height="28" VerticalAlignment="Center" HorizontalAlignment="Center" Background="Transparent">
                                <Ellipse Name="closeellipse" Height="28" Width="28" Fill="#3ea1e5"/>
                                <Path x:Name="ph1" Fill="#ffffff" Data="M15.25 14l4.3-4.29L18.3 8.46 14 12.76 9.71 8.46 8.44 9.71 12.76 14 8.44 18.29l1.27 1.27L14 15.25l4.3 4.3 1.27-1.27Z">
                                    <Path.RenderTransform>
                                        <TranslateTransform X="0" Y="0"/>
                                    </Path.RenderTransform>
                                </Path>
                            </Canvas>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter TargetName="closeellipse" Property="Fill"  Value="#e14315"/>
                                </Trigger>
                                <Trigger Property="IsPressed" Value="True">
                                    <Setter TargetName="closeellipse" Property="Fill" Value="#c02e03"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
            </Grid>
            <Grid Grid.Row="1" HorizontalAlignment="Center" >
                <Grid.RowDefinitions>
                    <RowDefinition Height="590"/>
                    <RowDefinition Height="50"/>
                </Grid.RowDefinitions>
                <Border Grid.Row="0" Width="800" Height="540" Background="White" ClipToBounds="True" HorizontalAlignment="Center" VerticalAlignment="Bottom" BorderBrush="#494949" BorderThickness="1" CornerRadius="3">
                    <!--放置矢量图资源-->
                    <Canvas Background="White" MouseWheel="Canvas_MouseWheel" MouseEnter="Canvas_MouseEnter">
                        <Image Name="ScanImg" Stretch="None" Canvas.Left="308" Canvas.Top="208">
                            <Image.RenderTransform>
                                <MatrixTransform></MatrixTransform>
                            </Image.RenderTransform>
                        </Image>
                    </Canvas>
                </Border>
                <Button Name="enlarge" Height="30" Width="30" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="140,0,0,0" Click="enlarge_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" CornerRadius="3">
                                <Border.Background>
                                    <ImageBrush ImageSource="Images/放大.jpg"/>
                                </Border.Background>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Name="fullscreen" Height="30" Width="30" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="220,0,0,0" Click="fullscreen_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" CornerRadius="3">
                                <Border.Background>
                                    <ImageBrush ImageSource="Images/全屏.jpg"/>
                                </Border.Background>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Name="left" Height="30" Width="30" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="320,0,0,0" Click="left_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" CornerRadius="3">
                                <Border.Background>
                                    <ImageBrush ImageSource="Images/左旋.png"/>
                                </Border.Background>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Name="right" Height="30" Width="30" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="420,0,0,0" Click="right_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" CornerRadius="3">
                                <Border.Background>
                                    <ImageBrush ImageSource="Images/右旋.png"/>
                                </Border.Background>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Name="resite" Height="30" Width="30" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="520,0,0,0" Click="resite_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" CornerRadius="3">
                                <Border.Background>
                                    <ImageBrush ImageSource="Images/还原放大.png"/>
                                </Border.Background>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Name="next" Height="30" Width="30" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="620,0,0,0" Click="next_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" CornerRadius="3">
                                <Border.Background>
                                    <ImageBrush ImageSource="Images/next.png"/>
                                </Border.Background>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Name="delete" Height="30" Width="30" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="720,0,0,0" Click="delete_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" CornerRadius="3">
                                <Border.Background>
                                    <ImageBrush ImageSource="Images/删除.png"/>
                                </Border.Background>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
            </Grid>
        </Grid>
    </Border>
</Window>

主界面后台代码

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Forms;

namespace WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public string path = string.Empty;
        public string photoPath = string.Empty;
        public string pressedid = string.Empty;
        public string _id = string.Empty;
        public int _height;
        public int _width;
        public int height;
        public int width;
        public string pressedImgpath = string.Empty;
        List<FrameworkElement> _elementlist = new List<System.Windows.FrameworkElement>();
        private double _nScales = 5;  // 图片最大放大倍数,默认5倍
        FrameworkElement _element = new FrameworkElement();
        public double primaryHeight;
        public double primaryWidth;
        public string lastpressedid;
        const int MinMemorySize = 1024;
        List<string> imgs = new List<string>();//图片列表
        List<string> AllImgs = new List<string>();//图片列表
        int currentView = 0;
        double pressed = 1;
        public string ImagePath = string.Empty;
        public MainWindow()
        {
            InitializeComponent();
            path = System.AppDomain.CurrentDomain.BaseDirectory;
            if (!path.EndsWith("\\"))
            {
                path = path + "\\";
            }
        }
        /// <summary>
        /// 按钮动作
        /// </summary>
        /// <param name="ev"></param>
        private void BtnEvent()
        {
            if (AllImgs.Count > 0)
            {
                if (currentView >= AllImgs.Count) { currentView = 0; }
                BitmapImage img = GetPictureImage(AllImgs[currentView]);
                ScanImg.Source = img;
                ScanImg.Width = img.Width;
                ScanImg.Height = img.Height;
                string title = AllImgs[currentView].Substring(AllImgs[currentView].LastIndexOf('\\') + 1);
                this.Title = title;
                currentView++;
            }
        }
        /// <summary>
        /// 获取指定路径的图片信息
        /// </summary>
        /// <param name="path">图片全路径</param>
        /// <returns></returns>
        private BitmapImage GetPictureImage(string path)
        {
            if (!File.Exists(path))
            {
                //CommonLog.log.Info("进入方法GetPictureImage(string path)中,图片路径不存在!参数path为:" + path);
                return null;
            }

            FileStream fs = null;
            BitmapImage bmp = null;

            try
            {
                fs = new FileStream(path, FileMode.Open);
                byte[] byData = new byte[fs.Length];
                fs.Read(byData, 0, byData.Length);
                fs.Close();

                bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(byData);
                bmp.EndInit();
            }
            catch (Exception ex)
            {
                bmp = null;
                //CommonLog.log.Error(string.Format("进入方法GetPictureImage(string path)中,获取图片信息失败,原因:{0},详细描述:{1},图片路径:{2}",
                //                                                   ex.Message, ex.StackTrace, path));
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }

            return bmp;
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string[] commandLineArgs = Environment.GetCommandLineArgs();//

            if (commandLineArgs.Length > 1)
            {
                string currentOpenedFile = Environment.GetCommandLineArgs()[1];//当前被打开的图片路径
                string _p = currentOpenedFile.Substring(0, currentOpenedFile.LastIndexOf('\\'));
                ImageFile hp = new ImageFile(_p);  //被打开的图片所在的目录
                imgs = hp.GetImgInfo;
                imgs.Remove(commandLineArgs[1]);
                AllImgs.Clear();
                AllImgs.Add(commandLineArgs[1]);
                for (int i = 0; i < imgs.Count; i++)
                {
                    AllImgs.Add(imgs[i]);
                }
                BtnEvent();
                ScanImg.SetValue(Canvas.LeftProperty,(400 - ScanImg.Width/2));
                ScanImg.SetValue(Canvas.TopProperty, (270 - ScanImg.Height/ 2));
               

            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ((MatrixTransform)ScanImg.RenderTransform).Matrix = _originMatrix;
            this.Close();
        }

        private void enlarge_Click(object sender, RoutedEventArgs e)
        {
            pressed = pressed + 0.1;
            //描述鼠标滑轮滚动
            if (_elementlist != null && _elementlist.Count >= 100)
            {
                _elementlist.RemoveAt(0);
            }

            FrameworkElement element = (FrameworkElement)ScanImg;
            element.Opacity = 1;
            Matrix matrix = ((MatrixTransform)element.RenderTransform).Matrix;

            System.Windows.Point center = new System.Windows.Point(element.ActualWidth / 2, element.ActualHeight / 2);

            if (center.X < 20 || center.Y < 20)
            {
                element = _elementlist[50];
                matrix = ((MatrixTransform)element.RenderTransform).Matrix;
                center = new System.Windows.Point(element.ActualWidth / 2, element.ActualHeight / 2);
            }
            center = matrix.Transform(center);
            if (matrix.M11 * pressed >= _nScales || matrix.M22 * pressed >= _nScales)
            {
                matrix.M11 = _nScales;
                matrix.M22 = _nScales;
                return;
            }
            matrix.ScaleAt(pressed, pressed, center.X, center.Y);
            //matrix.RotateAt(e.DeltaManipulation.Rotation, center.X, center.Y);
            //matrix.Translate(e.DeltaManipulation.Translation.X, e.DeltaManipulation.Translation.Y);
            ((MatrixTransform)element.RenderTransform).Matrix = matrix;
            _element = element;
            _elementlist.Add(element);
        }
        /// <summary>
        /// 图片全屏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fullscreen_Click(object sender, RoutedEventArgs e)
        {
            DoubleAnimation daV = new DoubleAnimation(1, 0, new Duration(TimeSpan.FromSeconds(1)));
            daV.Completed += daV_Completed;
            this.BeginAnimation(UIElement.OpacityProperty, daV);
           
        }
        private void daV_Completed(object sender, EventArgs e)
        {
            FullImg fl = new WpfApplication1.FullImg(ScanImg.Source);
            fl.Owner = this;
            fl.QuitKey_show = new FullImg.QuitKey(QuitKey_show);
            fl.ShowDialog();
            DoubleAnimation daV1 = new DoubleAnimation(0, 1, new Duration(TimeSpan.FromSeconds(1)));
            fl.BeginAnimation(UIElement.OpacityProperty, daV1);
        }
        private void QuitKey_show()
        {
            DoubleAnimation daV1 = new DoubleAnimation(0, 1, new Duration(TimeSpan.FromSeconds(1)));
            this.BeginAnimation(UIElement.OpacityProperty, daV1);
        }
        private void left_Click(object sender, RoutedEventArgs e)
        {
            System.Drawing.Image myBitmap = Rotate.GetSourceImg(AllImgs[currentView-1]);
            int angel = 90;
            Rotate.RotateImg(myBitmap, angel, AllImgs[currentView-1]);
            angel += 90;
            if (angel == 360)
            {
                angel = 90;
            }
            BitmapImage img = GetPictureImage(AllImgs[currentView-1]);
            ScanImg.Source = img;
            ScanImg.Width = img.Width;
            ScanImg.Height = img.Height;
            myBitmap.Dispose();
        }

        private void right_Click(object sender, RoutedEventArgs e)
        {
            System.Drawing.Image myBitmap = Rotate.GetSourceImg(AllImgs[currentView-1]);
            int angel = -90;
            Rotate.RotateImg(myBitmap, angel, AllImgs[currentView-1]);
            angel -= 90;
            if (angel == -360)
            {
                angel = -90;
            }
            BitmapImage img = GetPictureImage(AllImgs[currentView-1]);
            ScanImg.Source = img;
            ScanImg.Width = img.Width;
            ScanImg.Height = img.Height;
            myBitmap.Dispose();
        }

        private void topbd_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }
        /// <summary>
        /// 归位原图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void resite_Click(object sender, RoutedEventArgs e)
        {
            ((MatrixTransform)ScanImg.RenderTransform).Matrix = _originMatrix;
        }
        private Matrix _originMatrix;   // 初始矩阵
        private void Canvas_MouseWheel(object sender, MouseWheelEventArgs e)
        {
         
            double val;   //描述鼠标滑轮滚动
            if (_elementlist != null && _elementlist.Count >= 100)
            {
                _elementlist.RemoveAt(0);
            }

            FrameworkElement element = (FrameworkElement)ScanImg;
            element.Opacity = 1;
            Matrix matrix = ((MatrixTransform)element.RenderTransform).Matrix;

            System.Windows.Point center = new System.Windows.Point(element.ActualWidth / 2, element.ActualHeight / 2);
          
            if (center.X < 20 || center.Y < 20)
            {
                element = _elementlist[50];
                matrix = ((MatrixTransform)element.RenderTransform).Matrix;
                center = new System.Windows.Point(element.ActualWidth / 2, element.ActualHeight / 2);
            }
            center = matrix.Transform(center);

            // 不可以对原始图片进行缩小,即:缩放比例倍数不可小于1
            // if ((matrix.M11 * System.Math.Abs(val)) <= 1.0 || (matrix.M22 * System.Math.Abs(val)) <= 1.0)
            if ((double)e.Delta >= 0)
            {
                val = (double)e.Delta / 100;
                // 缩放最大不能大于5倍
                if (matrix.M11 * val >= _nScales || matrix.M22 * val >= _nScales)
                {
                    matrix.M11 = _nScales;
                    matrix.M22 = _nScales;
                    return;
                }
                matrix.ScaleAt(val, val, center.X, center.Y);
            }
            else
            {
               
                if (matrix.M11 * 0.7 <= 1 || matrix.M22 * 0.7 <= 1)
                {
                    ((MatrixTransform)ScanImg.RenderTransform).Matrix = _originMatrix;
                    return;
                }
                matrix.ScaleAt(0.7, 0.7, center.X, center.Y);
            }
            //matrix.RotateAt(e.DeltaManipulation.Rotation, center.X, center.Y);
            //matrix.Translate(e.DeltaManipulation.Translation.X, e.DeltaManipulation.Translation.Y);
            ((MatrixTransform)element.RenderTransform).Matrix = matrix;
            _element = element;
            _elementlist.Add(element);
        }

        private void Canvas_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            FrameworkElement element = (FrameworkElement)ScanImg;
            primaryHeight = element.ActualHeight;
            primaryWidth = element.ActualWidth;
        }
        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void delete_Click(object sender, RoutedEventArgs e)
        {
            BitmapImage img = GetPictureImage(AllImgs[currentView-1]);

            string[] file = pressedImgpath.Split('\\');
            string filename = file[file.Length - 1];
            int index = filename.IndexOf('.');
            int length = filename.Length;
            string type = filename.Substring(index + 1, (length - index - 1));
            type = type + "图像";

            System.Drawing.Image myBitmap = Rotate.GetSourceImg(AllImgs[currentView-1]);
            int height = myBitmap.Height;
            int width = myBitmap.Width;
            string wh = width.ToString() + "×" + height.ToString();
            myBitmap.Dispose();

            FileInfo f = new FileInfo(AllImgs[currentView-1]);
            double size = f.Length;

            size = size / (double)MinMemorySize;
            string imgsize = GetCapacity(size);
            showtip st = new showtip(img, filename, type, wh, imgsize);
            st.Owner = this;
            st.ShowDialog();
            if (st.DialogResult == true)
            {
                if (f.Exists)
                {
                    ScanImg.Source = null;
                    f.Delete();
                }
            }
        }
       
        /// <summary>
        /// 将获得的容量KB转化为MB或GB
        /// </summary>
        /// <param name="_num"></param>
        /// <returns></returns>
        public string GetCapacity(double inputNum)
        {
            string num = string.Empty;
            double Dnum;
            double _num = (inputNum < 0) ? 0 : inputNum;
            if (_num < MinMemorySize)
            {
                _num = Math.Round(_num, MidpointRounding.AwayFromZero);
                num = _num.ToString() + "KB";
            }
            else if (_num < (MinMemorySize * MinMemorySize))
            {
                Dnum = (double)_num / (double)MinMemorySize;
                Dnum = Math.Round(Dnum, MidpointRounding.AwayFromZero);
                num = Dnum.ToString() + "MB";
            }
            else
            {
                Dnum = (double)_num / (double)(MinMemorySize * MinMemorySize);
                Dnum = Math.Round(Dnum, MidpointRounding.AwayFromZero);
                num = Dnum.ToString() + "GB";
            }

            return num;
        }
        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openbtn_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog m_Dialog = new System.Windows.Forms.OpenFileDialog();
            m_Dialog.Multiselect = true;
            m_Dialog.Title = "请选择文件";
            m_Dialog.Filter = "所有文件(*.*)|*.*";
            DialogResult result = m_Dialog.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            ImagePath = m_Dialog.FileName;
            if (!string.IsNullOrEmpty(ImagePath))
            {
                string _p = ImagePath.Substring(0, ImagePath.LastIndexOf('\\'));
                ImageFile hp = new ImageFile(_p);  //被打开的图片所在的目录
                imgs = hp.GetImgInfo;
                imgs.Remove(ImagePath);
                AllImgs.Clear();
                AllImgs.Add(ImagePath);
                for (int i = 0; i < imgs.Count; i++)
                {
                    AllImgs.Add(imgs[i]);
                }
                BtnEvent();
            }
        }

        private void next_Click(object sender, RoutedEventArgs e)
        {
            if (AllImgs.Count < 2)
            {
                return;
            }
            BtnEvent();
        }
    }

}
提示界面

<Window x:Class="WpfApplication1.showtip"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="showtip" Height="220" Width="370" WindowStyle="None" AllowsTransparency="True" WindowStartupLocation="CenterScreen" Background="Transparent" Loaded="Window_Loaded">
    <Border Name="topbd" Height="200" Width="350" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,10,0,0">
        <Border.Effect>
            <DropShadowEffect Color="Black" BlurRadius="15" ShadowDepth="0" Opacity="0.5"/>
        </Border.Effect>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="30"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <StackPanel Grid.Row="0" Background="#3ea1e5">
                <Button Height="30" Width="30" Grid.Row="0" HorizontalAlignment="Right" VerticalAlignment="Top" Click="Button_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Canvas  Canvas.Left="0" Canvas.Top="0" Width="28" Height="28" VerticalAlignment="Center" HorizontalAlignment="Center" Background="Transparent">
                                <Ellipse Name="closeellipse" Height="28" Width="28" Fill="#3ea1e5"/>
                                <Path x:Name="ph1" Fill="#ffffff" Data="M15.25 14l4.3-4.29L18.3 8.46 14 12.76 9.71 8.46 8.44 9.71 12.76 14 8.44 18.29l1.27 1.27L14 15.25l4.3 4.3 1.27-1.27Z">
                                    <Path.RenderTransform>
                                        <TranslateTransform X="0" Y="0"/>
                                    </Path.RenderTransform>
                                </Path>
                            </Canvas>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter TargetName="closeellipse" Property="Fill"  Value="#e14315"/>
                                </Trigger>
                                <Trigger Property="IsPressed" Value="True">
                                    <Setter TargetName="closeellipse" Property="Fill" Value="#c02e03"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
            </StackPanel>
            <Grid Grid.Row="1" Background="White">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="50"/>
                </Grid.RowDefinitions>
                <Grid Grid.Row="0">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="32"/>
                        <RowDefinition Height="20"/>
                        <RowDefinition Height="20"/>
                        <RowDefinition Height="20"/>
                        <RowDefinition Height="20"/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="50"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <Image Grid.Row="0" Grid.Column="0" Source="Images/回收站.png" Height="30" Width="30" Stretch="UniformToFill"  HorizontalAlignment="Center" VerticalAlignment="Bottom" />
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="确实要把此文件放入回收站吗?" FontFamily="微软雅黑" FontSize="12" Foreground="#494949" HorizontalAlignment="Left" VerticalAlignment="Center"/>
                    <Image Name="deleteImg" Source="Images/背景色1.png" Grid.Column="1" Grid.Row="1" Grid.RowSpan="4" HorizontalAlignment="Left" VerticalAlignment="Top"/>
                    <TextBlock Grid.Column="1" Grid.Row="1" Name="ImgName"  FontFamily="微软雅黑" FontSize="12" Foreground="#494949" Text="背景色1.png"/>
                    <TextBlock Grid.Column="1" Grid.Row="2" Name="ImgType"  FontFamily="微软雅黑" FontSize="12" Foreground="#494949" Text="背景色1.png"/>
                    <TextBlock Grid.Column="1" Grid.Row="3" Name="ImgWH"  FontFamily="微软雅黑" FontSize="12" Foreground="#494949" Text="背景色1.png"/>
                    <TextBlock Grid.Column="1" Grid.Row="4" Name="ImgSize"  FontFamily="微软雅黑" FontSize="12" Foreground="#494949" Text="背景色1.png"/>
                </Grid>
                <Button Grid.Row="1" Width="50" Height="20" FocusVisualStyle="{x:Null}" BorderThickness="0" Name="OkBtn" Click="OkBtn_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" Background="#3ea1e5" CornerRadius="3">
                                <TextBlock Text="确定" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" FontFamily="微软雅黑" FontSize="12"/>
                            </Border>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter TargetName="closeellipse" Property="Background"  Value="#64bceb"/>
                                </Trigger>
                                <Trigger Property="IsPressed" Value="True">
                                    <Setter TargetName="closeellipse" Property="Background" Value="#3ea1e5"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button Grid.Row="1" Width="50" Height="20" Margin="200,0,0,0" FocusVisualStyle="{x:Null}" BorderThickness="0" Name="CancelBtn" Click="CancelBtn_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Name="closeellipse" Background="#3ea1e5" CornerRadius="3">
                                <TextBlock Text="取消" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" FontFamily="微软雅黑" FontSize="12"/>
                            </Border>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter TargetName="closeellipse" Property="Background"  Value="#64bceb"/>
                                </Trigger>
                                <Trigger Property="IsPressed" Value="True">
                                    <Setter TargetName="closeellipse" Property="Background" Value="#3ea1e5"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
            </Grid>
        </Grid>
    </Border>
</Window>
后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// showtip.xaml 的交互逻辑
    /// </summary>
    public partial class showtip : Window
    {
        public showtip()
        {
            InitializeComponent();
        }
        public showtip( BitmapImage img,string filename,string filetype, string fileWH,string fileSize)
        {
            InitializeComponent();
            deleteImg.Source = img;
            ImgName.Text = filename;
            ImgType.Text = "项目类型:" + filetype;
            ImgWH.Text = "尺寸:" + fileWH;
            ImgSize.Text = "大小:" + fileSize;
        }

        private void OkBtn_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            this.Close();
        }

        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            FrameworkElement element = (FrameworkElement)deleteImg;
            ImgName.Margin = new Thickness(element.ActualWidth+5,0,0,0);
            ImgType.Margin = new Thickness(element.ActualWidth+5, 0, 0, 0);
            ImgWH.Margin = new Thickness(element.ActualWidth+5, 0, 0, 0);
            ImgSize.Margin = new Thickness(element.ActualWidth+5, 0, 0, 0);
        }
    }
}
图片旋转相应方法

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApplication1
{
   public class Rotate
    {
        /// <summary> 

        /// 以逆时针为方向对图像进行旋转 

        /// </summary> 

        /// <param name="b">位图流</param> 

        /// <param name="angle">旋转角度[0,360](前台给的)</param> 

        /// <returns></returns> 

        public static Image RotateImg(Image b, int angle,string savepath)

        {
            if (angle >= 0)
            {
                angle = angle % 360;
            }
            else
            {
                angle = (angle + 360) % 360;
            }
          


            //弧度转换 

            double radian = angle * Math.PI / 180.0;

            double cos = Math.Cos(radian);

            double sin = Math.Sin(radian);


            //原图的宽和高 

            int w = b.Width;

            int h = b.Height;

            int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));

            int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));


            //目标位图 

            Bitmap dsImage = new Bitmap(W, H);

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

            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;

            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;


            //计算偏移量 

            Point Offset = new Point((W - w) / 2, (H - h) / 2);


            //构造图像显示区域:让图像的中心与窗口的中心点一致 

            Rectangle rect = new Rectangle(Offset.X, Offset.Y, w, h);

            Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);


            g.TranslateTransform(center.X, center.Y);

            g.RotateTransform(360 - angle);


            //恢复图像在水平和垂直方向的平移 

            g.TranslateTransform(-center.X, -center.Y);

            g.DrawImage(b, rect);


            //重至绘图的所有变换 

            g.ResetTransform();


            g.Save();

            g.Dispose();

            //保存旋转后的图片 

            b.Dispose();

            dsImage.Save(savepath, System.Drawing.Imaging.ImageFormat.Png);

            return dsImage;

        }


        //public Image RotateImg(string filename, int angle)

        //{

        //    return RotateImg(GetSourceImg(filename), angle);

        //}


        public static Image GetSourceImg(string filename)

        {

            Image img;


            img = Bitmap.FromFile(filename);


            return img;

        }
        /// <summary>
        /// Resize图片
        /// </summary>
        /// <param name="bmp">原始Bitmap</param>
        /// <param name="newW">新的宽度</param>
        /// <param name="newH">新的高度</param>
        /// <param name="Mode">保留着,暂时未用</param>
        /// <returns>处理以后的图片</returns>
        public static Image KiResizeImage(Image bmp, int newW, int newH,string savepath)
        {
            try
            {
                Bitmap b = new Bitmap(newW, newH);
                Graphics g = Graphics.FromImage(b);
                // 插值算法的质量
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                g.Dispose();
                bmp.Dispose();
                b.Save(savepath, System.Drawing.Imaging.ImageFormat.Png);
                return b;
            }
            catch
            {
                return null;
            }
        }
        public static Image pictureProcess(Image sourceImage, int targetWidth, int targetHeight,string path)
        {
            int width;//图片最终的宽
            int height;//图片最终的高
            try
            {
                System.Drawing.Imaging.ImageFormat format = sourceImage.RawFormat;
                Bitmap targetPicture = new Bitmap(targetWidth, targetHeight);
                Graphics g = Graphics.FromImage(targetPicture);
                g.Clear(Color.White);

                //计算缩放图片的大小
                if (sourceImage.Width > targetWidth && sourceImage.Height <= targetHeight)
                {
                    width = targetWidth;
                    height = (width * sourceImage.Height) / sourceImage.Width;
                }
                else if (sourceImage.Width <= targetWidth && sourceImage.Height > targetHeight)
                {
                    height = targetHeight;
                    width = (height * sourceImage.Width) / sourceImage.Height;
                }
                else if (sourceImage.Width <= targetWidth && sourceImage.Height <= targetHeight)
                {
                    width = sourceImage.Width;
                    height = sourceImage.Height;
                }
                else
                {
                    width = targetWidth;
                    height = (width * sourceImage.Height) / sourceImage.Width;
                    if (height > targetHeight)
                    {
                        height = targetHeight;
                        width = (height * sourceImage.Width) / sourceImage.Height;
                    }
                }
               // g.DrawImage(sourceImage, (targetWidth - width) / 2, (targetHeight - height) / 2, width, height);
               g.DrawImage(sourceImage, (targetWidth - width) / 2, (targetHeight - height) / 2, width, height);
                sourceImage.Dispose();
                targetPicture.Save(path, System.Drawing.Imaging.ImageFormat.Png);
                return targetPicture;
            }
            catch (Exception ex)
            {

            }
            return null;
        }
    }
}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值