Пример #1
0
        public BitmapSource ColorConvertedRead(string path, ColorProfileType from)
        {
            BitmapSource r = null;

            var bmi = new BitmapImage();

            bmi.BeginInit();
            bmi.UriSource   = new Uri(path, UriKind.RelativeOrAbsolute);
            bmi.CacheOption = BitmapCacheOption.OnLoad;
            bmi.EndInit();
            bmi.Freeze();

            if (0 == ColorProfileName(from).CompareTo(MonitorProfileName))
            {
                // color space is the same.
                r = bmi;
            }
            else
            {
                var ccb = new ColorConvertedBitmap();
                ccb.BeginInit();
                ccb.Source                  = bmi;
                ccb.SourceColorContext      = mColorCtx[(int)from];
                ccb.DestinationColorContext = mColorCtx[(int)ColorProfileType.Monitor];
                ccb.EndInit();
                ccb.Freeze();

                r = ccb;
            }

            IsVideo = false;

            return(r);
        }
        /// <summary>
        /// Converts byte array of an image to BitmapSource reflecting color profiles.
        /// </summary>
        /// <param name="sourceData">Byte array of source image</param>
        /// <param name="colorProfilePath">Color profile file path used by a monitor</param>
        /// <returns>BitmapSource</returns>
        public static async Task <BitmapSource> ConvertImageAsync(byte[] sourceData, string colorProfilePath)
        {
            using (var ms = new MemoryStream())
            {
                await ms.WriteAsync(sourceData, 0, sourceData.Length).ConfigureAwait(false);

                ms.Seek(0, SeekOrigin.Begin);

                var frame = BitmapFrame.Create(
                    ms,
                    BitmapCreateOptions.IgnoreColorProfile | BitmapCreateOptions.PreservePixelFormat,
                    BitmapCacheOption.OnLoad);

                var ccb = new ColorConvertedBitmap();
                ccb.BeginInit();
                ccb.Source = frame;

                ccb.SourceColorContext = (frame.ColorContexts?.Any() == true)
                                        ? frame.ColorContexts.First()
                                        : new ColorContext(PixelFormats.Bgra32); // Fallback color profile

                ccb.DestinationColorContext = !string.IsNullOrEmpty(colorProfilePath)
                                        ? new ColorContext(new Uri(colorProfilePath))
                                        : new ColorContext(PixelFormats.Bgra32); // Fallback color profile

                ccb.DestinationFormat = PixelFormats.Bgra32;
                ccb.EndInit();
                ccb.Freeze();

                return(ccb);
            }
        }
Пример #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);
        }
Пример #4
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);
        }
Пример #5
0
        /// <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);
        }
Пример #6
0
        protected override BitmapSource ReadData(AlphaMaskedImage image, Stream stream, int length, BitmapPalette palette, PixelFormat?pixelFormat)
        {
            int stride = BitmapHelper.Stride(image.Width, _inPixelFormat);

            byte[,] alphaMask = new byte[image.Height, image.Width];
            byte[] imageBuffer = new byte[image.Height * stride];

            ReadImageAndAlpha(image, stream, length, stride, alphaMask, imageBuffer);
            BitmapSource         internalBitmap  = CreateInternalBitmap(image, palette, stride, imageBuffer);
            ColorConvertedBitmap convertedBitmap = ConvertToAlphaChanneled(internalBitmap);
            WriteableBitmap      mergedBitmap    = MergeAlphaMask(image, convertedBitmap, alphaMask);

            return(mergedBitmap);
        }
Пример #7
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);
            }
        }
Пример #8
0
        public int VReadImage(long posToSeek, ColorProfileType from, out BitmapSource bs, ref long duration, ref long timeStamp)
        {
            int dpi = 96;
            var pf  = PixelFormats.Bgr32;
            int hr  = videoRead.ReadImage(posToSeek, out WWMFVideoReader.VideoImage vi);

            if (hr < 0)
            {
                bs = BitmapSource.Create(0, 0, dpi, dpi, pf, null, null, 1);
                return(hr);
            }

            var bytesPerPixel = (pf.BitsPerPixel + 7) / 8;
            var stride        = bytesPerPixel * vi.w;

            var wb = new WriteableBitmap(vi.w, vi.h, dpi, dpi, pf, null);

            wb.Lock();
            wb.WritePixels(new Int32Rect(0, 0, vi.w, vi.h), vi.img, stride, 0);
            wb.Unlock();
            wb.Freeze();

            if (0 == ColorProfileName(from).CompareTo(MonitorProfileName))
            {
                // color space is the same.
                bs = wb;
            }
            else
            {
                var ccb = new ColorConvertedBitmap();
                ccb.BeginInit();
                ccb.Source                  = wb;
                ccb.SourceColorContext      = mColorCtx[(int)from];
                ccb.DestinationColorContext = mColorCtx[(int)ColorProfileType.Monitor];
                ccb.EndInit();
                ccb.Freeze();

                bs = ccb;
            }

            duration  = vi.duration;
            timeStamp = vi.timeStamp;

            IsVideo = true;
            return(hr);
        }
Пример #9
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;
        }
Пример #10
0
        public void Convert()
        {
            var rgbJpeg     = BitmapFrame.Create(GetStreamFromResource("CMYKConversion.Images.Desert.jpg"));
            var iccCmykJpeg = new ColorConvertedBitmap(
                rgbJpeg,
                new ColorContext(PixelFormats.Default),
                new ColorContext(GetProfilePath("Profiles/1010_ISO_Coated_39L.icc")),
                PixelFormats.Cmyk32
                );
            var jpegBitmapEncoder = new JpegBitmapEncoder();

            jpegBitmapEncoder.Frames.Add(BitmapFrame.Create(iccCmykJpeg));
            var iccCmykJpegStream = new MemoryStream();

            jpegBitmapEncoder.Save(iccCmykJpegStream);

            iccCmykJpegStream.Flush();
            SaveMemoryStream(iccCmykJpegStream, "C:\\desertCMYK.jpg");
            iccCmykJpegStream.Close();
        }
Пример #11
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);
            }
        }
        /// <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);
        }
Пример #13
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);
        }
Пример #14
0
        private void CreateAndShowMainWindow()
        {
            // Create the application's main window
            mainWindow       = new Window();
            mainWindow.Title = "BitmapImage Sample";

            //<Snippet1>
            // Define a BitmapImage.
            Image       myImage = new Image();
            BitmapImage bi      = new BitmapImage();

            // Begin initialization.
            bi.BeginInit();

            // Set properties.
            bi.CacheOption       = BitmapCacheOption.OnDemand;
            bi.CreateOptions     = BitmapCreateOptions.DelayCreation;
            bi.DecodePixelHeight = 125;
            bi.DecodePixelWidth  = 125;
            bi.Rotation          = Rotation.Rotate90;
            MessageBox.Show(bi.IsDownloading.ToString());
            bi.UriSource = new Uri("smiley.png", UriKind.Relative);

            // End initialization.
            bi.EndInit();
            myImage.Source  = bi;
            myImage.Stretch = Stretch.None;
            myImage.Margin  = new Thickness(5);
            //</Snippet1>

            //Define a Second BitmapImage and Source
            Image       myImage2 = new Image();
            BitmapImage bi2      = new BitmapImage();

            bi2.BeginInit();
            bi2.DecodePixelHeight = 75;
            bi2.DecodePixelWidth  = 75;
            bi2.CacheOption       = BitmapCacheOption.None;
            bi2.CreateOptions     = BitmapCreateOptions.PreservePixelFormat;
            bi2.Rotation          = Rotation.Rotate180;
            bi2.UriSource         = new Uri("smiley.png", UriKind.Relative);
            bi2.EndInit();
            myImage2.Source  = bi2;
            myImage2.Stretch = Stretch.None;
            myImage2.Margin  = new Thickness(5);

            //<Snippet2>
            Stream               imageStream         = new FileStream("tulipfarm.jpg", FileMode.Open, FileAccess.Read, FileShare.Read);
            BitmapSource         myBitmapSource      = BitmapFrame.Create(imageStream);
            BitmapFrame          myBitmapSourceFrame = (BitmapFrame)myBitmapSource;
            ColorContext         sourceColorContext  = myBitmapSourceFrame.ColorContexts[0];
            ColorContext         destColorContext    = new ColorContext(PixelFormats.Bgra32);
            ColorConvertedBitmap ccb = new ColorConvertedBitmap(myBitmapSource, sourceColorContext, destColorContext, PixelFormats.Pbgra32);
            Image myImage3           = new Image();

            myImage3.Source  = ccb;
            myImage3.Stretch = Stretch.None;
            imageStream.Close();
            //</Snippet2>

            //Show ColorConvertedBitmap Properties
            Stream       imageStream2         = new FileStream("tulipfarm.jpg", FileMode.Open, FileAccess.Read, FileShare.Read);
            BitmapSource myBitmapSource2      = BitmapFrame.Create(imageStream2);
            BitmapFrame  myBitmapSourceFrame2 = (BitmapFrame)myBitmapSource;
            //<Snippet3>
            ColorConvertedBitmap myColorConvertedBitmap = new ColorConvertedBitmap();

            myColorConvertedBitmap.BeginInit();
            myColorConvertedBitmap.SourceColorContext      = myBitmapSourceFrame2.ColorContexts[0];
            myColorConvertedBitmap.Source                  = myBitmapSource2;
            myColorConvertedBitmap.DestinationFormat       = PixelFormats.Pbgra32;
            myColorConvertedBitmap.DestinationColorContext = new ColorContext(PixelFormats.Bgra32);
            myColorConvertedBitmap.EndInit();
            //</Snippet3>


            //Define a StackPanel
            StackPanel myStackPanel = new StackPanel();

            // Add the images to the parent StackPanel
            myStackPanel.Children.Add(myImage);
            myStackPanel.Children.Add(myImage2);
            myStackPanel.Children.Add(myImage3);

            // Add the StackPanel as the Content of the Parent Window Object
            mainWindow.Content = myStackPanel;
            mainWindow.Show();
        }