summaryrefslogtreecommitdiffstats
path: root/win/CS/HandBrakeWPF/Helpers/GrayscaleImage.cs
blob: 3993ddb40967b0080e79d561fd5e062d0af0a7a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GrayscaleImage.cs" company="HandBrake Project (http://handbrake.fr)">
//   This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License.
// </copyright>
// <summary>
//   Extend the Image Class to support a grayscale mode.
//   Usage: local:AutoGreyableImage Source="Image.png"
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace HandBrakeWPF.Helpers
{
    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;

    /// <summary>
    /// Extend the Image Class to support a grayscale mode.
    /// </summary>
    public class GrayscaleImage : Image
    {
        /// <summary>
        /// Initializes static members of the <see cref="GrayscaleImage"/> class. 
        /// Usage: local:AutoGreyableImage Source="Image.png"
        /// </summary>
        static GrayscaleImage()
        {
            // Override the metadata of the IsEnabled property.
            IsEnabledProperty.OverrideMetadata(typeof(GrayscaleImage), new FrameworkPropertyMetadata(true, IsEnabledPropertyChanged));
        }

        /// <summary>
        /// The is enabled property changed.
        /// When this changes, grayscale the image when false, leave with colour when true.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <param name="args">
        /// The args.
        /// </param>
        private static void IsEnabledPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs args)
        {
            var sourceImage = source as GrayscaleImage;
            if (sourceImage != null)
            {
                if (!Convert.ToBoolean(args.NewValue))
                {
                    var bitmapImage = new BitmapImage(new Uri(sourceImage.Source.ToString()));
                    sourceImage.Source = new FormatConvertedBitmap(bitmapImage, PixelFormats.Gray32Float, null, 0);
                    sourceImage.OpacityMask = new ImageBrush(bitmapImage);
                }
                else
                {
                    sourceImage.Source = ((FormatConvertedBitmap)sourceImage.Source).Source;
                    sourceImage.OpacityMask = null;
                }
            }
        }
    }
}