Пример #1
0
        internal TextureLoader(DeviceResources deviceResources)
        {
            this.deviceResources = deviceResources;
            factory = new ImagingFactory2();

            textures = new Dictionary <string, Tuple <ShaderResourceView, Texture2D> >();
        }
Пример #2
0
        // 生成と終了


        /// <summary>
        ///		コンストラクタ。
        ///		指定された画像ファイルと矩形リストyamlファイルを使って、フォント画像を生成する。
        /// </summary>
        /// <param name="文字幅補正dpx">文字と文字の間の(横方向の)間隔。拡大率の影響は受けない。負数もOK。</param>
        /// <param name="不透明度">透明: 0 ~ 1 :不透明</param>
        public フォント画像D2D(ImagingFactory2 imagingFactory2, DeviceContext d2dDeviceContext, VariablePath 文字盤の画像ファイルパス, VariablePath 文字盤の矩形リストファイルパス, float 文字幅補正dpx = 0f, float 透明度 = 1f)
        {
            this._文字盤     = new 画像D2D(imagingFactory2, d2dDeviceContext, 文字盤の画像ファイルパス);
            this._矩形リスト   = new 矩形リスト(文字盤の矩形リストファイルパス);
            this.文字幅補正dpx = 文字幅補正dpx;
            this.透明度      = 透明度;
        }
 public void Dispose()
 {
     Device?.Dispose();
     Device = null;
     ImagingFactory2?.Dispose();
     ImagingFactory2 = null;
 }
        private static SharpDX.Direct2D1.Bitmap LoadBitmapFromContentFile(ImagingFactory2 imagingFactory, string filePath, RenderTarget renderTarget)
        {
            SharpDX.Direct2D1.Bitmap newBitmap;

            // Neccessary for creating WIC objects.

            //NativeFileStream fileStream = new NativeFileStream(filePath,
            //    NativeFileMode.Open, NativeFileAccess.Read);

            // Used to read the image source file.
            BitmapDecoder bitmapDecoder = new BitmapDecoder(imagingFactory, filePath, DecodeOptions.CacheOnDemand);

            // Get the first frame of the image.
            BitmapFrameDecode frame = bitmapDecoder.GetFrame(0);

            // Convert it to a compatible pixel format.
            FormatConverter converter = new FormatConverter(imagingFactory);

            converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA);

            // Create the new Bitmap1 directly from the FormatConverter.
            newBitmap = SharpDX.Direct2D1.Bitmap1.FromWicBitmap(renderTarget, converter);

            //Utilities.Dispose(ref bitmapDecoder);
            //Utilities.Dispose(ref fileStream);
            //Utilities.Dispose(ref imagingFactory);

            return(newBitmap);
        }
Пример #5
0
        public ImageLoader()
        {
            alphaThresholdPct = 0.0;

            factory      = new ImagingFactory2();
            fmtConverter = new FormatConverter(factory);
        }
 /// <summary>
 /// 将 Direct2D 位图保存到文件中。
 /// </summary>
 /// <param name="image">要保存的位图。</param>
 /// <param name="fileName">要保存的文件名。</param>
 public void SaveBitmapToFile(Bitmap image, string fileName)
 {
     using (ImagingFactory2 factory = new ImagingFactory2())
     {
         using (WICStream stream = new WICStream(factory, fileName, NativeFileAccess.Write))
         {
             using (BitmapEncoder encoder = new PngBitmapEncoder(factory))
             {
                 encoder.Initialize(stream);
                 using (BitmapFrameEncode bitmapFrameEncode = new BitmapFrameEncode(encoder))
                 {
                     bitmapFrameEncode.Initialize();
                     int width  = image.PixelSize.Width;
                     int height = image.PixelSize.Height;
                     bitmapFrameEncode.SetSize(width, height);
                     Guid wicPixelFormat = WICPixelFormat;
                     bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);
                     using (ImageEncoder imageEncoder = new ImageEncoder(factory, this.d2DDevice))
                     {
                         imageEncoder.WriteFrame(image, bitmapFrameEncode,
                                                 new ImageParameters(D2PixelFormat, 96, 96, 0, 0, width, height));
                         bitmapFrameEncode.Commit();
                         encoder.Commit();
                     }
                 }
             }
         }
     }
 }
Пример #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="factory"></param>
        /// <param name="filename"></param>
        /// <param name="resource">null の場合、ファイル読み込み、nullでない場合リソース読み込み。リソースの場合、呼び出し後解放されます</param>
        /// <returns></returns>
        protected static unsafe BitmapSource LoadDDS(ImagingFactory2 factory, string filename, Stream resource = null)
        {
            IScratchImage si;

            if (resource == null)
            {
                si = DirectXTexNet.DirectXTex.LoadFromDDSFile(filename, DDSFlags.FORCE_RGB);
            }
            else
            {
                si = DirectXTexNet.DirectXTex.LoadFromDDSResource(filename, DDSFlags.FORCE_RGB);
            }

            var bff = si.GetRawBytes(0, 0);

            SharpDX.WIC.Bitmap descBmp = null;

            fixed(byte *pBff = bff)
            {
                descBmp = new SharpDX.WIC.Bitmap(
                    factory,
                    (int)si.MetaData.width, (int)si.MetaData.height,
                    SharpDX.WIC.PixelFormat.Format32bppPRGBA,
                    new DataRectangle((IntPtr)pBff, (int)si.MetaData.width * 4));
            }

            return(descBmp);
        }
        /// <summary>
        /// Заргуражет писели из картинки
        /// </summary>
        /// <param name="device">Устройство с помощью которого будет рисоваться эта картинка</param>
        /// <param name="filename">Путь к файлу с картинкой</param>
        /// <returns>Набор пикселей</returns>
        public static BitmapSource LoadBitmapSource(SharpDX.Direct3D11.DeviceContext device, string filename)
        {
            var    pFormat = SharpDX.WIC.PixelFormat.Format32bppPRGBA;
            string ext     = System.IO.Path.GetExtension(filename);

            if (ext.ToLower() == ".dds")
            {
                pFormat = SharpDX.WIC.PixelFormat.Format32bppRGBA;
            }
            using (var Imgfactory = new ImagingFactory2())
                using (var d = new BitmapDecoder(
                           Imgfactory,
                           filename,
                           DecodeOptions.CacheOnDemand
                           ))
                    using (var frame = d.GetFrame(0))
                    {
                        var fconv = new FormatConverter(Imgfactory);
                        fconv.Initialize(
                            frame,
                            pFormat,
                            BitmapDitherType.None, null,
                            0.0, BitmapPaletteType.Custom);
                        return(fconv);
                    }
        }
Пример #9
0
        public static Texture2D LoadTexture2D(Device device, string fileName)
        {
            var factory      = new ImagingFactory2();
            var bitmapSource = LoadBitmap(factory, fileName);

            factory.Dispose();
            int stride = bitmapSource.Size.Width * 4;

            using (var buffer = new DataStream(bitmapSource.Size.Height * stride, true, true)) {
                bitmapSource.CopyPixels(stride, buffer);
                var texture = new Texture2D(device, new Texture2DDescription {
                    Width             = bitmapSource.Size.Width,
                    Height            = bitmapSource.Size.Height,
                    ArraySize         = 1,
                    BindFlags         = BindFlags.ShaderResource,
                    Usage             = ResourceUsage.Immutable,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    Format            = Format.R8G8B8A8_UNorm,
                    MipLevels         = 1,
                    OptionFlags       = ResourceOptionFlags.None,
                    SampleDescription = new SampleDescription(1, 0)
                }, new DataRectangle(buffer.DataPointer, stride));
                bitmapSource.Dispose();
                return(texture);
            }
        }
Пример #10
0
        static byte[] CreateRaw(IntPtr pixels, int width, int height)
        {
            using (var bitmap = new System.Drawing.Bitmap(width, height, width * 4, System.Drawing.Imaging.PixelFormat.Format32bppArgb, pixels))
            {
                using (var stream = new MemoryStream())
                {
                    bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);

                    var factory = new ImagingFactory2();
                    using (var decoder = new BitmapDecoder(factory, stream, DecodeOptions.CacheOnDemand))
                    {
                        using (var formatConverter = new FormatConverter(factory))
                        {
                            formatConverter.Initialize(decoder.GetFrame(0), PixelFormat.Format32bppPRGBA);

                            var stride = formatConverter.Size.Width * 4;
                            using (var dataStream = new SharpDX.DataStream(formatConverter.Size.Height * stride, true, true))
                            {
                                formatConverter.CopyPixels(stride, dataStream);

                                byte[] b;

                                using (BinaryReader br = new BinaryReader(dataStream))
                                {
                                    b = br.ReadBytes((int)dataStream.Length);
                                }

                                return(b);
                            }
                        }
                    }
                }
            }
        }
Пример #11
0
        public BitmapSource LoadBitmap(ImagingFactory2 factory, string filename)
        {
            var bitmapDecoder   = new BitmapDecoder(factory, filename, DecodeOptions.CacheOnDemand);
            var formatConverter = new FormatConverter(factory);

            formatConverter.Initialize(bitmapDecoder.GetFrame(0), PixelFormat.Format32bppPRGBA, BitmapDitherType.None, null, 0.0, BitmapPaletteType.Custom);
            return(formatConverter);
        }
        /// <inheritdoc />
        /// <summary>
        ///   Creates a single bitmap from the captured frames and returns an object with its information
        /// </summary>
        /// <returns>
        ///   A <see cref="VideoFrame" /> instance that can be either a <see cref="D3D11VideoFrame"/> or
        ///   a <see cref="BitmapVideoFrame" />
        /// </returns>
        public override VideoFrame LockFrame()
        {
            long presentTimeTicks = (long)(this.lastPresentTime * 10e6 / this.perfFreq);

            if (this.sources.Length == 1 && this.sources.First().Alive)
            {
                // TODO: if multiple textures are owned by a single adapter, merge them using CopySubresourceRegion
                return(new D3D11VideoFrame(this.sources[0].Texture, presentTimeTicks));
            }

            using (var factory = new ImagingFactory2()) {
                // create Bitmap but DON'T dispose it here
                var bmp = new Bitmap(factory,
                                     this.virtualRect.Width,
                                     this.virtualRect.Height,
                                     PixelFormat.Format32bppBGRA,
                                     BitmapCreateCacheOption.CacheOnDemand);

                // caller is responsible for disposing BitmapLock
                BitmapLock data = bmp.Lock(BitmapLockFlags.Write);
                int        minX = this.sources.Select(s => s.Region.Left).Min();
                int        minY = this.sources.Select(s => s.Region.Top).Min();

                // map textures
                foreach (DxgiCaptureSource source in this.sources)
                {
                    using (var res = source.Texture.QueryInterface <SharpDX.Direct3D11.Resource>()) {
                        DataBox map = source.Device.ImmediateContext.MapSubresource(res, 0, MapMode.Read, MapFlags.None);

                        // merge partial captures into one big bitmap
                        IntPtr dstScan0  = data.Data.DataPointer,
                               srcScan0  = map.DataPointer;
                        int dstStride    = data.Stride,
                            srcStride    = map.RowPitch;
                        int srcWidth     = source.Region.Right - source.Region.Left,
                            srcHeight    = source.Region.Bottom - source.Region.Top;
                        int dstPixelSize = dstStride / data.Size.Width,
                            srcPixelSize = srcStride / srcWidth;
                        int dstX         = source.Region.Left - minX,
                            dstY         = source.Region.Top - minY;

                        for (int y = 0; y < srcHeight; y++)
                        {
                            Utilities.CopyMemory(IntPtr.Add(dstScan0, dstPixelSize * dstX + (y + dstY) * dstStride),
                                                 IntPtr.Add(srcScan0, y * srcStride), srcPixelSize * srcWidth);
                        }

                        // release system memory
                        source.Device.ImmediateContext.UnmapSubresource(res, 0);
                    }
                }

                // return locked bitmap frame
                return(new BitmapVideoFrame(bmp, data, presentTimeTicks));
            }
        }
Пример #13
0
        /// <inheritdoc />
        /// <summary>
        ///   Creates a single bitmap from the captured frames and returns an object with its information
        /// </summary>
        /// <returns>A <see cref="BitmapData" /> containing raw bitmap information</returns>
        public BitmapData LockFrameBitmap()
        {
            using (var factory = new ImagingFactory2()) {
                using (var bmp = new Bitmap(factory,
                                            CaptureBounds.Width,
                                            CaptureBounds.Height,
                                            PixelFormat.Format32bppBGRA,
                                            BitmapCreateCacheOption.CacheOnDemand)) {
                    // caller is responsible for disposing BitmapLock
                    BitmapLock data = bmp.Lock(BitmapLockFlags.Write);
                    int        minX = this.rects.Select(b => b.X).Min();
                    int        minY = this.rects.Select(b => b.Y).Min();

                    // map textures
                    for (int i = 0; i < StagingTextures.Length; i++)
                    {
                        DataBox map = StagingTextures[i]
                                      .Device.ImmediateContext
                                      .MapSubresource(StagingTextures[i], 0, MapMode.Read, MapFlags.None);

                        IntPtr dstScan0 = data.Data.DataPointer,
                               srcScan0 = map.DataPointer;

                        int dstStride    = data.Stride,
                            srcStride    = map.RowPitch;
                        int srcWidth     = this.rects[i].Width,
                            srcHeight    = this.rects[i].Height;
                        int dstPixelSize = dstStride / data.Size.Width,
                            srcPixelSize = srcStride / srcWidth;
                        int dstX         = this.rects[i].X - minX,
                            dstY         = this.rects[i].Y - minY;

                        for (int y = 0; y < srcHeight; y++)
                        {
                            Utilities.CopyMemory(IntPtr.Add(dstScan0,
                                                            dstPixelSize * dstX + (y + dstY) * dstStride),
                                                 IntPtr.Add(srcScan0, y * srcStride),
                                                 srcPixelSize * srcWidth);
                        }

                        StagingTextures[i].Device.ImmediateContext.UnmapSubresource(StagingTextures[i], 0);
                    }

                    return(new BitmapData {
                        Width = CaptureBounds.Width,
                        Height = CaptureBounds.Height,
                        PixelFormat = bmp.PixelFormat,
                        Scan0 = data.Data.DataPointer,
                        Stride = data.Stride,
                        LockPointer = data.NativePointer
                    });
                }
            }
        }
Пример #14
0
        /// <summary>
        /// Reads a bitmap a file
        /// </summary>
        /// <param name="filename">File name</param>
        /// <returns>Returns the bitmap source</returns>
        private static BitmapSource ReadBitmap(string filename)
        {
            using (var factory = new ImagingFactory2())
            {
                var bitmapDecoder = new BitmapDecoder(factory, filename, DecodeOptions.CacheOnLoad);

                var formatConverter = new FormatConverter(factory);

                formatConverter.Initialize(
                    bitmapDecoder.GetFrame(0),
                    PixelFormat.Format32bppPRGBA,
                    BitmapDitherType.None,
                    null,
                    0.0,
                    BitmapPaletteType.Custom);

                return(formatConverter);
            }
        }
Пример #15
0
        private void Initialize()
        {
            _d2dFactory   = new SharpDX.Direct2D1.Factory1();
            DWriteFactory = new SharpDX.DirectWrite.Factory1();
            WicFactory    = new ImagingFactory2();

            DevicePixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied);
            ImagePixelFormat  = SharpDX.WIC.PixelFormat.Format32bppPRGBA;
            using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport))
                using (var d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>())
                    using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device2>())
                    {
                        _d2dDevice    = new SharpDX.Direct2D1.Device(_d2dFactory, dxgiDevice);
                        DeviceContext = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, new DeviceContextOptions());
                    }

            WicImageEncoder = new ImageEncoder(WicFactory, _d2dDevice);
            DeviceContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;
        }
        public static SharpDX.WIC.BitmapSource LoadBitmap(ImagingFactory2 factory, string ImageFilePath)
        {
            var bitmapDecoder = new BitmapDecoder(
                factory,
                ImageFilePath,
                DecodeOptions.CacheOnDemand
                );

            var formatConverter = new FormatConverter(factory);

            formatConverter.Initialize(
                bitmapDecoder.GetFrame(0),
                SharpDX.WIC.PixelFormat.Format32bppPRGBA,
                BitmapDitherType.None,
                null,
                0.0,
                BitmapPaletteType.Custom);

            return(formatConverter);
        }
        public static BitmapSource LoadBitmap(ImagingFactory2 factory, string filename)
        {
            var bitmapDecoder = new SharpDX.WIC.BitmapDecoder(
                factory,
                filename,
                SharpDX.WIC.DecodeOptions.CacheOnDemand
                );

            var result = new SharpDX.WIC.FormatConverter(factory);

            result.Initialize(
                bitmapDecoder.GetFrame(0),
                SharpDX.WIC.PixelFormat.Format32bppPRGBA,
                SharpDX.WIC.BitmapDitherType.None,
                null,
                0.0,
                SharpDX.WIC.BitmapPaletteType.Custom);

            return(result);
        }
Пример #18
0
        /// <summary>
        /// Creates the client adn initializes the members that will request a Twitter authorization and
        /// perform search tasks.
        /// </summary>
        /// <param name="device">DirectX device.</param>
        /// <param name="factory">Imaging factory.</param>
        public TwitterClient(Device1 device, ImagingFactory2 factory)
        {
            this.authorizer = new WinRtAuthorizer()
            {
                Credentials = new LocalDataCredentials()
                {
#error Please create an application in Twitter and set your own consumer key and secret.
                    ConsumerKey    = null,
                    ConsumerSecret = null,
                },
                UseCompression = true,
                Callback       = new Uri("http://followercatcher.codeplex.com/"),
            };

            this.device         = device;
            this.factory        = factory;
            this.AvatarTextures = new List <Texture>();
            this.Tweets         = new Dictionary <string, TweetInfo>();

            LoadTexturesFromCache();
        }
 public static byte[] LoadBytesFormFile(SharpDX.Direct3D11.DeviceContext device, string filename)
 {
     using (var Imgfactory = new ImagingFactory2())
         using (var d = new BitmapDecoder(
                    Imgfactory,
                    filename,
                    DecodeOptions.CacheOnDemand
                    ))
             using (var frame = d.GetFrame(0))
                 using (var fconv = new FormatConverter(Imgfactory))
                 {
                     fconv.Initialize(
                         frame,
                         SharpDX.WIC.PixelFormat.Format32bppPRGBA,
                         BitmapDitherType.None, null,
                         0.0, BitmapPaletteType.Custom);
                     var b = new byte[fconv.Size.Width * fconv.Size.Height * 4];
                     fconv.CopyPixels(b, fconv.Size.Width * 4);
                     return(b);
                 }
 }
Пример #20
0
        /// <summary>
        /// Import texture for DirectX11 renderer
        /// </summary>
        /// <param name="device"> DirectX11 target rendering device </param>
        /// <param name="TexturePath"> Source path for the texture </param>
        internal static Texture2D BitmapToDX11Texture(SharpDX.Direct3D11.Device device, string TexturePath)
        {
            ImagingFactory2 Fac = new ImagingFactory2();

            BitmapDecoder bitmapDecoder = new BitmapDecoder(Fac, TexturePath, DecodeOptions.CacheOnDemand
                                                            );

            FormatConverter formatConverter = new FormatConverter(Fac);

            formatConverter.Initialize(
                bitmapDecoder.GetFrame(0),
                PixelFormat.Format32bppPRGBA,
                BitmapDitherType.None,
                null,
                0.0,
                BitmapPaletteType.Custom);

            using (var buffer = new DataStream(formatConverter.Size.Height * formatConverter.Size.Width * 4, true, true))
            {
                formatConverter.CopyPixels(formatConverter.Size.Width * 4, buffer);

                return(new Texture2D(device, new Texture2DDescription()
                {
                    Width = formatConverter.Size.Width,
                    Height = formatConverter.Size.Height,
                    ArraySize = 1,
                    BindFlags = BindFlags.ShaderResource,
                    Usage = ResourceUsage.Immutable,
                    CpuAccessFlags = CpuAccessFlags.None,
                    Format = Format.R8G8B8A8_UNorm,
                    MipLevels = 1,
                    OptionFlags = ResourceOptionFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                }, new DataRectangle(buffer.DataPointer, formatConverter.Size.Width * 4)));
            }
        }
Пример #21
0
        public async Task <System.IO.MemoryStream> RenderLabelToStream(
            float imageWidth,
            float imageHeight,
            Color4 foregroundColor,
            Vector2 origin,
            TextLayout textLayout,
            float dpi = DEFAULT_DPI,
            SharpDX.DXGI.Format format        = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
            SharpDX.Direct2D1.AlphaMode alpha = AlphaMode.Premultiplied)
        {
            // Get stream
            var pngStream = new MemoryStream();

            using (var renderTarget = RenderLabel(
                       imageWidth,
                       imageHeight,
                       foregroundColor,
                       origin,
                       textLayout,
                       dpi,
                       format,
                       alpha))
            {
                pngStream.Position = 0;

                // Create a WIC outputstream
                using (var wicStream = new WICStream(FactoryImaging, pngStream))
                {
                    var size = renderTarget.PixelSize;

                    // Initialize a Png encoder with this stream
                    using (var wicBitmapEncoder = new PngBitmapEncoder(FactoryImaging, wicStream))
                    {
                        // Create a Frame encoder
                        using (var wicFrameEncoder = new BitmapFrameEncode(wicBitmapEncoder))
                        {
                            wicFrameEncoder.Initialize();

                            // Create image encoder
                            ImageEncoder    wicImageEncoder;
                            ImagingFactory2 factory2 = new ImagingFactory2();
                            wicImageEncoder = new ImageEncoder(factory2, D2DDevice);


                            var imgParams = new ImageParameters();
                            imgParams.PixelFormat =
                                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                                                                  AlphaMode.Premultiplied);

                            imgParams.PixelHeight = (int)size.Height;
                            imgParams.PixelWidth  = (int)size.Width;

                            wicImageEncoder.WriteFrame(renderTarget, wicFrameEncoder, imgParams);

                            //// Commit changes
                            wicFrameEncoder.Commit();
                            wicBitmapEncoder.Commit();

                            byte[] buffer = new byte[pngStream.Length];
                            pngStream.Position = 0;
                            await pngStream.ReadAsync(buffer, 0, (int)pngStream.Length);
                        }
                    }
                }
            }

            return(pngStream);
        }
Пример #22
0
 /// <summary>
 /// Creates a new image encoder object.
 /// </summary>
 /// <param name="factory">The WIC factory.</param>
 /// <param name="d2dDevice">The <see cref="Direct2D1.Device" /> object on which the corresponding image encoder is created.</param>
 /// <msdn-id>hh880849</msdn-id>
 ///   <unmanaged>HRESULT IWICImagingFactory2::CreateImageEncoder([In] ID2D1Device* pD2DDevice,[In] IWICImageEncoder** ppWICImageEncoder)</unmanaged>
 ///   <unmanaged-short>IWICImagingFactory2::CreateImageEncoder</unmanaged-short>
 public ImageEncoder(ImagingFactory2 factory, Direct2D1.Device d2dDevice)
 {
     factory.CreateImageEncoder(d2dDevice, this);
 }
Пример #23
0
        private void SaveToFile(D3DX direct3D, Texture2D texture, Guid format)
        {
            var stream        = new System.IO.FileStream("Output.png", System.IO.FileMode.Create);
            var textureTarget = texture;
            var textureCopy   = new Texture2D(direct3D.Device, new Texture2DDescription
            {
                Width             = (int)textureTarget.Description.Width,
                Height            = (int)textureTarget.Description.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = textureTarget.Description.Format,
                Usage             = ResourceUsage.Staging,
                SampleDescription = new SampleDescription(1, 0),
                BindFlags         = BindFlags.None,
                CpuAccessFlags    = CpuAccessFlags.Read,
                OptionFlags       = ResourceOptionFlags.None
            });

            direct3D.DeviceContext.CopyResource(textureTarget, textureCopy);

            var dataBox = direct3D.DeviceContext.MapSubresource(
                textureCopy,
                0,
                0,
                MapMode.Read,
                SharpDX.Direct3D11.MapFlags.None,
                out DataStream dataStream);

            var dataRectangle = new DataRectangle
            {
                DataPointer = dataStream.DataPointer,
                Pitch       = dataBox.RowPitch
            };

            var imagingFactory = new ImagingFactory2();
            var bitmap         = new SharpDX.WIC.Bitmap(
                imagingFactory,
                textureCopy.Description.Width,
                textureCopy.Description.Height,
                format,
                dataRectangle);

            using (var s = stream)
            {
                s.Position = 0;
                using (var bitmapEncoder = new PngBitmapEncoder(imagingFactory, s))
                {
                    using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder))
                    {
                        bitmapFrameEncode.Initialize();
                        bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
                        var pixelFormat = SharpDX.WIC.PixelFormat.FormatDontCare;
                        bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
                        bitmapFrameEncode.WriteSource(bitmap);
                        bitmapFrameEncode.Commit();
                        bitmapEncoder.Commit();
                        bitmapFrameEncode.Dispose();
                        bitmapEncoder.Dispose();
                    }
                }
            }

            direct3D.DeviceContext.UnmapSubresource(textureCopy, 0);
            textureCopy.Dispose();
            bitmap.Dispose();
            imagingFactory.Dispose();
            dataStream.Dispose();
            stream.Dispose();
        }
Пример #24
0
        public bool GetThumbnail(Stream stream, int width, int height, bool cachedOnly, out byte[] imageData, out ImageType imageType)
        {
            imageData = null;
            imageType = ImageType.Unknown;
            // No support for cache
            if (cachedOnly)
            {
                return(false);
            }

            try
            {
                if (stream.CanSeek)
                {
                    stream.Seek(0, SeekOrigin.Begin);
                }

                // open the image file for reading
                using (var factory = new ImagingFactory2())
                    using (var inputStream = new WICStream(factory, stream))
                        using (var decoder = new BitmapDecoder(factory, inputStream, DecodeOptions.CacheOnLoad))
                            using (var scaler = new BitmapScaler(factory))
                                using (var output = new MemoryStream())
                                    using (var encoder = new BitmapEncoder(factory, ContainerFormatGuids.Jpeg))
                                    {
                                        // decode the loaded image to a format that can be consumed by D2D
                                        BitmapSource source = decoder.GetFrame(0);

                                        // Scale down larger images
                                        int sourceWidth  = source.Size.Width;
                                        int sourceHeight = source.Size.Height;
                                        if (width > 0 && height > 0 && (sourceWidth > width || sourceHeight > height))
                                        {
                                            if (sourceWidth <= height)
                                            {
                                                width = sourceWidth;
                                            }

                                            int newHeight = sourceHeight * height / sourceWidth;
                                            if (newHeight > height)
                                            {
                                                // Resize with height instead
                                                width     = sourceWidth * height / sourceHeight;
                                                newHeight = height;
                                            }

                                            scaler.Initialize(source, width, newHeight, BitmapInterpolationMode.Fant);
                                            source = scaler;
                                        }
                                        encoder.Initialize(output);

                                        using (var bitmapFrameEncode = new BitmapFrameEncode(encoder))
                                        {
                                            // Create image encoder
                                            var wicPixelFormat = PixelFormat.FormatDontCare;
                                            bitmapFrameEncode.Initialize();
                                            bitmapFrameEncode.SetSize(source.Size.Width, source.Size.Height);
                                            bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);
                                            bitmapFrameEncode.WriteSource(source);
                                            bitmapFrameEncode.Commit();
                                            encoder.Commit();
                                        }
                                        imageData = output.ToArray();
                                        imageType = ImageType.Jpeg;
                                        return(true);
                                    }
            }
            catch (Exception e)
            {
                // ServiceRegistration.Get<ILogger>().Warn("WICThumbnailProvider: Error loading bitmapSource from file data stream", e);
                return(false);
            }
        }
Пример #25
0
        /// <inheritdoc />
        /// <summary>
        ///   Creates a single bitmap from the captured frames and returns an object with its information
        /// </summary>
        /// <returns>A <see cref="BitmapData" /> containing raw bitmap information</returns>
        public override BitmapData LockFrameBitmap()
        {
            using (var factory
                       = new ImagingFactory2()) {
                var bmp
                    = new Bitmap(factory,
                                 CaptureBounds.Width,
                                 CaptureBounds.Height,
                                 PixelFormat.Format32bppBGRA,
                                 BitmapCreateCacheOption.CacheOnDemand);

                // caller is responsible for disposing BitmapLock
                BitmapLock data
                    = bmp.Lock(BitmapLockFlags.Write);
                int minX
                    = this.rects.Select(b => b.X).Min();
                int minY
                    = this.rects.Select(b => b.Y).Min();

                // map textures
                for (int i
                         = 0; i < Surfaces.Length; i++)
                {
                    DataRectangle map
                        = Surfaces[i].LockRectangle(LockFlags.ReadOnly);
                    IntPtr dstScan0
                        = data.Data.DataPointer,
                           srcScan0
                        = map.DataPointer;

                    int dstStride
                        = data.Stride,
                        srcStride
                        = map.Pitch;
                    int srcWidth
                        = this.regions[i].Width,
                        srcHeight
                        = this.regions[i].Height;
                    int dstPixelSize
                        = dstStride / data.Size.Width,
                        srcPixelSize
                        = srcStride / srcWidth;
                    int dstX
                        = this.rects[i].X - minX,
                        dstY
                        = this.rects[i].Y - minY;

                    for (int y
                             = 0; y < srcHeight; y++)
                    {
                        Utilities.CopyMemory(IntPtr.Add(dstScan0,
                                                        dstPixelSize * dstX + (y + dstY) * dstStride),
                                             IntPtr.Add(srcScan0, y * srcStride),
                                             srcPixelSize * srcWidth);
                    }

                    Surfaces[i].UnlockRectangle();
                }

                return(new BitmapData {
                    Width
                        = CaptureBounds.Width,
                    Height
                        = CaptureBounds.Height,
                    PixelFormat
                        = bmp.PixelFormat,
                    Scan0
                        = data.Data.DataPointer,
                    Stride
                        = data.Stride,
                    LockPointer
                        = data.NativePointer
                });
            }
        }
Пример #26
0
 /// <summary>
 /// Creates a new image encoder object.
 /// </summary>
 /// <param name="factory">The WIC factory.</param>
 /// <param name="d2dDevice">The <see cref="Direct2D1.Device" /> object on which the corresponding image encoder is created.</param>
 /// <msdn-id>hh880849</msdn-id>
 ///   <unmanaged>HRESULT IWICImagingFactory2::CreateImageEncoder([In] ID2D1Device* pD2DDevice,[In] IWICImageEncoder** ppWICImageEncoder)</unmanaged>
 ///   <unmanaged-short>IWICImagingFactory2::CreateImageEncoder</unmanaged-short>
 public ImageEncoder(ImagingFactory2 factory, Direct2D1.Device d2dDevice)
 {
     factory.CreateImageEncoder(d2dDevice, this);
 }
Пример #27
0
        public bool GetThumbnail(Stream stream, int width, int height, bool cachedOnly, out byte[] imageData, out ImageType imageType)
        {
            imageData = null;
            imageType = ImageType.Unknown;
            // No support for cache
            if (cachedOnly)
            {
                return(false);
            }

            Bitmap cachedBitmap = null; // used only for rotation

            try
            {
                if (stream.CanSeek)
                {
                    stream.Seek(0, SeekOrigin.Begin);
                }

                // open the image file for reading
                using (var factory = new ImagingFactory2())
                    using (var inputStream = new WICStream(factory, stream))
                        using (var decoder = new BitmapDecoder(factory, inputStream, DecodeOptions.CacheOnLoad))
                            using (var rotator = new BitmapFlipRotator(factory))
                                using (var scaler = new BitmapScaler(factory))
                                    using (var output = new MemoryStream())
                                    {
                                        // decode the loaded image to a format that can be consumed by D2D
                                        BitmapSource source = decoder.GetFrame(0);

                                        // Prefer PNG output for source PNG and for source formats with Alpha channel
                                        var usePngOutput = decoder.DecoderInfo.FriendlyName.StartsWith("PNG") || PixelFormat.GetBitsPerPixel(source.PixelFormat) == 32;

                                        BitmapTransformOptions bitmapTransformationOptions = BitmapTransformOptions.Rotate0;
                                        BitmapFrameDecode      frame = source as BitmapFrameDecode;
                                        if (frame != null)
                                        {
                                            const string EXIF_ORIENTATION_TAG = "/app1/{ushort=0}/{ushort=274}";
                                            ushort?      orientation          = null;
                                            try
                                            {
                                                // Not supported on all input types, i.e. BMP will fail here
                                                orientation = (ushort?)frame.MetadataQueryReader.TryGetMetadataByName(EXIF_ORIENTATION_TAG); //0x0112
                                            }
                                            catch { }

                                            // If the EXIF orientation specifies that the image needs to be flipped or rotated before display, set that up to happen
                                            if (orientation.HasValue)
                                            {
                                                switch (orientation.Value)
                                                {
                                                case 1: break; // No rotation required.

                                                case 2: bitmapTransformationOptions = BitmapTransformOptions.Rotate0 | BitmapTransformOptions.FlipHorizontal; break;

                                                case 3: bitmapTransformationOptions = BitmapTransformOptions.Rotate180; break;

                                                case 4: bitmapTransformationOptions = BitmapTransformOptions.Rotate180 | BitmapTransformOptions.FlipHorizontal; break;

                                                case 5: bitmapTransformationOptions = BitmapTransformOptions.Rotate270 | BitmapTransformOptions.FlipHorizontal; break;

                                                case 6: bitmapTransformationOptions = BitmapTransformOptions.Rotate90; break;

                                                case 7: bitmapTransformationOptions = BitmapTransformOptions.Rotate90 | BitmapTransformOptions.FlipHorizontal; break;

                                                case 8: bitmapTransformationOptions = BitmapTransformOptions.Rotate270; break;
                                                }
                                            }
                                        }

                                        // Scale down larger images
                                        int sourceWidth  = source.Size.Width;
                                        int sourceHeight = source.Size.Height;
                                        if (width > 0 && height > 0 && (sourceWidth > width || sourceHeight > height))
                                        {
                                            if (sourceWidth <= height)
                                            {
                                                width = sourceWidth;
                                            }

                                            int newHeight = sourceHeight * height / sourceWidth;
                                            if (newHeight > height)
                                            {
                                                // Resize with height instead
                                                width     = sourceWidth * height / sourceHeight;
                                                newHeight = height;
                                            }

                                            scaler.Initialize(source, width, newHeight, BitmapInterpolationMode.Fant);
                                            source = scaler;
                                        }

                                        // Rotate
                                        if (bitmapTransformationOptions != BitmapTransformOptions.Rotate0)
                                        {
                                            // For fast rotation a cached bitmap is needed, otherwise only per-pixel-decoding happens which makes the process extremly slow.
                                            // See https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/5ff2b52b-602f-4b22-9fb2-371539ff5ebb/hang-in-createbitmapfromwicbitmap-when-using-iwicbitmapfliprotator?forum=windowswic
                                            cachedBitmap = new Bitmap(factory, source, BitmapCreateCacheOption.CacheOnLoad);
                                            rotator.Initialize(cachedBitmap, bitmapTransformationOptions);
                                            source = rotator;
                                        }

                                        Guid formatGuid = ContainerFormatGuids.Jpeg;
                                        imageType = ImageType.Jpeg;

                                        if (usePngOutput)
                                        {
                                            formatGuid = ContainerFormatGuids.Png;
                                            imageType  = ImageType.Png;
                                        }

                                        using (var encoder = new BitmapEncoder(factory, formatGuid))
                                        {
                                            encoder.Initialize(output);
                                            using (var bitmapFrameEncode = new BitmapFrameEncode(encoder))
                                            {
                                                // Create image encoder
                                                var wicPixelFormat = PixelFormat.FormatDontCare;
                                                bitmapFrameEncode.Initialize();
                                                bitmapFrameEncode.SetSize(source.Size.Width, source.Size.Height);
                                                bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);
                                                bitmapFrameEncode.WriteSource(source);
                                                bitmapFrameEncode.Commit();
                                                encoder.Commit();
                                            }
                                        }
                                        imageData = output.ToArray();
                                        return(true);
                                    }
            }
            catch (Exception)
            {
                //ServiceRegistration.Get<ILogger>().Warn("WICThumbnailProvider: Error loading bitmapSource from file data stream", ex);
                return(false);
            }
            finally
            {
                cachedBitmap?.Dispose();
            }
        }
Пример #28
0
        protected void Bitmapを生成する(ImagingFactory2 imagingFactory2, DeviceContext d2dDeviceContext, VariablePath 画像ファイルパス, BitmapProperties1?bitmapProperties1 = null)
        {
            var decoder     = (BitmapDecoder?)null;
            var sourceFrame = (BitmapFrameDecode?)null;
            var converter   = (FormatConverter?)null;

            try
            {
                // 以下、生成に失敗しても例外は発生しない。ただ描画メソッドで表示されなくなるだけ。

                #region " 事前チェック。"
                //-----------------
                if (string.IsNullOrEmpty(画像ファイルパス.数なしパス))
                {
                    Log.ERROR($"画像ファイルパスが null または空文字列です。[{画像ファイルパス.変数付きパス}]");
                    return;
                }
                if (!File.Exists(画像ファイルパス.数なしパス))
                {
                    Log.ERROR($"画像ファイルが存在しません。[{画像ファイルパス.変数付きパス}]");
                    return;
                }
                //-----------------
                #endregion

                #region " 画像ファイルに対応できるデコーダを見つける。"
                //-----------------
                try
                {
                    decoder = new BitmapDecoder(
                        imagingFactory2,
                        画像ファイルパス.数なしパス,
                        NativeFileAccess.Read,
                        DecodeOptions.CacheOnLoad);
                }
                catch (SharpDXException e)
                {
                    Log.ERROR($"画像ファイルに対応するコーデックが見つかりません。(0x{e.HResult:x8})[{画像ファイルパス.変数付きパス}]");
                    return;
                }
                //-----------------
                #endregion

                #region " 最初のフレームをデコードし、取得する。"
                //-----------------
                try
                {
                    sourceFrame = decoder.GetFrame(0);
                }
                catch (SharpDXException e)
                {
                    Log.ERROR($"画像ファイルの最初のフレームのデコードに失敗しました。(0x{e.HResult:x8})[{画像ファイルパス.変数付きパス}]");
                    return;
                }
                //-----------------
                #endregion

                #region " 32bitPBGRA へのフォーマットコンバータを生成する。"
                //-----------------
                try
                {
                    // WICイメージングファクトリから新しいコンバータを生成。
                    converter = new FormatConverter(imagingFactory2);

                    // コンバータに変換元フレームや変換後フォーマットなどを設定。
                    converter.Initialize(
                        sourceRef: sourceFrame,
                        dstFormat: SharpDX.WIC.PixelFormat.Format32bppPBGRA,    // Premultiplied BGRA
                        dither: BitmapDitherType.None,
                        paletteRef: null,
                        alphaThresholdPercent: 0.0,
                        paletteTranslate: BitmapPaletteType.MedianCut);
                }
                catch (SharpDXException e)
                {
                    Log.ERROR($"32bitPBGRA へのフォーマットコンバータの生成または初期化に失敗しました。(0x{e.HResult:x8})[{画像ファイルパス.変数付きパス}]");
                    return;
                }
                //-----------------
                #endregion

                #region " コンバータを使って、フレームを WICビットマップ経由で D2D ビットマップに変換する。"
                //-----------------
                try
                {
                    // WIC ビットマップを D2D ビットマップに変換する。
                    this.Bitmap?.Dispose();
                    this.Bitmap = bitmapProperties1 switch
                    {
                        null => Bitmap1.FromWicBitmap(d2dDeviceContext, converter),
                        _ => Bitmap1.FromWicBitmap(d2dDeviceContext, converter, bitmapProperties1),
                    };
                }
                catch (SharpDXException e)
                {
                    Log.ERROR($"Direct2D1.Bitmap1 への変換に失敗しました。(0x{e.HResult:x8})[{画像ファイルパス.変数付きパス}]");
                    return;
                }
                //-----------------
                #endregion

                this.サイズ = new Size2F(this.Bitmap.PixelSize.Width, this.Bitmap.PixelSize.Height);
            }
            finally
            {
                converter?.Dispose();
                sourceFrame?.Dispose();
                decoder?.Dispose();
            }
        }
Пример #29
0
        // 生成と終了


        public 画像D2D(ImagingFactory2 imagingFactory2, DeviceContext d2dDeviceContext, VariablePath 画像ファイルパス, BitmapProperties1?bitmapProperties1 = null)
        {
            //using var _ = new LogBlock( Log.現在のメソッド名 );

            this.Bitmapを生成する(imagingFactory2, d2dDeviceContext, 画像ファイルパス, bitmapProperties1);
        }
        public async static Task <MemoryStream> InterpolateImageMarkup(StorageFile imageFile, StorageFile markupFile)
        {
            try
            {
                var bitmap = new BitmapImage();
                using (var strm = await imageFile.OpenAsync(FileAccessMode.Read))
                {
                    bitmap.SetSource(strm);
                }
                var width       = bitmap.PixelWidth;
                var height      = bitmap.PixelHeight;
                var pixelFormat = WicPixelFormat.Format32bppBGR;

                var             wicFactory    = new ImagingFactory2();
                var             markupFactory = new ImagingFactory2();
                var             dddFactory    = new SharpDX.Direct2D1.Factory();
                var             dwFactory     = new SharpDX.DirectWrite.Factory();
                WicRenderTarget renderTarget;
                Bitmap          wicBitmap;


                SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);


                var device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
                SharpDX.DXGI.Device2     dxgiDevice2 = device.QueryInterface <SharpDX.DXGI.Device2>();
                SharpDX.Direct2D1.Device d2dDevice   = new SharpDX.Direct2D1.Device(dxgiDevice2);
                // d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);


                using (var bitmapSource = LoadBitmap(wicFactory, imageFile.Path))
                {
                    wicBitmap = new Bitmap(wicFactory, bitmapSource, BitmapCreateCacheOption.CacheOnLoad);

                    int pixelWidth  = (int)(wicBitmap.Size.Width * DisplayProperties.LogicalDpi / 96.0);
                    int pixelHeight = (int)(wicBitmap.Size.Height * DisplayProperties.LogicalDpi / 96.0);

                    var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default,
                                                                            new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), 0, 0, RenderTargetUsage.None,
                                                                            SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT);

                    renderTarget = new WicRenderTarget(dddFactory, wicBitmap, renderTargetProperties)
                    {
                        TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype
                    };
                }

                renderTarget.BeginDraw();


                renderTarget.DrawBitmap(LoadBitmapFromContentFile(wicFactory, markupFile.Path, renderTarget), 1.0f, SharpDX.Direct2D1.BitmapInterpolationMode.NearestNeighbor, new SharpDX.RectangleF(30, 50, 100, 80));



                //new RectangleF(width - 150, 0, width, height + 25),

                renderTarget.EndDraw();

                var ms = new MemoryStream();

                var stream = new WICStream(wicFactory, ms);

                BitmapEncoder encoder = null;
                if (imageFile.FileType == ".png")
                {
                    encoder = new PngBitmapEncoder(wicFactory);
                }
                else if (imageFile.FileType == ".jpg")
                {
                    encoder = new JpegBitmapEncoder(wicFactory);
                }

                encoder.Initialize(stream);

                var frameEncoder = new BitmapFrameEncode(encoder);
                frameEncoder.Initialize();
                frameEncoder.SetSize(width, height);
                //frameEncoder.piPixelFormat = WicPixelFormat.FormatDontCare;
                frameEncoder.WriteSource(wicBitmap);
                frameEncoder.Commit();

                encoder.Commit();

                frameEncoder.Dispose();
                encoder.Dispose();
                stream.Dispose();

                ms.Position = 0;
                return(ms);
            }
            catch (Exception)
            {
                throw;
            }
        }
        //  private static SharpDX.Direct2D1.DeviceContext d2dContext;
        public async static Task <MemoryStream> RenderStaticTextToBitmap(StorageFile imageFile)
        {
            var bitmap = new BitmapImage();

            using (var strm = await imageFile.OpenAsync(FileAccessMode.Read))
            {
                bitmap.SetSource(strm);
            }
            var width       = bitmap.PixelWidth;
            var height      = bitmap.PixelHeight;
            var pixelFormat = WicPixelFormat.Format32bppBGR;

            var             wicFactory = new ImagingFactory2();
            var             dddFactory = new SharpDX.Direct2D1.Factory();
            var             dwFactory  = new SharpDX.DirectWrite.Factory();
            WicRenderTarget renderTarget;
            Bitmap          wicBitmap;

            using (var bitmapSource = LoadBitmap(wicFactory, imageFile.Path))
            {
                wicBitmap = new Bitmap(wicFactory, bitmapSource, BitmapCreateCacheOption.CacheOnLoad);

                int pixelWidth  = (int)(wicBitmap.Size.Width * DisplayProperties.LogicalDpi / 96.0);
                int pixelHeight = (int)(wicBitmap.Size.Height * DisplayProperties.LogicalDpi / 96.0);

                var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default,
                                                                        new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), 0, 0, RenderTargetUsage.None,
                                                                        SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT);

                renderTarget = new WicRenderTarget(
                    dddFactory,
                    wicBitmap,
                    renderTargetProperties)
                {
                    TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype
                };
            }

            renderTarget.BeginDraw();

            var textFormat = new TextFormat(dwFactory, "Segoe UI Light", 25)
            {
                TextAlignment      = SharpDX.DirectWrite.TextAlignment.Leading,
                ParagraphAlignment = ParagraphAlignment.Far
            };
            var textBrush = new SharpDX.Direct2D1.SolidColorBrush(
                renderTarget,
                SharpDX.Color.DarkBlue);

            StringBuilder sb     = new StringBuilder();
            var           dstamp = StampPersistData.Instance.DataStamp;

            sb.Append(dstamp.KMReading).Append("\n");
            sb.Append(dstamp.DateOfFirstReg).Append("\n");

            sb.Append(dstamp.Gps).Append("\n");
            sb.Append(dstamp.VehRegNo).Append("\n");
            sb.Append(dstamp.Make).Append("\n");

            sb.Append(dstamp.CusName).Append("\n");
            sb.Append(dstamp.InspectorName).Append("\n");
            sb.Append(dstamp.CaseNo);



            renderTarget.DrawText(
                sb.ToString(),
                textFormat,
                new SharpDX.RectangleF(1, 1, width + 50, height + 25),
                textBrush);

            //new RectangleF(width - 150, 0, width, height + 25),

            renderTarget.EndDraw();

            var ms = new MemoryStream();

            var stream = new WICStream(
                wicFactory,
                ms);

            BitmapEncoder encoder = null;

            if (imageFile.FileType == ".png")
            {
                encoder = new PngBitmapEncoder(wicFactory);
            }
            else if (imageFile.FileType == ".jpg")
            {
                encoder = new JpegBitmapEncoder(wicFactory);
            }

            encoder.Initialize(stream);

            var frameEncoder = new BitmapFrameEncode(encoder);

            frameEncoder.Initialize();
            frameEncoder.SetSize(width, height);
            // frameEncoder.PixelFormat = WicPixelFormat.FormatDontCare;
            frameEncoder.WriteSource(wicBitmap);
            frameEncoder.Commit();

            encoder.Commit();

            frameEncoder.Dispose();
            encoder.Dispose();
            stream.Dispose();

            ms.Position = 0;
            return(ms);
        }