Example #1
0
        public static IntPtr GenerateHICON(ImageSource image, Size dimensions)
        {
            if (image == null)
            {
                return(IntPtr.Zero);
            }

            // If we're getting this from a ".ico" resource, then it comes through as a BitmapFrame.
            // We can use leverage this as a shortcut to get the right 16x16 representation
            // because DrawImage doesn't do that for us.
            var bf = image as BitmapFrame;

            if (bf != null)
            {
                bf = GetBestMatch(bf.Decoder.Frames, ( int )dimensions.Width, ( int )dimensions.Height);
            }
            else
            {
                // Constrain the dimensions based on the aspect ratio.
                var drawingDimensions = new Rect(0, 0, dimensions.Width, dimensions.Height);

                // There's no reason to assume that the requested image dimensions are square.
                double renderRatio = dimensions.Width / dimensions.Height;
                double aspectRatio = image.Width / image.Height;

                // If it's smaller than the requested size, then place it in the middle and pad the image.
                if (image.Width <= dimensions.Width && image.Height <= dimensions.Height)
                {
                    drawingDimensions = new Rect((dimensions.Width - image.Width) / 2, (dimensions.Height - image.Height) / 2, image.Width, image.Height);
                }
                else if (renderRatio > aspectRatio)
                {
                    double scaledRenderWidth = (image.Width / image.Height) * dimensions.Width;
                    drawingDimensions = new Rect((dimensions.Width - scaledRenderWidth) / 2, 0, scaledRenderWidth, dimensions.Height);
                }
                else if (renderRatio < aspectRatio)
                {
                    double scaledRenderHeight = (image.Height / image.Width) * dimensions.Height;
                    drawingDimensions = new Rect(0, (dimensions.Height - scaledRenderHeight) / 2, dimensions.Width, scaledRenderHeight);
                }

                var            dv = new DrawingVisual();
                DrawingContext dc = dv.RenderOpen();
                dc.DrawImage(image, drawingDimensions);
                dc.Close();

                var bmp = new RenderTargetBitmap(( int )dimensions.Width, ( int )dimensions.Height, 96, 96, PixelFormats.Pbgra32);
                bmp.Render(dv);
                bf = BitmapFrame.Create(bmp);
            }

            // Using GDI+ to convert to an HICON.
            // I'd rather not duplicate their code.
            using (MemoryStream memstm = new MemoryStream())
            {
                BitmapEncoder enc = new PngBitmapEncoder();
                enc.Frames.Add(bf);
                enc.Save(memstm);

                using (var istm = new ManagedIStream(memstm))
                {
                    // We are not bubbling out GDI+ errors when creating the native image fails.
                    IntPtr bitmap = IntPtr.Zero;
                    try
                    {
                        Status gpStatus = NativeMethods.GdipCreateBitmapFromStream(istm, out bitmap);
                        if (Status.Ok != gpStatus)
                        {
                            return(IntPtr.Zero);
                        }

                        IntPtr hicon;
                        gpStatus = NativeMethods.GdipCreateHICONFromBitmap(bitmap, out hicon);
                        if (Status.Ok != gpStatus)
                        {
                            return(IntPtr.Zero);
                        }

                        // Caller is responsible for freeing this.
                        return(hicon);
                    }
                    finally
                    {
                        Utility.SafeDisposeImage(ref bitmap);
                    }
                }
            }
        }
Example #2
0
        public static IntPtr GenerateHICON(ImageSource image, Size dimensions)
        {
            if (image == null)
            {
                return(IntPtr.Zero);
            }
            BitmapFrame bitmapFrame = image as BitmapFrame;

            if (bitmapFrame != null)
            {
                bitmapFrame = Utility.GetBestMatch(bitmapFrame.Decoder.Frames, (int)dimensions.Width, (int)dimensions.Height);
            }
            else
            {
                Rect   rectangle = new Rect(0.0, 0.0, dimensions.Width, dimensions.Height);
                double num       = dimensions.Width / dimensions.Height;
                double num2      = image.Width / image.Height;
                if (image.Width <= dimensions.Width && image.Height <= dimensions.Height)
                {
                    rectangle = new Rect((dimensions.Width - image.Width) / 2.0, (dimensions.Height - image.Height) / 2.0, image.Width, image.Height);
                }
                else if (num > num2)
                {
                    double num3 = image.Width / image.Height * dimensions.Width;
                    rectangle = new Rect((dimensions.Width - num3) / 2.0, 0.0, num3, dimensions.Height);
                }
                else if (num < num2)
                {
                    double num4 = image.Height / image.Width * dimensions.Height;
                    rectangle = new Rect(0.0, (dimensions.Height - num4) / 2.0, dimensions.Width, num4);
                }
                DrawingVisual  drawingVisual  = new DrawingVisual();
                DrawingContext drawingContext = drawingVisual.RenderOpen();
                drawingContext.DrawImage(image, rectangle);
                drawingContext.Close();
                RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)dimensions.Width, (int)dimensions.Height, 96.0, 96.0, PixelFormats.Pbgra32);
                renderTargetBitmap.Render(drawingVisual);
                bitmapFrame = BitmapFrame.Create(renderTargetBitmap);
            }
            IntPtr result;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                new PngBitmapEncoder
                {
                    Frames =
                    {
                        bitmapFrame
                    }
                }.Save(memoryStream);
                using (ManagedIStream managedIStream = new ManagedIStream(memoryStream))
                {
                    IntPtr zero = IntPtr.Zero;
                    try
                    {
                        Status status = NativeMethods.GdipCreateBitmapFromStream(managedIStream, out zero);
                        if (status != Status.Ok)
                        {
                            result = IntPtr.Zero;
                        }
                        else
                        {
                            IntPtr intPtr;
                            status = NativeMethods.GdipCreateHICONFromBitmap(zero, out intPtr);
                            if (status != Status.Ok)
                            {
                                result = IntPtr.Zero;
                            }
                            else
                            {
                                result = intPtr;
                            }
                        }
                    }
                    finally
                    {
                        Utility.SafeDisposeImage(ref zero);
                    }
                }
            }
            return(result);
        }
Example #3
0
        private static SafeHBITMAP _CreateHBITMAPFromImageStream(Stream imgStream, out Size bitmapSize)
        {
            IWICImagingFactory    pImagingFactory = null;
            IWICBitmapDecoder     pDecoder        = null;
            IWICStream            pStream         = null;
            IWICBitmapFrameDecode pDecodedFrame   = null;
            IWICFormatConverter   pBitmapSourceFormatConverter = null;
            IWICBitmapFlipRotator pBitmapFlipRotator           = null;

            SafeHBITMAP hbmp = null;

            try
            {
                using (var istm = new ManagedIStream(imgStream))
                {
                    pImagingFactory = CLSID.CoCreateInstance <IWICImagingFactory>(CLSID.WICImagingFactory);
                    pStream         = pImagingFactory.CreateStream();
                    pStream.InitializeFromIStream(istm);

                    // Create an object that will decode the encoded image
                    Guid vendor = Guid.Empty;
                    pDecoder = pImagingFactory.CreateDecoderFromStream(pStream, ref vendor, WICDecodeMetadata.CacheOnDemand);

                    pDecodedFrame = pDecoder.GetFrame(0);
                    pBitmapSourceFormatConverter = pImagingFactory.CreateFormatConverter();

                    // Convert the image from whatever format it is in to 32bpp premultiplied alpha BGRA
                    Guid pixelFormat = WICPixelFormat.WICPixelFormat32bppPBGRA;
                    pBitmapSourceFormatConverter.Initialize(pDecodedFrame, ref pixelFormat, WICBitmapDitherType.None, IntPtr.Zero, 0, WICBitmapPaletteType.Custom);

                    pBitmapFlipRotator = pImagingFactory.CreateBitmapFlipRotator();
                    pBitmapFlipRotator.Initialize(pBitmapSourceFormatConverter, WICBitmapTransform.FlipVertical);

                    int width, height;
                    pBitmapFlipRotator.GetSize(out width, out height);

                    bitmapSize = new Size {
                        Width = width, Height = height
                    };

                    var bmi = new BITMAPINFO
                    {
                        bmiHeader = new BITMAPINFOHEADER
                        {
                            biSize        = Marshal.SizeOf(typeof(BITMAPINFOHEADER)),
                            biWidth       = width,
                            biHeight      = height,
                            biPlanes      = 1,
                            biBitCount    = 32,
                            biCompression = BI.RGB,
                            biSizeImage   = (width * height * 4),
                        },
                    };

                    // Create a 32bpp DIB.  This DIB must have an alpha channel for UpdateLayeredWindow to succeed.
                    IntPtr pBitmapBits;
                    hbmp = NativeMethods.CreateDIBSection(null, ref bmi, out pBitmapBits, IntPtr.Zero, 0);

                    // Copy the decoded image to the new buffer which backs the HBITMAP
                    var rect = new WICRect {
                        X = 0, Y = 0, Width = width, Height = height
                    };
                    pBitmapFlipRotator.CopyPixels(ref rect, width * 4, bmi.bmiHeader.biSizeImage, pBitmapBits);

                    var ret = hbmp;
                    hbmp = null;
                    return(ret);
                }
            }
            finally
            {
                Utility.SafeRelease(ref pImagingFactory);
                Utility.SafeRelease(ref pDecoder);
                Utility.SafeRelease(ref pStream);
                Utility.SafeRelease(ref pDecodedFrame);
                Utility.SafeRelease(ref pBitmapFlipRotator);
                Utility.SafeRelease(ref pBitmapSourceFormatConverter);
                Utility.SafeDispose(ref hbmp);
            }
        }
Example #4
0
        /// <summary>
        /// Utility to set a binary property on an INativeContactProperties.
        /// </summary>
        /// <param name="contact">The INativeContactProperties to set the value on.</param>
        /// <param name="propertyName">The property to set.</param>
        /// <param name="binary">The value to set to the property.</param>
        /// <param name="binaryType">The mime-type of the value being applied.</param>
        /// <returns>HRESULT.</returns>
        /// <remarks>
        /// This is a thin wrapper over the COM INativeContactProperties::SetBinary to make it more easily consumable
        /// in .Net.  Behavior and returned error codes should be similar to the native version.
        /// </remarks>
        public static HRESULT SetBinary(INativeContactProperties contact, string propertyName, string binaryType, Stream binary)
        {
            Verify.IsNotNull(contact, "contact");
            Verify.IsNotNull(propertyName, "propertyName");

            using (var mstream = new ManagedIStream(binary))
            {
                mstream.Seek(0, (int)SeekOrigin.Begin, IntPtr.Zero);
                return contact.SetBinary(propertyName, ContactValue.CGD_DEFAULT, binaryType, mstream);
            }
        }
Example #5
0
        public static IntPtr GenerateHICON(ImageSource image, Size dimensions)
        {
            if (image == null)
            {
                return IntPtr.Zero;
            }

            // If we're getting this from a ".ico" resource, then it comes through as a BitmapFrame.
            // We can use leverage this as a shortcut to get the right 16x16 representation
            // because DrawImage doesn't do that for us.
            var bf = image as BitmapFrame;
            if (bf != null)
            {
                bf = GetBestMatch(bf.Decoder.Frames, (int)dimensions.Width, (int)dimensions.Height);
            }
            else
            {
                // Constrain the dimensions based on the aspect ratio.
                var drawingDimensions = new Rect(0, 0, dimensions.Width, dimensions.Height);

                // There's no reason to assume that the requested image dimensions are square.
                double renderRatio = dimensions.Width / dimensions.Height;
                double aspectRatio = image.Width / image.Height;

                // If it's smaller than the requested size, then place it in the middle and pad the image.
                if (image.Width <= dimensions.Width && image.Height <= dimensions.Height)
                {
                    drawingDimensions = new Rect((dimensions.Width - image.Width) / 2, (dimensions.Height - image.Height) / 2, image.Width, image.Height);
                }
                else if (renderRatio > aspectRatio)
                {
                    double scaledRenderWidth = (image.Width / image.Height) * dimensions.Width;
                    drawingDimensions = new Rect((dimensions.Width - scaledRenderWidth) / 2, 0, scaledRenderWidth, dimensions.Height);
                }
                else if (renderRatio < aspectRatio)
                {
                    double scaledRenderHeight = (image.Height / image.Width) * dimensions.Height;
                    drawingDimensions = new Rect(0, (dimensions.Height - scaledRenderHeight) / 2, dimensions.Width, scaledRenderHeight);
                }

                var dv = new DrawingVisual();
                DrawingContext dc = dv.RenderOpen();
                dc.DrawImage(image, drawingDimensions);
                dc.Close();

                var bmp = new RenderTargetBitmap((int)dimensions.Width, (int)dimensions.Height, 96, 96, PixelFormats.Pbgra32);
                bmp.Render(dv);
                bf = BitmapFrame.Create(bmp);
            }

            // Using GDI+ to convert to an HICON.
            // I'd rather not duplicate their code.
            using (MemoryStream memstm = new MemoryStream())
            {
                BitmapEncoder enc = new PngBitmapEncoder();
                enc.Frames.Add(bf);
                enc.Save(memstm);

                using (var istm = new ManagedIStream(memstm))
                {
                    // We are not bubbling out GDI+ errors when creating the native image fails.
                    IntPtr bitmap = IntPtr.Zero;
                    try
                    {
                        Status gpStatus = NativeMethods.GdipCreateBitmapFromStream(istm, out bitmap);
                        if (Status.Ok != gpStatus)
                        {
                            return IntPtr.Zero;
                        }

                        IntPtr hicon;
                        gpStatus = NativeMethods.GdipCreateHICONFromBitmap(bitmap, out hicon);
                        if (Status.Ok != gpStatus)
                        {
                            return IntPtr.Zero;
                        }

                        // Caller is responsible for freeing this.
                        return hicon;
                    }
                    finally
                    {
                        Utility.SafeDisposeImage(ref bitmap);
                    }
                }
            }
        }
Example #6
0
        public static HRESULT CommitContact(IContact contact, bool force)
        {
			Verify.IsNotNull<IContact>(contact, "contact");

            HRESULT hr = contact.CommitChanges(ContactValue.CGD_DEFAULT);
            // If this failed because of conflicting changes then try going directly to the file at the caller's behest.
            if (force
                && ((HRESULT)Win32Error.ERROR_NESTING_NOT_ALLOWED == hr
                    || (HRESULT)Win32Error.ERROR_FILE_NOT_FOUND == hr))
            {
                string path;
                GetPath(contact, out path).ThrowIfFailed("Conflicting changes were encountered but an error occurred trying to bypass them.");
                using (FileStream fstream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
                {
                    using (ManagedIStream istream = new ManagedIStream(fstream))
                    {
                        ((IPersistStream)contact).Save(istream, true);
                        hr = HRESULT.S_OK;
                    }
                }
            }
            return hr;
        }
Example #7
0
        public static IntPtr GenerateHICON(ImageSource image, Size dimensions)
        {
            IntPtr intPtr;
            IntPtr zero;

            if (image == null)
            {
                return(IntPtr.Zero);
            }
            BitmapFrame bestMatch = image as BitmapFrame;

            if (bestMatch == null)
            {
                Rect   rect  = new Rect(0, 0, dimensions.Width, dimensions.Height);
                double width = dimensions.Width / dimensions.Height;
                double num   = image.Width / image.Height;
                if (image.Width <= dimensions.Width && image.Height <= dimensions.Height)
                {
                    rect = new Rect((dimensions.Width - image.Width) / 2, (dimensions.Height - image.Height) / 2, image.Width, image.Height);
                }
                else if (width > num)
                {
                    double width1 = image.Width / image.Height * dimensions.Width;
                    rect = new Rect((dimensions.Width - width1) / 2, 0, width1, dimensions.Height);
                }
                else if (width < num)
                {
                    double height = image.Height / image.Width * dimensions.Height;
                    rect = new Rect(0, (dimensions.Height - height) / 2, dimensions.Width, height);
                }
                DrawingVisual  drawingVisual  = new DrawingVisual();
                DrawingContext drawingContext = drawingVisual.RenderOpen();
                drawingContext.DrawImage(image, rect);
                drawingContext.Close();
                RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)dimensions.Width, (int)dimensions.Height, 96, 96, PixelFormats.Pbgra32);
                renderTargetBitmap.Render(drawingVisual);
                bestMatch = BitmapFrame.Create(renderTargetBitmap);
            }
            else
            {
                bestMatch = Utility.GetBestMatch(bestMatch.Decoder.Frames, (int)dimensions.Width, (int)dimensions.Height);
            }
            using (MemoryStream memoryStream = new MemoryStream())
            {
                BitmapEncoder pngBitmapEncoder = new PngBitmapEncoder();
                pngBitmapEncoder.Frames.Add(bestMatch);
                pngBitmapEncoder.Save(memoryStream);
                using (ManagedIStream managedIStream = new ManagedIStream(memoryStream))
                {
                    IntPtr zero1 = IntPtr.Zero;
                    try
                    {
                        if (Standard.NativeMethods.GdipCreateBitmapFromStream(managedIStream, out zero1) == Status.Ok)
                        {
                            zero = (Standard.NativeMethods.GdipCreateHICONFromBitmap(zero1, out intPtr) == Status.Ok ? intPtr : IntPtr.Zero);
                        }
                        else
                        {
                            zero = IntPtr.Zero;
                        }
                    }
                    finally
                    {
                        Utility.SafeDisposeImage(ref zero1);
                    }
                }
            }
            return(zero);
        }
Example #8
0
        public static IntPtr GenerateHICON(ImageSource image, Size dimensions)
        {
            IntPtr ptr3;

            if (image == null)
            {
                return(IntPtr.Zero);
            }
            BitmapFrame item = image as BitmapFrame;

            if (item != null)
            {
                item = GetBestMatch(item.Decoder.Frames, (int)dimensions.Width, (int)dimensions.Height);
            }
            else
            {
                Rect   rectangle = new Rect(0.0, 0.0, dimensions.Width, dimensions.Height);
                double num       = dimensions.Width / dimensions.Height;
                double num2      = image.Width / image.Height;
                if ((image.Width <= dimensions.Width) && (image.Height <= dimensions.Height))
                {
                    rectangle = new Rect((dimensions.Width - image.Width) / 2.0, (dimensions.Height - image.Height) / 2.0, image.Width, image.Height);
                }
                else if (num > num2)
                {
                    double width = (image.Width / image.Height) * dimensions.Width;
                    rectangle = new Rect((dimensions.Width - width) / 2.0, 0.0, width, dimensions.Height);
                }
                else if (num < num2)
                {
                    double height = (image.Height / image.Width) * dimensions.Height;
                    rectangle = new Rect(0.0, (dimensions.Height - height) / 2.0, dimensions.Width, height);
                }
                DrawingVisual  visual  = new DrawingVisual();
                DrawingContext context = visual.RenderOpen();
                context.DrawImage(image, rectangle);
                context.Close();
                RenderTargetBitmap source = new RenderTargetBitmap((int)dimensions.Width, (int)dimensions.Height, 96.0, 96.0, PixelFormats.Pbgra32);
                source.Render(visual);
                item = BitmapFrame.Create(source);
            }
            using (MemoryStream stream = new MemoryStream())
            {
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(item);
                encoder.Save(stream);
                using (ManagedIStream stream2 = new ManagedIStream(stream))
                {
                    IntPtr zero = IntPtr.Zero;
                    try
                    {
                        IntPtr ptr2;
                        if (Standard.NativeMethods.GdipCreateBitmapFromStream(stream2, out zero) != Standard.Status.Ok)
                        {
                            return(IntPtr.Zero);
                        }
                        if (Standard.NativeMethods.GdipCreateHICONFromBitmap(zero, out ptr2) != Standard.Status.Ok)
                        {
                            return(IntPtr.Zero);
                        }
                        ptr3 = ptr2;
                    }
                    finally
                    {
                        SafeDisposeImage(ref zero);
                    }
                }
            }
            return(ptr3);
        }
 public Stream SaveToStream()
 {
     var memstm = new MemoryStream();
     using (var istream = new ManagedIStream(memstm))
     {
         ((IPersistStream)_nativeContact).Save(istream, true);
     }
     return memstm;
 }
        private VistaContactProperties(Stream stream, bool ownsStream)
        {
            Verify.IsNotNull(stream, "stream");

            _nativeContact = new ContactRcw();

            var persistStream = (IPersistStream)_nativeContact;
            stream.Seek(0, SeekOrigin.Begin);

            // COM APIs may keep the stream and rely on using it later.
            // Managed callers are likely to call dispose on it, which destroys it.
            // Need to create a copy of the stream and keep it alive and unchanged
            // for the lifetime of this object.
            if (ownsStream)
            {
                // This is our own copy.  Don't need to dupe it.
                _streamCopy = stream;
            }
            else
            {
                _streamCopy = new MemoryStream();
                Utility.CopyStream(_streamCopy, stream);
            }
            _istreamCopy = new ManagedIStream(_streamCopy);

            HRESULT hr = persistStream.Load(_istreamCopy);
            if (HRESULT.WC_E_SYNTAX == hr || HRESULT.WC_E_GREATERTHAN == hr || Win32Error.ERROR_INVALID_DATATYPE == hr)
            {
                throw new InvalidDataException("The data stream is of an invalid format");
            }
            hr.ThrowIfFailed("An error occurred loading the contact");

            //_modified = false;
        }