Beispiel #1
0
 public static void SeedData(ColorContext context)
 {
     Console.WriteLine("Applying Migration");
     context.Database.Migrate();
     if (!context.colors.Any())
     {
         Console.WriteLine("Seeding");
         context.colors.AddRange(new Color()
         {
             colorName = "Red"
         },
                                 new Color()
         {
             colorName = "Yellow"
         },
                                 new Color()
         {
             colorName = "Green"
         }
                                 );
         context.SaveChanges();
     }
     else
     {
         Console.WriteLine("Data Available");
     }
 }
Beispiel #2
0
        /// <summary>
        /// Construct a ColorConvertedBitmap
        /// </summary>
        /// <param name="source">Input BitmapSource to color convert</param>
        /// <param name="sourceColorContext">Source Color Context</param>
        /// <param name="destinationColorContext">Destination Color Context</param>
        /// <param name="format">Destination Pixel format</param>
        public ColorConvertedBitmap(BitmapSource source, ColorContext sourceColorContext, ColorContext destinationColorContext, PixelFormat format)
            : base(true) // Use base class virtuals
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (sourceColorContext == null)
            {
                throw new ArgumentNullException("sourceColorContext");
            }

            if (destinationColorContext == null)
            {
                throw new ArgumentNullException("destinationColorContext");
            }

            _bitmapInit.BeginInit();

            Source                  = source;
            SourceColorContext      = sourceColorContext;
            DestinationColorContext = destinationColorContext;
            DestinationFormat       = format;

            _bitmapInit.EndInit();
            FinalizeCreation();
        }
Beispiel #3
0
        /// <summary>
        ///  Return an object that should be set on the targetObject's targetProperty
        ///  for this markup extension.  For ColorConvertedBitmapExtension, this is the object found in
        ///  a resource dictionary in the current parent chain that is keyed by ResourceKey
        /// </summary>
        /// <returns>
        ///  The object to set on this property.
        /// </returns>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (_image == null)
            {
                throw new InvalidOperationException(SR.Get(SRID.ColorConvertedBitmapExtensionNoSourceImage));
            }
            if (_sourceProfile == null)
            {
                throw new InvalidOperationException(SR.Get(SRID.ColorConvertedBitmapExtensionNoSourceProfile));
            }

            // [BreakingChange]
            // (NullReferenceException in ColorConvertedBitmapExtension.ProvideValue)
            // We really should throw an ArgumentNullException here for serviceProvider.

            // Save away the BaseUri.
            IUriContext uriContext = serviceProvider.GetService(typeof(IUriContext)) as IUriContext;

            if (uriContext == null)
            {
                throw new InvalidOperationException(SR.Get(SRID.MarkupExtensionNoContext, GetType().Name, "IUriContext"));
            }
            _baseUri = uriContext.BaseUri;


            Uri imageUri              = GetResolvedUri(_image);
            Uri sourceProfileUri      = GetResolvedUri(_sourceProfile);
            Uri destinationProfileUri = GetResolvedUri(_destinationProfile);

            ColorContext sourceContext      = new ColorContext(sourceProfileUri);
            ColorContext destinationContext = destinationProfileUri != null ?
                                              new ColorContext(destinationProfileUri) :
                                              new ColorContext(PixelFormats.Default);

            BitmapDecoder decoder = BitmapDecoder.Create(
                imageUri,
                BitmapCreateOptions.IgnoreColorProfile | BitmapCreateOptions.IgnoreImageCache,
                BitmapCacheOption.None
                );

            BitmapSource          bitmap          = decoder.Frames[0];
            FormatConvertedBitmap formatConverted = new FormatConvertedBitmap(bitmap, PixelFormats.Bgra32, null, 0.0);

            object result = formatConverted;

            try
            {
                ColorConvertedBitmap colorConverted = new ColorConvertedBitmap(formatConverted, sourceContext, destinationContext, PixelFormats.Bgra32);
                result = colorConverted;
            }
            catch (FileFormatException)
            {   // Gracefully ignore non-matching profile
                // If the file contains a bad color context, we catch the exception here
                // since color transform isn't possible
                // with the given color context.
            }

            return(result);
        }
Beispiel #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BitmapProperties1"/> class.
 /// </summary>
 /// <param name="pixelFormat">The pixel format.</param>
 /// <param name="dpiX">The dpi X.</param>
 /// <param name="dpiY">The dpi Y.</param>
 /// <param name="bitmapOptions">The bitmap options.</param>
 /// <param name="colorContext">The color context.</param>
 public BitmapProperties1(PixelFormat pixelFormat, float dpiX, float dpiY, BitmapOptions bitmapOptions, ColorContext colorContext)
 {
     PixelFormat   = pixelFormat;
     DpiX          = dpiX;
     DpiY          = dpiY;
     BitmapOptions = bitmapOptions;
     ColorContext  = colorContext;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="BitmapProperties1"/> class.
 /// </summary>
 /// <param name="pixelFormat">The pixel format.</param>
 /// <param name="dpiX">The dpi X.</param>
 /// <param name="dpiY">The dpi Y.</param>
 /// <param name="bitmapOptions">The bitmap options.</param>
 /// <param name="colorContext">The color context.</param>
 public BitmapProperties1(PixelFormat pixelFormat, float dpiX, float dpiY, BitmapOptions bitmapOptions, ColorContext colorContext)
 {
     PixelFormat = pixelFormat;
     DpiX = dpiX;
     DpiY = dpiY;
     BitmapOptions = bitmapOptions;
     ColorContext = colorContext;
 }
Beispiel #6
0
        private static ColorConvertedBitmap ConvertToAlphaChanneled(BitmapSource internalBitmap)
        {
            ColorContext         sourceContext   = new ColorContext(_inPixelFormat);
            ColorContext         targetContext   = new ColorContext(_outPixelFormat);
            ColorConvertedBitmap convertedBitmap = new ColorConvertedBitmap(internalBitmap, sourceContext, targetContext, _outPixelFormat);

            return(convertedBitmap);
        }
        public override ColorConvertedBitmap Create(DeterministicRandom random)
        {
            BitmapSource         bitmapSource       = (BitmapSource)BitmapFrame;
            ColorContext         sourceColorContext = BitmapFrame.ColorContexts[0];
            ColorConvertedBitmap cloreConverted     = new ColorConvertedBitmap(bitmapSource, sourceColorContext, ColorContext, PixelFormat);

            cloreConverted.Freeze();
            return(cloreConverted);
        }
Beispiel #8
0
        internal override void Draw(TMenu instance)
        {
            if (this.lastInstance == null || this.lastContext == null || !this.lastInstance.Equals(instance))
            {
                this.lastContext = this.GetContext(instance);
            }

            this.lastContext.Draw();
        }
Beispiel #9
0
 private void PrintInstructions()
 {
     using (new ColorContext(ColorContext.InstructionsColor))
     {
         ColorContext.PrintWithKeyCodes("Please enter [N]orth, [S]outh, [E]ast or [W]est to move around,\n");
         ColorContext.PrintWithKeyCodes("[L] to look around, [P] to pick up an item, [I] for Inventory, [B] for Battle,\n");
         ColorContext.PrintWithKeyCodes("[C] to view stats, or [M] to print the map. [U] is to use items,\n");
         ColorContext.PrintWithKeyCodes("[T] to talk to someone, or [Q] qommit suicide to exit the game.\n\n");
     }
 }
Beispiel #10
0
        /// <summary>
        /// print a text
        /// </summary>
        /// <param name="text"></param>
        public static void Print(string text)
        {
            var contextGreen = new ColorContext(new Green());

            contextGreen.ContextInterface();
            Console.WriteLine(text);
            var contextWhite = new ColorContext(new White());

            contextWhite.ContextInterface();
            Console.WriteLine(new string('-', 50));
        }
Beispiel #11
0
        /// <summary>
        /// print turtle changed its direction
        /// </summary>
        /// <param name="dir"></param>
        public static void Print(Directions dir)
        {
            var contextGreen = new ColorContext(new Green());

            contextGreen.ContextInterface();
            Console.WriteLine(rotate.Replace("{to}", dir.ToString()));
            var contextWhite = new ColorContext(new White());

            contextWhite.ContextInterface();
            Console.WriteLine(new string('-', 50));
        }
Beispiel #12
0
        /// <summary>
        /// print turtle's starting state
        /// </summary>
        /// <param name="turtle"></param>
        public static void Print(Turtle.Library.Models.Turtle turtle)
        {
            var contextGreen = new ColorContext(new Green());

            contextGreen.ContextInterface();
            Console.WriteLine(startString.Replace("{x}", turtle.Position.X.ToString()).Replace("{y}", turtle.Position.Y.ToString()).Replace("{dir}", turtle.Direction.ToString()));
            var contextWhite = new ColorContext(new White());

            contextWhite.ContextInterface();
            Console.WriteLine(new string('-', 50));
        }
Beispiel #13
0
 private static void SaveColors(IEnumerable <ColorSwatch> colorSwatches, string dbFile)
 {
     using ColorContext colorContext = new ColorContext(dbFile);
     colorContext.Database.EnsureCreated();
     foreach (ColorSwatch colorSwatch in colorSwatches)
     {
         if (!colorContext.TryAddNewColorSwatch(colorSwatch))
         {
             Console.WriteLine("Already added " + colorSwatch.Name + " " + colorSwatch.ColorNumbers[0].Number);
         }
     }
 }
Beispiel #14
0
 public void PrintItems <T>(List <T> items) where T : BaseObject
 {
     for (int i = 0; i < items.Count; i++)
     {
         var item = items[i];
         using (new ColorContext(item.Color))
         {
             ColorContext.PrintWithKeyCodes($"[{i + 1}] {item.Name} {item.Description}\n");
         }
     }
     Console.WriteLine();
 }
Beispiel #15
0
        public static void Execute(MatchOptions opts)
        {
            Color customColor = ColorTranslator.FromHtml("#" + opts.HexCode.Replace("#", ""));

            using ColorContext colorContext = new ColorContext(opts.DbFile);
            List <ColorSwatch> colorSwatches             = colorContext.ColorSwatches.Include(s => s.ColorNumbers).ToList();
            IOrderedEnumerable <ColorMatch> colorMatches = colorSwatches.Select(x => new ColorMatch(customColor, x)).OrderBy(x => x.MatchError);

            foreach (ColorMatch colorMatch in colorMatches.Take(opts.Top))
            {
                Console.WriteLine(colorMatch);
            }
        }
        /// <summary>
        /// Converts color profile of BitmapSource for color management.
        /// </summary>
        /// <param name="bitmapSource">Source BitmapSource</param>
        /// <param name="sourceProfile">Source color profile</param>
        /// <param name="destinationProfile">Destination color profile</param>
        /// <returns>Outcome BitmapSource</returns>
        /// <remarks>
        /// Source color profile is color profile embedded in image file and destination color profile is
        /// color profile used by the monitor to which the Window belongs.
        /// </remarks>
        public static BitmapSource ConvertColorProfile(BitmapSource bitmapSource, ColorContext sourceProfile, ColorContext destinationProfile)
        {
            var bitmapConverted = new ColorConvertedBitmap();

            bitmapConverted.BeginInit();
            bitmapConverted.Source                  = bitmapSource;
            bitmapConverted.SourceColorContext      = sourceProfile;
            bitmapConverted.DestinationColorContext = destinationProfile;
            bitmapConverted.DestinationFormat       = PixelFormats.Bgra32;
            bitmapConverted.EndInit();

            return(bitmapConverted);
        }
Beispiel #17
0
        private static BitmapSource ConvertToAlpha(BitmapSource image, AowImage imageData)
        {
            unsafe
            {
                int sourceStride = BitmapHelper.Stride(image.PixelWidth, image.Format);

                //	array has twice more rows than needed, but otherwise CopyPixels fails for some reason
                ushort[,] sourceDataRaw = new ushort[image.PixelHeight * sizeof(ushort), sourceStride / sizeof(ushort)];
                fixed(ushort *dataPtr = &sourceDataRaw[0, 0])
                {
                    image.CopyPixels(Int32Rect.Empty, new IntPtr(dataPtr), sourceDataRaw.Length, sourceStride);
                }

                ushort          alphaCode    = (ushort)(imageData as KeyColorImage <int>).KeyColorIndex;
                List <IntPoint> alphaIndexes = new List <IntPoint>();

                for (int i = 0; i < sourceDataRaw.GetLength(0); i++)
                {
                    for (int j = 0; j < sourceDataRaw.GetLength(1); j++)
                    {
                        if (sourceDataRaw[i, j] == alphaCode)
                        {
                            alphaIndexes.Add(new IntPoint {
                                X = i, Y = j
                            });
                        }
                    }
                }

                ColorContext         sourceContext = new ColorContext(image.Format);
                ColorContext         targetContext = new ColorContext(PixelFormats.Bgra32);
                ColorConvertedBitmap converted     = new ColorConvertedBitmap(image, sourceContext, targetContext, PixelFormats.Bgra32);
                int targetStride = BitmapHelper.Stride(converted.PixelWidth, converted.Format);

                WriteableBitmap writeable = new WriteableBitmap(converted);
                writeable.Lock();

                IntPtr backBufferPtr = writeable.BackBuffer;
                foreach (IntPoint p in alphaIndexes)
                {
                    IntPtr pixelPtr = backBufferPtr + targetStride * p.X + 4 * p.Y;
                    *((int *)pixelPtr) = 0;
                }

                writeable.AddDirtyRect(new Int32Rect(0, 0, writeable.PixelWidth, writeable.PixelHeight));
                writeable.Unlock();

                return(writeable);
            }
        }
Beispiel #18
0
        public static void Print(Point pointFrom, Point pointTo)
        {
            ColorContext context = new ColorContext(new Yellow());

            context.ContextInterface();
            string combinePointFrom = $"({pointFrom.X},{pointFrom.Y})";
            string combinePointTo   = $"({pointTo.X},{pointTo.Y})";
            string printText        = movedFromTo.Replace("{from}", combinePointFrom).Replace("{to}", combinePointTo);

            Console.WriteLine(printText);
            ColorContext contextWhite = new ColorContext(new White());

            contextWhite.ContextInterface();
            Console.WriteLine(new string('-', 50));
        }
Beispiel #19
0
 /// <summary>
 /// Returns a string containing all the characters in the room
 /// </summary>
 /// <returns>A description of the characters in the room</returns>
 public void PrintNPCs()
 {
     if (NPCsInRoom.Count == 0)
     {
         using (new ColorContext(ColorContext.FailureColor))
         {
             Console.WriteLine("There's no one here.");
         }
     }
     for (int i = 0; i < NPCsInRoom.Count; i++)
     {
         string formattedName = NPCsInRoom[i].Name.Replace('_', ' ');
         ColorContext.PrintWithKeyCodes($"[{i+1}] {formattedName} : {NPCsInRoom[i].Description}\n");
     }
     Console.WriteLine();
 }
        private ImageSource GetBitmapSource(SvgImageElement element, WpfDrawingContext context)
        {
            ImageSource imageSource = this.GetBitmap(element, context);

            if (imageSource == null)
            {
                return(imageSource);
            }

            SvgColorProfileElement colorProfile = (SvgColorProfileElement)element.ColorProfile;

            if (colorProfile == null || !(imageSource is BitmapSource))
            {
                return(imageSource);
            }
            BitmapSource bitmapSource = (BitmapSource)imageSource;
            BitmapFrame  inputFrame   = BitmapFrame.Create(bitmapSource);

            SvgUriReference svgUri     = colorProfile.UriReference;
            Uri             profileUri = new Uri(svgUri.AbsoluteUri);

            ColorContext colorContext = new ColorContext(new Uri(svgUri.AbsoluteUri));

            var colorContexts = new ReadOnlyCollection <ColorContext>(new ColorContext[] { colorContext });

            BitmapFrame outputFrame   = BitmapFrame.Create(inputFrame, null, null, colorContexts);
            var         bitmapImage   = new BitmapImage();
            var         bitmapEncoder = new PngBitmapEncoder();

            bitmapEncoder.Frames.Add(outputFrame);

            using (var stream = new MemoryStream())
            {
                bitmapEncoder.Save(stream);
                stream.Seek(0, SeekOrigin.Begin);

                bitmapImage.BeginInit();
                bitmapImage.CacheOption  = BitmapCacheOption.OnLoad;
                bitmapImage.StreamSource = stream;
                bitmapImage.EndInit();
            }

//            bitmapImage.Freeze();

            return(bitmapImage);
        }
Beispiel #21
0
        /// <summary>
        /// print turtle moved from point a to point b
        /// </summary>
        /// <param name="pointFrom"></param>
        /// <param name="pointTo"></param>
        public static void Print(Point pointFrom, Point pointTo)
        {
            var context = new ColorContext(new Yellow());

            context.ContextInterface();
            var combinePointFrom = $"({pointFrom.X},{pointFrom.Y})";
            var combinePointTo   = $"({pointTo.X},{pointTo.Y})";
            var printText        = movedFromTo.Replace("{from}", combinePointFrom).Replace("{to}", combinePointTo);

            //var printText = text.Replace("{from}", combinePointFrom).Replace("{to}", combinePointTo);
            //if (action != null) printText = $"{printText} - {action}";
            Console.WriteLine(printText);
            var contextWhite = new ColorContext(new White());

            contextWhite.ContextInterface();
            Console.WriteLine(new string('-', 50));
        }
Beispiel #22
0
        public ColorConvertedBitmapExample()
        {
            //How to use ColorConvertedBitmap
            string       jpegFile    = "sampleImages/WaterLilies.jpg";
            Stream       imageStream = new FileStream(jpegFile, FileMode.Open, FileAccess.Read, FileShare.Read);
            BitmapSource bsrc        = BitmapFrame.Create(imageStream);
            BitmapFrame  bsrcFrame   = (BitmapFrame)bsrc;
            //ColorContext sourceColorContext = (ColorContext)bsrcFrame.ColorContexts;
            ColorContext sourceColorContext = new ColorContext(PixelFormats.Indexed1);
            // Get the ColorContext from the BitmapFrame if there is one.
            ReadOnlyCollection <ColorContext> myColorContextCollection = bsrcFrame.ColorContexts;

            if (myColorContextCollection != null)
            {
                foreach (ColorContext myColorContext in myColorContextCollection)
                {
                    sourceColorContext = myColorContext;
                }
            }

            // sourceColorContext= bsrcFrame.ColorContext;
            // ColorContext sourceColorContext = new ColorContext();


            ColorContext         destColorContext = new ColorContext(System.Windows.Media.PixelFormats.Indexed1);
            ColorConvertedBitmap ccb = new ColorConvertedBitmap(bsrc, sourceColorContext, destColorContext, PixelFormats.Bgr24);

            // Create Image Element
            Image myImage = new Image();

            myImage.Width = 200;
            //set image source
            myImage.Source = ccb;

            // Add Image to the UI
            StackPanel myStackPanel = new StackPanel();

            //myStackPanel.Children.Add(myImage);
            //TextBlock tb = new TextBlock();
            //tb.Text = s;
            myStackPanel.Children.Add(myImage);
            this.Content = myStackPanel;
        }
        /// <summary>Returns an object that should be set on the property where this extension is applied. For <see cref="T:System.Windows.ColorConvertedBitmapExtension" />, this is the completed <see cref="T:System.Windows.Media.Imaging.ColorConvertedBitmap" />.</summary>
        /// <param name="serviceProvider">An object that can provide services for the markup extension. This service is expected to provide results for <see cref="T:System.Windows.Markup.IUriContext" />.</param>
        /// <returns>A <see cref="T:System.Windows.Media.Imaging.ColorConvertedBitmap" /> based on the values passed to the constructor.</returns>
        // Token: 0x06000859 RID: 2137 RVA: 0x0001B1C4 File Offset: 0x000193C4
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (this._image == null)
            {
                throw new InvalidOperationException(SR.Get("ColorConvertedBitmapExtensionNoSourceImage"));
            }
            if (this._sourceProfile == null)
            {
                throw new InvalidOperationException(SR.Get("ColorConvertedBitmapExtensionNoSourceProfile"));
            }
            IUriContext uriContext = serviceProvider.GetService(typeof(IUriContext)) as IUriContext;

            if (uriContext == null)
            {
                throw new InvalidOperationException(SR.Get("MarkupExtensionNoContext", new object[]
                {
                    base.GetType().Name,
                    "IUriContext"
                }));
            }
            this._baseUri = uriContext.BaseUri;
            Uri                   resolvedUri             = this.GetResolvedUri(this._image);
            Uri                   resolvedUri2            = this.GetResolvedUri(this._sourceProfile);
            Uri                   resolvedUri3            = this.GetResolvedUri(this._destinationProfile);
            ColorContext          sourceColorContext      = new ColorContext(resolvedUri2);
            ColorContext          destinationColorContext = (resolvedUri3 != null) ? new ColorContext(resolvedUri3) : new ColorContext(PixelFormats.Default);
            BitmapDecoder         bitmapDecoder           = BitmapDecoder.Create(resolvedUri, BitmapCreateOptions.IgnoreColorProfile | BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.None);
            BitmapSource          source = bitmapDecoder.Frames[0];
            FormatConvertedBitmap formatConvertedBitmap = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0.0);
            object                result = formatConvertedBitmap;

            try
            {
                ColorConvertedBitmap colorConvertedBitmap = new ColorConvertedBitmap(formatConvertedBitmap, sourceColorContext, destinationColorContext, PixelFormats.Bgra32);
                result = colorConvertedBitmap;
            }
            catch (FileFormatException)
            {
            }
            return(result);
        }
Beispiel #24
0
        private ImageSource GetBitmapSource(SvgImageElement element, WpfDrawingContext context)
        {
            ImageSource imageSource = this.GetBitmap(element, context);

            if (imageSource == null)
            {
                return(imageSource);
            }

            SvgColorProfileElement colorProfile = (SvgColorProfileElement)element.ColorProfile;

            if (colorProfile == null || !(imageSource is BitmapSource))
            {
                return(imageSource);
            }
            else
            {
                BitmapSource         bitmapSource       = (BitmapSource)imageSource;
                BitmapFrame          bitmapSourceFrame  = BitmapFrame.Create(bitmapSource);
                ColorContext         sourceColorContext = null;
                IList <ColorContext> colorContexts      = bitmapSourceFrame.ColorContexts;
                if (colorContexts != null && colorContexts.Count != 0)
                {
                    sourceColorContext = colorContexts[0];
                }
                else
                {
                    sourceColorContext = new ColorContext(bitmapSource.Format);
                    //sourceColorContext = new ColorContext(PixelFormats.Default);
                }

                SvgUriReference svgUri     = colorProfile.UriReference;
                Uri             profileUri = new Uri(svgUri.AbsoluteUri);

                ColorContext         destColorContext = new ColorContext(profileUri);
                ColorConvertedBitmap convertedBitmap  = new ColorConvertedBitmap(bitmapSource,
                                                                                 sourceColorContext, destColorContext, bitmapSource.Format);

                return(convertedBitmap);
            }
        }
Beispiel #25
0
        /// <summary>
        /// デバイスコンテキストからモニタを取得
        /// </summary>
        /// <param name="hDC"></param>
        /// <returns></returns>
        private static MonitorInfo GetMonitorFromHDC(IntPtr hDC)
        {
            var mi      = new MONITORINFOEX();
            var success = NativeMethods.GetMonitorInfo(hDC, mi);

            if (!success)
            {
                throw new InvalidOperationException();
            }

            var dc = NativeMethods.CreateDC(mi.szDevice, mi.szDevice, null, IntPtr.Zero);

            var lpcbName = 0U;

            NativeMethods.GetICMProfile(dc, ref lpcbName, null);
            var sb = new StringBuilder((int)lpcbName);

            NativeMethods.GetICMProfile(dc, ref lpcbName, sb);

            NativeMethods.DeleteDC(dc);

            var profileUri = sb.ToString();
            var context    = new ColorContext(new Uri(profileUri));

            return(new MonitorInfo
            {
                DeviceName = mi.szDevice,
                MonitorProfile = context,
                Bounds = new Rect(
                    mi.rcMonitor.Left,
                    mi.rcMonitor.Top,
                    mi.rcMonitor.Right - mi.rcMonitor.Left,
                    mi.rcMonitor.Bottom - mi.rcMonitor.Top),
                WorkingArea = new Rect(
                    mi.rcWork.Left,
                    mi.rcWork.Top,
                    mi.rcWork.Right - mi.rcWork.Left,
                    mi.rcWork.Bottom - mi.rcWork.Top),
                IsPrimary = mi.dwFlags == 1
            });
        }
Beispiel #26
0
        public static void Execute(FilterOptions opts)
        {
            using ColorContext colorContext = new ColorContext(opts.DbFile);

            List <ColorSwatch> colorSwatches = colorContext.ColorSwatches.Include(s => s.ColorNumbers).ToList();
            List <ColorFilter> colorFilters  = GetColorFilters();

            foreach (ColorFilter colorFilter in colorFilters)
            {
                ColorSwatch[] filteredColorSwatches = colorFilter.FilterColors(colorSwatches).Where(x => ColorHslSelector(x, opts)).ToArray();
                string        fileName = colorFilter + ".png";
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
                if (filteredColorSwatches.Length != 0)
                {
                    ColorWriter.WriteColors(filteredColorSwatches, fileName);
                    PrintFilteredColors(colorFilter, filteredColorSwatches);
                }
            }
        }
Beispiel #27
0
        /// <summary>
        /// Converts a System.Drawing.Image to a BitmapImage which is compatible
        /// with WPF
        /// </summary>
        /// <param name="image">The image.</param>
        /// <returns></returns>
        //internal static BitmapSource GetColourCorrectedImageSource(DrawingImage image)
        internal static BitmapSource GetBitmapImage2(DrawingImage image)
        {
            var memoryStream = new MemoryStream();

            image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
            var frame = BitmapFrame.Create(memoryStream);

            // Windows ICC profile location: C:\Windows\System32\spool\drivers\color
            // Adobe ICC profiles: C:\Program Files (x86)\Common Files\Adobe\Color
            var          iccProfilePath        = @"C:\Program Files (x86)\Common Files\Adobe\Color\MPProfiles\FilmTheaterK2395PD.icc";
            Uri          destinationProfileUri = new Uri(iccProfilePath);
            ColorContext scc = new ColorContext(destinationProfileUri);

            // Using frame.Format is the same as loading the sRGB default
            ColorContext dcc = new ColorContext(frame.Format);
            //ColorContext scc = new ColorContext(new Uri(@"C:\Windows\System32\spool\drivers\color\sRGB Color Space Profile.icm"));

            // NOTE: the source and destination colorcontexes seem conceptually reversed.
            var colorConvertedBitmap = new ColorConvertedBitmap((BitmapSource)frame, scc, dcc, frame.Format);

            colorConvertedBitmap.Freeze();

            return(colorConvertedBitmap);
        }
        private void SaveFrame(SafeMILHandle frameEncodeHandle, SafeMILHandle encoderOptions, BitmapFrame frame)
        {
            SetupFrame(frameEncodeHandle, encoderOptions);

            // Helpful for debugging stress and remote dumps
            _encodeState = EncodeState.FrameEncodeInitialized;

            // Set the size
            HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.SetSize(
                              frameEncodeHandle,
                              frame.PixelWidth,
                              frame.PixelHeight
                              ));

            // Helpful for debugging stress and remote dumps
            _encodeState = EncodeState.FrameEncodeSizeSet;

            // Set the resolution
            double dpiX = frame.DpiX;
            double dpiY = frame.DpiY;

            if (dpiX <= 0)
            {
                dpiX = 96;
            }
            if (dpiY <= 0)
            {
                dpiY = 96;
            }

            HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.SetResolution(
                              frameEncodeHandle,
                              dpiX,
                              dpiY
                              ));

            // Helpful for debugging stress and remote dumps
            _encodeState = EncodeState.FrameEncodeResolutionSet;

            if (_supportsFrameThumbnails)
            {
                // Set the thumbnail.
                BitmapSource thumbnail = frame.Thumbnail;

                if (thumbnail != null)
                {
                    SafeMILHandle thumbnailHandle = thumbnail.WicSourceHandle;

                    lock (thumbnail.SyncObject)
                    {
                        HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.SetThumbnail(
                                          frameEncodeHandle,
                                          thumbnailHandle
                                          ));

                        // Helpful for debugging stress and remote dumps
                        _encodeState = EncodeState.FrameEncodeThumbnailSet;
                    }
                }
            }

            // if the source has been color corrected, we want to use a corresponding color profile
            if (frame._isColorCorrected)
            {
                ColorContext colorContext     = new ColorContext(frame.Format);
                IntPtr[]     colorContextPtrs = new IntPtr[1] {
                    colorContext.ColorContextHandle.DangerousGetHandle()
                };

                int hr = UnsafeNativeMethods.WICBitmapFrameEncode.SetColorContexts(
                    frameEncodeHandle,
                    1,
                    colorContextPtrs
                    );

                // It's possible that some encoders may not support color contexts so don't check hr
                if (hr == HRESULT.S_OK)
                {
                    // Helpful for debugging stress and remote dumps
                    _encodeState = EncodeState.FrameEncodeColorContextsSet;
                }
            }
            // if the caller has explicitly provided color contexts, add them to the encoder
            else
            {
                IList <ColorContext> colorContexts = frame.ColorContexts;
                if (colorContexts != null && colorContexts.Count > 0)
                {
                    int count = colorContexts.Count;

                    // Marshal can't convert SafeMILHandle[] so we must
                    {
                        IntPtr[] colorContextPtrs = new IntPtr[count];
                        for (int i = 0; i < count; ++i)
                        {
                            colorContextPtrs[i] = colorContexts[i].ColorContextHandle.DangerousGetHandle();
                        }

                        int hr = UnsafeNativeMethods.WICBitmapFrameEncode.SetColorContexts(
                            frameEncodeHandle,
                            (uint)count,
                            colorContextPtrs
                            );

                        // It's possible that some encoders may not support color contexts so don't check hr
                        if (hr == HRESULT.S_OK)
                        {
                            // Helpful for debugging stress and remote dumps
                            _encodeState = EncodeState.FrameEncodeColorContextsSet;
                        }
                    }
                }
            }

            // Set the pixel format and palette

            lock (frame.SyncObject)
            {
                SafeMILHandle outSourceHandle    = new SafeMILHandle();
                SafeMILHandle bitmapSourceHandle = frame.WicSourceHandle;
                SafeMILHandle paletteHandle      = new SafeMILHandle();

                // Set the pixel format and palette of the bitmap.
                // This could (but hopefully won't) introduce a format converter.
                HRESULT.Check(UnsafeNativeMethods.WICCodec.WICSetEncoderFormat(
                                  bitmapSourceHandle,
                                  paletteHandle,
                                  frameEncodeHandle,
                                  out outSourceHandle
                                  ));

                // Helpful for debugging stress and remote dumps
                _encodeState = EncodeState.FrameEncodeFormatSet;
                _writeSourceHandles.Add(outSourceHandle);

                // Set the metadata
                if (_supportsFrameMetadata)
                {
                    BitmapMetadata metadata = frame.Metadata as BitmapMetadata;

                    // If the frame has metadata associated with a different container format, then we ignore it.
                    if (metadata != null && metadata.GuidFormat == ContainerFormat)
                    {
                        SafeMILHandle /* IWICMetadataQueryWriter */ metadataHandle = new SafeMILHandle();

                        HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.GetMetadataQueryWriter(
                                          frameEncodeHandle,
                                          out metadataHandle
                                          ));

                        PROPVARIANT propVar = new PROPVARIANT();

                        try
                        {
                            propVar.Init(metadata);

                            lock (metadata.SyncObject)
                            {
                                HRESULT.Check(UnsafeNativeMethods.WICMetadataQueryWriter.SetMetadataByName(
                                                  metadataHandle,
                                                  "/",
                                                  ref propVar
                                                  ));

                                // Helpful for debugging stress and remote dumps
                                _encodeState = EncodeState.FrameEncodeMetadataSet;
                            }
                        }
                        finally
                        {
                            propVar.Clear();
                        }
                    }
                }

                Int32Rect r = new Int32Rect();
                HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.WriteSource(
                                  frameEncodeHandle,
                                  outSourceHandle,
                                  ref r
                                  ));

                // Helpful for debugging stress and remote dumps
                _encodeState = EncodeState.FrameEncodeSourceWritten;

                HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.Commit(
                                  frameEncodeHandle
                                  ));

                // Helpful for debugging stress and remote dumps
                _encodeState = EncodeState.FrameEncodeCommitted;
            }
        }
        /// <summary>
        /// Converts Stream to BitmapSource.
        /// </summary>
        /// <param name="stream">Stream</param>
        /// <param name="outerSize">Target outer size</param>
        /// <param name="willReadExif">Whether Exif metadata will be read from Stream</param>
        /// <param name="destinationProfile">Destination color profile for color management</param>
        /// <returns>BitmapSource</returns>
        private static BitmapSource ConvertStreamToBitmapSource(Stream stream, Size outerSize, bool willReadExif, ColorContext destinationProfile)
        {
            if (0 < stream.Position)
            {
                stream.Seek(0, SeekOrigin.Begin);
            }

            var bitmapFrame = BitmapFrame.Create(
                stream,
                BitmapCreateOptions.IgnoreColorProfile | BitmapCreateOptions.PreservePixelFormat,                 // For color management
                BitmapCacheOption.OnLoad);

            var orientation = willReadExif ? GetExifOrientation(bitmapFrame) : 0;             // 0 means invalid.

            var bitmapSource = ResizeAndReflectExifOrientation(bitmapFrame, outerSize, orientation);

            if (destinationProfile != null)
            {
                var sourceProfile = GetColorProfile(bitmapFrame);
                bitmapSource = ConvertColorProfile(bitmapSource, sourceProfile, destinationProfile);
            }

            bitmapSource.Freeze();

            return(bitmapSource);
        }
        /// <summary>
        /// Converts byte array to BitmapSource applying Uniform transformation.
        /// </summary>
        /// <param name="bytes">Byte array</param>
        /// <param name="outerSize">Target outer size</param>
        /// <param name="willReadExif">Whether Exif metadata will be read from byte array</param>
        /// <param name="destinationProfile">Destination color profile for color management</param>
        /// <returns>BitmapSource</returns>
        /// <exception cref="ArgumentNullException">When byte array is null or has no element.</exception>
        /// <exception cref="ImageNotSupportedException">When image format is not supported by PC.</exception>
        internal static async Task <BitmapSource> ConvertBytesToBitmapSourceUniformAsync(byte[] bytes, Size outerSize, bool willReadExif, ColorContext destinationProfile = null)
        {
            ThrowIfCollectionNullOrEmpty(bytes, nameof(bytes));

            try
            {
                using (var ms = new MemoryStream())
                {
                    await ms.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);

                    return(await Task.Run(() =>
                    {
                        if (willReadExif || (destinationProfile != null))
                        {
                            return ConvertStreamToBitmapSource(ms, outerSize, willReadExif, destinationProfile);
                        }
                        else
                        {
                            return ConvertStreamToBitmapImageUniform(ms, outerSize);
                        }
                    }));
                }
            }
            catch (Exception ex) when(IsImageNotSupported(ex))
            {
                throw new ImageNotSupportedException();
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Failed to convert byte array to BitmapSource.\r\n{ex}");
                throw;
            }
        }
 /// <summary>
 /// Converts byte array to BitmapSource.
 /// </summary>
 /// <param name="bytes">Byte array</param>
 /// <param name="targetWidth">Target width</param>
 /// <param name="willReadExif">Whether Exif metadata will be read from byte array</param>
 /// <param name="destinationProfile">Destination color profile for color management</param>
 /// <returns>BitmapSource</returns>
 /// <exception cref="ArgumentNullException">When byte array is null or has no element.</exception>
 /// <exception cref="ImageNotSupportedException">When image format is not supported by PC.</exception>
 internal static Task <BitmapSource> ConvertBytesToBitmapSourceAsync(byte[] bytes, double targetWidth, bool willReadExif, ColorContext destinationProfile = null)
 {
     return(ConvertBytesToBitmapSourceAsync(bytes, targetWidth, 0D, willReadExif, destinationProfile));
 }