public void Save(Stream systemStream, Direct2DImageFormat format)
        {
          renderTarget.EndDraw();

          var stream = new WICStream(factoryManager.WicFactory, systemStream);
          var encoder = new BitmapEncoder(factoryManager.WicFactory, Direct2DConverter.ConvertImageFormat(format));
          encoder.Initialize(stream);

          var bitmapFrameEncode = new BitmapFrameEncode(encoder);
          bitmapFrameEncode.Initialize();
          bitmapFrameEncode.SetSize(imageWidth, imageHeight);

          Guid fdc = SharpDX.WIC.PixelFormat.FormatDontCare;
          //fdc = Direct2DConverter.ConvertImageFormat(Direct2DImageFormat.Gif);
          bitmapFrameEncode.SetPixelFormat(ref fdc);
          bitmapFrameEncode.WriteSource(wicBitmap);

          bitmapFrameEncode.Commit();
          try
          {
              encoder.Commit();
          }catch(Exception ex){

              var f = ex.Message;
          }
          bitmapFrameEncode.Dispose();
          encoder.Dispose();
          stream.Dispose();      



        }   
        public void Save(Stream systemStream, Direct2DImageFormat format, string text, string faceName, float fontSize, out int width, out int height)
        {
#if BENCHMARK
            using (var handler = Benchmark.Instance.Start("DirectWrite", "Save"))
#endif
            using (var layout = new TextLayout(factoryManager.DwFactory, text, new TextFormat(factoryManager.DwFactory, faceName, fontSize * 1.3f), 4000, 4000))
            {
                width  = (int)Math.Ceiling(layout.Metrics.WidthIncludingTrailingWhitespace);
                height = (int)Math.Ceiling(layout.Metrics.Height);
                using (var wicBitmap = new SharpDX.WIC.Bitmap(factoryManager.WicFactory, width, height, SharpDX.WIC.PixelFormat.Format32bppPRGBA, BitmapCreateCacheOption.CacheOnLoad))
                {
                    var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default,
                                                                            new SharpDX.Direct2D1.PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Unknown), imageDpi, imageDpi, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT);
                    using (var renderTarget = new WicRenderTarget(factoryManager.D2DFactory, wicBitmap, renderTargetProperties))
                        using (var brush = new SolidColorBrush(renderTarget, SharpDX.Color.White))
                            using (var encoder = new BitmapEncoder(factoryManager.WicFactory, Direct2DConverter.ConvertImageFormat(format)))
                            {
                                renderTarget.BeginDraw();
                                renderTarget.Clear(new Color4(1, 1, 1, 0));
                                renderTarget.DrawTextLayout(Vector2.Zero, layout, brush);
                                renderTarget.EndDraw();
                                var stream = new WICStream(factoryManager.WicFactory, systemStream);
                                encoder.Initialize(stream);
                                using (var bitmapFrameEncode = new BitmapFrameEncode(encoder))
                                {
                                    bitmapFrameEncode.Initialize();
                                    bitmapFrameEncode.SetSize(width, height);
                                    bitmapFrameEncode.WriteSource(wicBitmap);
                                    bitmapFrameEncode.Commit();
                                }
                                encoder.Commit();
                            }
                }
            }
        }
Exemple #3
0
        public static MemoryStream ToMemoryStream(this global::SharpDX.WIC.Bitmap bitmap,
                                                  IDevice2DResources deviceResources,
                                                  Direct2DImageFormat imageType = Direct2DImageFormat.Bmp)
        {
            if (bitmap == null)
            {
                return(null);
            }

            var systemStream = new MemoryStream();

            using (var stream = new WICStream(deviceResources.WICImgFactory, systemStream))
            {
                using (var encoder = new BitmapEncoder(deviceResources.WICImgFactory, imageType.ToWICImageFormat()))
                {
                    encoder.Initialize(stream);
                    using (var frameEncoder = new BitmapFrameEncode(encoder))
                    {
                        frameEncoder.Initialize();
                        frameEncoder.SetSize(bitmap.Size.Width, bitmap.Size.Height);
                        frameEncoder.WriteSource(bitmap);
                        frameEncoder.Commit();
                        encoder.Commit();
                        return(systemStream);
                    }
                }
            }
        }
        /// <inheritdoc />
        /// <summary>
        ///   Encodes a still image
        /// </summary>
        /// <param name="data">Bitmap data</param>
        /// <param name="stream">Output stream</param>
        public void Encode(BitmapData data, Stream stream)
        {
            using (var factory = new ImagingFactory()) {
                using (var encoder = new BitmapEncoder(factory, ContainerFormatGuids.Jpeg)) {
                    encoder.Initialize(stream);

                    using (var frame = new BitmapFrameEncode(encoder)) {
                        frame.Options.ImageQuality    = (float)(double)Options["Quality"];
                        frame.Options.BitmapTransform =
                            ((BitmapTransformOptions[])Enum.GetValues(typeof(BitmapTransformOptions)))[
                                Convert.ToInt32(Options["Transform"])];
                        frame.Options.JpegYCrCbSubsampling =
                            (JpegYCrCbSubsamplingOption)Convert.ToInt32(Options["ChromaSubsampling"]);
                        frame.Options.SuppressApp0 = (bool)Options["NoApp0"];
                        frame.Initialize();

                        using (var bitmap = new Bitmap(factory,
                                                       data.Width,
                                                       data.Height,
                                                       data.PixelFormat,
                                                       new DataRectangle(data.Scan0, data.Stride),
                                                       data.Height * data.Stride)) {
                            frame.WriteSource(bitmap);
                            frame.Commit();
                        }

                        encoder.Commit();
                    }
                }
            }
        }
        public void Save(Stream systemStream, Direct2DImageFormat format)
        {
            renderTarget.EndDraw();

            var stream  = new WICStream(factoryManager.WicFactory, systemStream);
            var encoder = new BitmapEncoder(factoryManager.WicFactory, Direct2DConverter.ConvertImageFormat(format));

            encoder.Initialize(stream);

            var bitmapFrameEncode = new BitmapFrameEncode(encoder);

            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(imageWidth, imageHeight);

            Guid fdc = SharpDX.WIC.PixelFormat.FormatDontCare;

            //fdc = Direct2DConverter.ConvertImageFormat(Direct2DImageFormat.Gif);
            bitmapFrameEncode.SetPixelFormat(ref fdc);
            bitmapFrameEncode.WriteSource(wicBitmap);

            bitmapFrameEncode.Commit();
            try
            {
                encoder.Commit();
            }catch (Exception ex) {
                var f = ex.Message;
            }
            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();
        }
Exemple #6
0
        // Used for debugging purposes
        private void SaveToFile(string fileName)
        {
            using (var pStream = new WICStream(FactoryImaging, fileName, SharpDX.IO.NativeFileAccess.Write))
            {
                //var format = SharpDX.WIC.PixelFormat.Format32bppPRGBA;
                var format = SharpDX.WIC.PixelFormat.FormatDontCare;
                //// Use InitializeFromFilename to write to a file. If there is need to write inside the memory, use InitializeFromMemory.
                var encodingFormat = BitmapEncoderGuids.Png;
                var encoder        = new PngBitmapEncoder(FactoryImaging, pStream);

                // Create a Frame encoder
                var pFrameEncode = new BitmapFrameEncode(encoder);
                pFrameEncode.Initialize();

                pFrameEncode.SetSize((int)_renderTarget.Size.Width, (int)_renderTarget.Size.Height);

                pFrameEncode.SetPixelFormat(ref format);

                pFrameEncode.WriteSource(_bitmap);

                pFrameEncode.Commit();

                encoder.Commit();
            }
        }
Exemple #7
0
        /// <inheritdoc />
        /// <summary>
        ///   Encodes a still image
        /// </summary>
        /// <param name="data">Bitmap data</param>
        /// <param name="stream">Output stream</param>
        public void Encode(BitmapData data, Stream stream)
        {
            using (var factory = new ImagingFactory()) {
                using (var encoder = new BitmapEncoder(factory, ContainerFormatGuids.Png)) {
                    encoder.Initialize(stream);

                    using (var frame = new BitmapFrameEncode(encoder)) {
                        frame.Options.FilterOption    = (PngFilterOption)Convert.ToInt32(Options["Filter"]);
                        frame.Options.InterlaceOption = (bool)Options["Interlaced"];
                        frame.Initialize();

                        using (var bitmap = new Bitmap(factory,
                                                       data.Width,
                                                       data.Height,
                                                       data.PixelFormat,
                                                       new DataRectangle(data.Scan0, data.Stride),
                                                       data.Height * data.Stride)) {
                            frame.WriteSource(bitmap);
                            frame.Commit();
                        }

                        encoder.Commit();
                    }
                }
            }
        }
Exemple #8
0
    public static void Save(this Texture2D texture, IRandomAccessStream stream, DeviceManager deviceManager)
    {
        var textureCopy = new Texture2D(deviceManager.DeviceDirect3D, new Texture2DDescription
        {
            Width             = (int)texture.Description.Width,
            Height            = (int)texture.Description.Height,
            MipLevels         = 1,
            ArraySize         = 1,
            Format            = texture.Description.Format,
            Usage             = ResourceUsage.Staging,
            SampleDescription = new SampleDescription(1, 0),
            BindFlags         = BindFlags.None,
            CpuAccessFlags    = CpuAccessFlags.Read,
            OptionFlags       = ResourceOptionFlags.None
        });

        deviceManager.ContextDirect3D.CopyResource(texture, textureCopy);
        DataStream dataStream;
        var        dataBox = deviceManager.ContextDirect3D.MapSubresource(
            textureCopy,
            0,
            0,
            MapMode.Read,
            SharpDX.Direct3D11.MapFlags.None,
            out dataStream);
        var dataRectangle = new DataRectangle
        {
            DataPointer = dataStream.DataPointer,
            Pitch       = dataBox.RowPitch
        };
        var bitmap = new Bitmap(
            deviceManager.WICFactory,
            textureCopy.Description.Width,
            textureCopy.Description.Height,
            PixelFormat.Format32bppBGRA,
            dataRectangle);

        using (var s = stream.AsStream())
        {
            s.Position = 0;
            using (var bitmapEncoder = new PngBitmapEncoder(deviceManager.WICFactory, s))
            {
                using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder))
                {
                    bitmapFrameEncode.Initialize();
                    bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
                    var pixelFormat = PixelFormat.FormatDontCare;
                    bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
                    bitmapFrameEncode.WriteSource(bitmap);
                    bitmapFrameEncode.Commit();
                    bitmapEncoder.Commit();
                }
            }
        }
        deviceManager.ContextDirect3D.UnmapSubresource(textureCopy, 0);
        textureCopy.Dispose();
        bitmap.Dispose();
    }
Exemple #9
0
    public MemoryStream RenderToPngStream(FrameworkElement fe)
    {
        var width  = (int)Math.Ceiling(fe.ActualWidth);
        var height = (int)Math.Ceiling(fe.ActualHeight);
        // pixel format with transparency/alpha channel and RGB values premultiplied by alpha
        var pixelFormat = WicPixelFormat.Format32bppPRGBA;
        // pixel format without transparency, but one that works with Cleartype antialiasing
        //var pixelFormat = WicPixelFormat.Format32bppBGR;
        var wicBitmap = new Bitmap(
            this.WicFactory,
            width,
            height,
            pixelFormat,
            BitmapCreateCacheOption.CacheOnLoad);
        var renderTargetProperties = new RenderTargetProperties(
            RenderTargetType.Default,
            new D2DPixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied),
            //new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), // use this for non-alpha, cleartype antialiased text
            0,
            0,
            RenderTargetUsage.None,
            FeatureLevel.Level_DEFAULT);
        var renderTarget = new WicRenderTarget(
            this.D2DFactory,
            wicBitmap,
            renderTargetProperties)
        {
            //TextAntialiasMode = TextAntialiasMode.Cleartype // this only works with the pixel format with no alpha channel
            TextAntialiasMode = TextAntialiasMode.Grayscale     // this is the best we can do for bitmaps with alpha channels
        };

        Compose(renderTarget, fe);
        // TODO: There is no need to encode the bitmap to PNG - we could just copy the texture pixel buffer to a WriteableBitmap pixel buffer.
        var ms     = new MemoryStream();
        var stream = new WICStream(
            this.WicFactory,
            ms);
        var encoder = new PngBitmapEncoder(WicFactory);

        encoder.Initialize(stream);
        var frameEncoder = new BitmapFrameEncode(encoder);

        frameEncoder.Initialize();
        frameEncoder.SetSize(width, height);
        var format = WicPixelFormat.Format32bppBGRA;

        //var format = WicPixelFormat.FormatDontCare;
        frameEncoder.SetPixelFormat(ref format);
        frameEncoder.WriteSource(wicBitmap);
        frameEncoder.Commit();
        encoder.Commit();
        frameEncoder.Dispose();
        encoder.Dispose();
        stream.Dispose();
        ms.Position = 0;
        return(ms);
    }
Exemple #10
0
        private static void Main()
        {
            var wicFactory = new ImagingFactory();
            var d2dFactory = new SharpDX.Direct2D1.Factory();

            string    filename = "output.jpg";
            const int width    = 512;
            const int height   = 512;

            var rectangleGeometry = new RoundedRectangleGeometry(d2dFactory, new RoundedRectangle()
            {
                RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, width - 128 * 2, height - 128 * 2)
            });

            var wicBitmap = new Bitmap(wicFactory, width, height, SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad);

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

            var d2dRenderTarget = new WicRenderTarget(d2dFactory, wicBitmap, renderTargetProperties);

            var solidColorBrush = new SolidColorBrush(d2dRenderTarget, Color.White);

            d2dRenderTarget.BeginDraw();
            d2dRenderTarget.Clear(Color.Black);
            d2dRenderTarget.FillGeometry(rectangleGeometry, solidColorBrush, null);
            d2dRenderTarget.EndDraw();

            if (File.Exists(filename))
            {
                File.Delete(filename);
            }

            var stream = new WICStream(wicFactory, filename, NativeFileAccess.Write);
            // Initialize a Jpeg encoder with this stream
            var encoder = new JpegBitmapEncoder(wicFactory);

            encoder.Initialize(stream);

            // Create a Frame encoder
            var bitmapFrameEncode = new BitmapFrameEncode(encoder);

            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(width, height);
            var pixelFormatGuid = SharpDX.WIC.PixelFormat.FormatDontCare;

            bitmapFrameEncode.SetPixelFormat(ref pixelFormatGuid);
            bitmapFrameEncode.WriteSource(wicBitmap);

            bitmapFrameEncode.Commit();
            encoder.Commit();

            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();

            System.Diagnostics.Process.Start(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, filename)));
        }
        private static void InternalSaveTexture(string path, int arraySlice, int mipSlice, ImagingFactory2 Factory, Texture2D textureCopy, DeviceContext context)
        {
            DataStream dataStream;
            var        dataBox = context.MapSubresource(
                textureCopy,
                mipSlice,
                arraySlice,
                MapMode.Read,
                SharpDX.Direct3D11.MapFlags.None,
                out dataStream);

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

            Guid m_PixelFormat = PixelFormat.Format64bppRGBAHalf;

            if (textureCopy.Description.Format == Format.R16G16_Float)
            {
                m_PixelFormat = PixelFormat.Format32bppGrayFloat;
            }

            if (textureCopy.Description.Format == Format.R8G8B8A8_UNorm)
            {
                m_PixelFormat = PixelFormat.Format32bppBGRA;
            }

            int mipSize = (int)(textureCopy.Description.Width * Math.Pow(0.5, mipSlice));

            var bitmap = new Bitmap(
                Factory,
                mipSize,
                mipSize,
                m_PixelFormat,
                dataRectangle);

            using (var s = new FileStream(path, FileMode.OpenOrCreate)) {//CREATE
                s.Position = 0;
                using (var bitmapEncoder = new PngBitmapEncoder(Factory, s)) {
                    using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder)) {
                        bitmapFrameEncode.Initialize();
                        bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
                        var pixelFormat = PixelFormat.FormatDontCare;
                        bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
                        bitmapFrameEncode.WriteSource(bitmap);
                        bitmapFrameEncode.Commit();
                        bitmapEncoder.Commit();
                    }
                }
            }
            bitmap.Dispose();
            context.UnmapSubresource(textureCopy, 0);
        }
Exemple #12
0
 public override void Save(Stream stream)
 {
     using (var encoder = new PngBitmapEncoder(Direct2D1Platform.ImagingFactory, stream))
         using (var frame = new BitmapFrameEncode(encoder))
         {
             frame.Initialize();
             frame.WriteSource(WicImpl);
             frame.Commit();
             encoder.Commit();
         }
 }
 public override void Save(Stream stream)
 {
     using (var encoder = new PngBitmapEncoder(Direct2D1Platform.ImagingFactory, stream))
         using (var frame = new BitmapFrameEncode(encoder))
             using (var bitmapSource = _direct2DBitmap.QueryInterface <BitmapSource>())
             {
                 frame.Initialize();
                 frame.WriteSource(bitmapSource);
                 frame.Commit();
                 encoder.Commit();
             }
 }
Exemple #14
0
        public override void Save(Stream stream)
        {
            PngBitmapEncoder encoder = new PngBitmapEncoder(_factory);

            encoder.Initialize(stream);

            BitmapFrameEncode frame = new BitmapFrameEncode(encoder);

            frame.Initialize();
            frame.WriteSource(WicImpl);
            frame.Commit();
            encoder.Commit();
        }
        public void Save(IEnumerable<BitmapFrame> frames, Stream stream)
        {
            this.wicImpl.Initialize(stream);

            foreach (WicBitmapSource source in frames.Select(x => x.PlatformImpl))
            {
                BitmapFrameEncode frame = new BitmapFrameEncode(this.wicImpl);
                frame.Initialize();
                frame.WriteSource(source.WicImpl);
                frame.Commit();
            }

            this.wicImpl.Commit();
        }
        public void Save(IEnumerable <BitmapFrame> frames, Stream stream)
        {
            this.wicImpl.Initialize(stream);

            foreach (WicBitmapSource source in frames.Select(x => x.PlatformImpl))
            {
                BitmapFrameEncode frame = new BitmapFrameEncode(this.wicImpl);
                frame.Initialize();
                frame.WriteSource(source.WicImpl);
                frame.Commit();
            }

            this.wicImpl.Commit();
        }
Exemple #17
0
 public void Save(FileInfo file)
 {
     using (var factory = new ImagingFactory())
         using (var bitmap = new Bitmap(factory, Size.Width, Size.Height, PixelFormat.Format32bppBGR, DataRectangle))
             using (var stream = file.OpenWrite())
                 using (var encoder = new BitmapEncoder(factory, ContainerFormatGuids.Png, stream)) {
                     using (var frameEncode = new BitmapFrameEncode(encoder)) {
                         frameEncode.Initialize();
                         frameEncode.WriteSource(bitmap);
                         frameEncode.Commit();
                     }
                     encoder.Commit();
                 }
 }
Exemple #18
0
        private static void Main()
        {
            var wicFactory = new ImagingFactory();
            var d2dFactory = new SharpDX.Direct2D1.Factory();

            string filename = "output.jpg";
            const int width = 512;
            const int height = 512;

            var rectangleGeometry = new RoundedRectangleGeometry(d2dFactory, new RoundedRectangle() { RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, width - 128, height-128) });

            var wicBitmap = new Bitmap(wicFactory, width, height, SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad);

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

            var d2dRenderTarget = new WicRenderTarget(d2dFactory, wicBitmap, renderTargetProperties);

            var solidColorBrush = new SolidColorBrush(d2dRenderTarget, Color.White);

            d2dRenderTarget.BeginDraw();
            d2dRenderTarget.Clear(Color.Black);
            d2dRenderTarget.FillGeometry(rectangleGeometry, solidColorBrush, null);
            d2dRenderTarget.EndDraw();

            if (File.Exists(filename))
                File.Delete(filename);

            var stream = new WICStream(wicFactory, filename, NativeFileAccess.Write);
            // Initialize a Jpeg encoder with this stream
            var encoder = new JpegBitmapEncoder(wicFactory);
            encoder.Initialize(stream);

            // Create a Frame encoder
            var bitmapFrameEncode = new BitmapFrameEncode(encoder);
            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(width, height);
            var pixelFormatGuid = SharpDX.WIC.PixelFormat.FormatDontCare;
            bitmapFrameEncode.SetPixelFormat(ref pixelFormatGuid);
            bitmapFrameEncode.WriteSource(wicBitmap);

            bitmapFrameEncode.Commit();
            encoder.Commit();

            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();

            System.Diagnostics.Process.Start(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory,filename)));
        }
        public static void ExportTexture(DeviceResources resources, StorageFile textureFile, Texture2D texture)
        {
            var device  = resources.D3DDevice;
            var context = resources.D3DDeviceContext;

            var textureToSave = texture;
            var outputTexture = new Texture2D(device, new Texture2DDescription
            {
                Width             = textureToSave.Description.Width,
                Height            = textureToSave.Description.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = textureToSave.Description.Format,
                Usage             = ResourceUsage.Staging,
                SampleDescription = new SampleDescription(1, 0),
                BindFlags         = BindFlags.None,
                CpuAccessFlags    = CpuAccessFlags.Read,
                OptionFlags       = ResourceOptionFlags.None
            });

            context.CopyResource(textureToSave, outputTexture);
            var mappedResource = context.MapSubresource(outputTexture, 0, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out var dataStream);
            var dataRectangle  = new DataRectangle
            {
                DataPointer = dataStream.DataPointer,
                Pitch       = mappedResource.RowPitch
            };
            var imagingFactory = new ImagingFactory();
            var bitmap         = new Bitmap(imagingFactory, outputTexture.Description.Width, outputTexture.Description.Height, PixelFormat.Format32bppRGBA, dataRectangle);

            using (var stream = new MemoryStream())
                using (var bitmapEncoder = new PngBitmapEncoder(imagingFactory, stream))
                    using (var bitmapFrame = new BitmapFrameEncode(bitmapEncoder))
                    {
                        bitmapFrame.Initialize();
                        bitmapFrame.SetSize(bitmap.Size.Width, bitmap.Size.Height);
                        var pixelFormat = PixelFormat.FormatDontCare;
                        bitmapFrame.SetPixelFormat(ref pixelFormat);
                        bitmapFrame.WriteSource(bitmap);
                        bitmapFrame.Commit();
                        bitmapEncoder.Commit();
                        FileIO.WriteBytesAsync(textureFile, stream.ToArray()).AsTask().Wait(-1);
                    }
            context.UnmapSubresource(outputTexture, 0);
            outputTexture.Dispose();
            bitmap.Dispose();
        }
Exemple #20
0
        public static void WriteJpegToStream(this Bitmap bitmap, Stream stream, int width = -1, int height = -1)
        {
            if (width <= 0)
            {
                width = bitmap.Size.Width;
            }

            if (height <= 0)
            {
                height = bitmap.Size.Height;
            }

            // ------------------------------------------------------
            // Encode a JPEG image
            // ------------------------------------------------------

            // Create a WIC outputstream
            var wicStream = new WICStream(DXGraphicsService.FactoryImaging, stream);

            // Initialize a Jpeg encoder with this stream
            var encoder = new JpegBitmapEncoder(DXGraphicsService.FactoryImaging);

            encoder.Initialize(wicStream);

            // Create a Frame encoder
            var bitmapFrameEncode = new BitmapFrameEncode(encoder);

            bitmapFrameEncode.Options.CompressionQuality = .8f;
            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(width, height);
            var guid = PixelFormat.Format24bppRGB;

            bitmapFrameEncode.SetPixelFormat(ref guid);

            bitmapFrameEncode.WriteSource(bitmap);

            // Commit changes
            bitmapFrameEncode.Commit();
            encoder.Commit();

            // Cleanup
            bitmapFrameEncode.Options.Dispose();
            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            wicStream.Dispose();
        }
Exemple #21
0
        public void Save(string fileName)
        {
            if (Path.GetExtension(fileName) != ".png")
            {
                // Yeah, we need to support other formats.
                throw new NotSupportedException("Use PNG, stoopid.");
            }

            using (FileStream s = new FileStream(fileName, FileMode.Create))
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder(factory);
                encoder.Initialize(s);

                BitmapFrameEncode frame = new BitmapFrameEncode(encoder);
                frame.Initialize();
                frame.WriteSource(this.WicImpl);
                frame.Commit();
                encoder.Commit();
            }
        }
Exemple #22
0
        private static void EncodeImage(ImagingFactory imagingFactory, Image image, WicFlags flags, Guid containerFormat, BitmapFrameEncode frame)
        {
            Guid pfGuid = ToWic(image.Format, false);

            frame.Initialize();
            frame.SetSize(image.Width, image.Height);
            frame.SetResolution(72, 72);
            Guid targetGuid = pfGuid;

            frame.SetPixelFormat(ref targetGuid);

            EncodeMetadata(frame, containerFormat, image.Format);

            if (targetGuid != pfGuid)
            {
                // Conversion required to write.
                GCHandle handle = GCHandle.Alloc(image.Data, GCHandleType.Pinned);
                using (var source = new Bitmap(imagingFactory, image.Width, image.Height, pfGuid, new DataRectangle(handle.AddrOfPinnedObject(), image.RowPitch), image.Data.Length))
                {
                    using (var converter = new FormatConverter(imagingFactory))
                    {
                        if (!converter.CanConvert(pfGuid, targetGuid))
                        {
                            throw new NotSupportedException("Format conversion is not supported.");
                        }

                        converter.Initialize(source, targetGuid, GetWicDither(flags), null, 0, BitmapPaletteType.Custom);
                        frame.WriteSource(converter, new Rectangle(0, 0, image.Width, image.Height));
                    }
                }

                handle.Free();
            }
            else
            {
                // No conversion required.
                frame.WritePixels(image.Height, image.RowPitch, image.Data);
            }

            frame.Commit();
        }
Exemple #23
0
        public static MemoryStream CreateBitmapStream(IDevice2DResources deviceResources, int width, int height, Direct2DImageFormat imageType, Action <RenderTarget> drawingAction)
        {
            using (var bitmap = new global::SharpDX.WIC.Bitmap(deviceResources.WICImgFactory, (int)width, (int)height, global::SharpDX.WIC.PixelFormat.Format32bppBGR,
                                                               BitmapCreateCacheOption.CacheOnDemand))
            {
                using (var target = new WicRenderTarget(deviceResources.Factory2D, bitmap,
                                                        new RenderTargetProperties()
                {
                    DpiX = 96,
                    DpiY = 96,
                    MinLevel = FeatureLevel.Level_DEFAULT,
                    PixelFormat = new global::SharpDX.Direct2D1.PixelFormat(global::SharpDX.DXGI.Format.Unknown, AlphaMode.Unknown)
                }))
                {
                    target.Transform = Matrix3x2.Identity;
                    target.BeginDraw();
                    drawingAction(target);
                    target.EndDraw();
                }
                var systemStream = new MemoryStream();

                using (var stream = new WICStream(deviceResources.WICImgFactory, systemStream))
                {
                    using (var encoder = new BitmapEncoder(deviceResources.WICImgFactory, imageType.ToWICImageFormat()))
                    {
                        encoder.Initialize(stream);
                        using (var frameEncoder = new BitmapFrameEncode(encoder))
                        {
                            frameEncoder.Initialize();
                            frameEncoder.SetSize((int)width, (int)height);
                            frameEncoder.WriteSource(bitmap);
                            frameEncoder.Commit();
                            encoder.Commit();
                            return(systemStream);
                        }
                    }
                }
            }
        }
        public static void WritePngToStream(Bitmap bitmap, Stream stream)
        {
            int width  = bitmap.Size.Width;
            int height = bitmap.Size.Height;

            // ------------------------------------------------------
            // Encode a PNG image
            // ------------------------------------------------------

            // Create a WIC outputstream
            var wicStream = new WICStream(DXGraphicsService.FactoryImaging, stream);

            // Initialize a Jpeg encoder with this stream
            var encoder = new PngBitmapEncoder(DXGraphicsService.FactoryImaging);

            encoder.Initialize(wicStream);

            // Create a Frame encoder
            var bitmapFrameEncode = new BitmapFrameEncode(encoder);

            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(width, height);
            Guid guid = PixelFormat.Format32bppRGBA;

            bitmapFrameEncode.SetPixelFormat(ref guid);

            bitmapFrameEncode.WriteSource(bitmap);

            // Commit changes
            bitmapFrameEncode.Commit();
            encoder.Commit();

            // Cleanup
            bitmapFrameEncode.Options.Dispose();
            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            wicStream.Dispose();
        }
Exemple #25
0
        /// <inheritdoc />
        /// <summary>
        ///   Encodes a still image
        /// </summary>
        /// <param name="data">Bitmap data</param>
        /// <param name="stream">Output stream</param>
        public virtual void Encode(BitmapData data, Stream stream)
        {
            using (var factory = new ImagingFactory()) {
                using (var encoder = new BitmapEncoder(factory, ContainerFormat)) {
                    encoder.Initialize(stream);

                    using (var frame = new BitmapFrameEncode(encoder)) {
                        frame.Initialize();

                        using (var bitmap = new Bitmap(factory,
                                                       data.Width,
                                                       data.Height,
                                                       data.PixelFormat,
                                                       new DataRectangle(data.Scan0, data.Stride),
                                                       data.Height * data.Stride)) {
                            frame.WriteSource(bitmap);
                            frame.Commit();
                        }

                        encoder.Commit();
                    }
                }
            }
        }
        // 
        // http://stackoverflow.com/questions/9151615/how-does-one-use-a-memory-stream-instead-of-files-when-rendering-direct2d-images
        // 
        // Identical to above SO question, except that we are rendering to MemoryStream because it was added to the API
        //
        private MemoryStream RenderStaticTextToBitmap()
        {
            var width = 400;
            var height = 100;
            var pixelFormat = WicPixelFormat.Format32bppBGR;

            var wicFactory = new ImagingFactory();
            var dddFactory = new SharpDX.Direct2D1.Factory();
            var dwFactory = new SharpDX.DirectWrite.Factory();

            var wicBitmap = new Bitmap(
                wicFactory,
                width,
                height,
                pixelFormat,
                BitmapCreateCacheOption.CacheOnLoad);

            var renderTargetProperties = new RenderTargetProperties(
                RenderTargetType.Default,
                new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown),
                0,
                0,
                RenderTargetUsage.None,
                FeatureLevel.Level_DEFAULT);
            var renderTarget = new WicRenderTarget(
                dddFactory,
                wicBitmap,
                renderTargetProperties)
            {
                TextAntialiasMode = TextAntialiasMode.Cleartype
            };

            renderTarget.BeginDraw();

            var textFormat = new TextFormat(dwFactory, "Consolas", 48)
            {
                TextAlignment = SharpDX.DirectWrite.TextAlignment.Center,
                ParagraphAlignment = ParagraphAlignment.Center
            };
            var textBrush = new SharpDX.Direct2D1.SolidColorBrush(
                renderTarget,
                SharpDX.Colors.Blue);

            renderTarget.Clear(Colors.White);
            renderTarget.DrawText(
                "Hi, mom!",
                textFormat,
                new RectangleF(0, 0, width, height),
                textBrush);

            renderTarget.EndDraw();

            var ms = new MemoryStream();

            var stream = new WICStream(
                wicFactory,
                ms);

            var encoder = new PngBitmapEncoder(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;
        }
Exemple #27
0
        public void Save(Stream stream)
        {
            PngBitmapEncoder encoder = new PngBitmapEncoder(_factory);
            encoder.Initialize(stream);

            BitmapFrameEncode frame = new BitmapFrameEncode(encoder);
            frame.Initialize();
            frame.WriteSource(WicImpl);
            frame.Commit();
            encoder.Commit();
        }
        //
        // http://stackoverflow.com/questions/9151615/how-does-one-use-a-memory-stream-instead-of-files-when-rendering-direct2d-images
        //
        // Identical to above SO question, except that we are rendering to MemoryStream because it was added to the API
        //
        private MemoryStream RenderStaticTextToBitmap()
        {
            var width       = 400;
            var height      = 100;
            var pixelFormat = WicPixelFormat.Format32bppBGR;

            var wicFactory = new ImagingFactory();
            var dddFactory = new SharpDX.Direct2D1.Factory();
            var dwFactory  = new SharpDX.DirectWrite.Factory();

            var wicBitmap = new Bitmap(
                wicFactory,
                width,
                height,
                pixelFormat,
                BitmapCreateCacheOption.CacheOnLoad);

            var renderTargetProperties = new RenderTargetProperties(
                RenderTargetType.Default,
                new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown),
                0,
                0,
                RenderTargetUsage.None,
                FeatureLevel.Level_DEFAULT);
            var renderTarget = new WicRenderTarget(
                dddFactory,
                wicBitmap,
                renderTargetProperties)
            {
                TextAntialiasMode = TextAntialiasMode.Cleartype
            };

            renderTarget.BeginDraw();

            var textFormat = new TextFormat(dwFactory, "Consolas", 48)
            {
                TextAlignment      = SharpDX.DirectWrite.TextAlignment.Center,
                ParagraphAlignment = ParagraphAlignment.Center
            };
            var textBrush = new SharpDX.Direct2D1.SolidColorBrush(
                renderTarget,
                SharpDX.Colors.Blue);

            renderTarget.Clear(Colors.White);
            renderTarget.DrawText(
                "Hi, mom!",
                textFormat,
                new RectangleF(0, 0, width, height),
                textBrush);

            renderTarget.EndDraw();

            var ms = new MemoryStream();

            var stream = new WICStream(
                wicFactory,
                ms);

            var encoder = new PngBitmapEncoder(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);
        }
Exemple #29
0
        public void Save(string fileName)
        {
            if (Path.GetExtension(fileName) != ".png")
            {
                // Yeah, we need to support other formats.
                throw new NotSupportedException("Use PNG, stoopid.");
            }

            using (FileStream s = new FileStream(fileName, FileMode.Create))
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder(this.factory);
                encoder.Initialize(s);

                BitmapFrameEncode frame = new BitmapFrameEncode(encoder);
                frame.Initialize();
                frame.WriteSource(this.WicImpl);
                frame.Commit();
                encoder.Commit();
            }
        }
        // Used for debugging purposes
        private void SaveToFile(string fileName, SharpDX.WIC.Bitmap _bitmap, RenderTarget _renderTarget)
        {

            using (var pStream = new WICStream(FactoryImaging, fileName, SharpDX.IO.NativeFileAccess.Write))
            {

                //var format = SharpDX.WIC.PixelFormat.Format32bppPRGBA;
                var format = SharpDX.WIC.PixelFormat.FormatDontCare;
                //// Use InitializeFromFilename to write to a file. If there is need to write inside the memory, use InitializeFromMemory. 
                var encodingFormat = BitmapEncoderGuids.Png;
                var encoder = new PngBitmapEncoder(FactoryImaging, pStream);

                // Create a Frame encoder
                var pFrameEncode = new BitmapFrameEncode(encoder);
                pFrameEncode.Initialize();

                pFrameEncode.SetSize((int)_renderTarget.Size.Width, (int)_renderTarget.Size.Height);

                pFrameEncode.SetPixelFormat(ref format);

                pFrameEncode.WriteSource(_bitmap);

                pFrameEncode.Commit();

                encoder.Commit();

            }
        }
Exemple #31
0
		/// <summary>
		/// Saves a texture to a stream as an image.
		/// </summary>
		/// <param name="texture">The texture to save.</param>
		/// <param name="imageFormat">The image format of the saved image.</param>
		/// <param name="imageResolutionInDpi">The image resolution in dpi.</param>
		/// <param name="toStream">The stream to save the texture to.</param>
		public static void SaveToStream(this Texture2D texture, System.Drawing.Imaging.ImageFormat imageFormat, double imageResolutionInDpi, System.IO.Stream toStream)
		{
			Texture2D textureCopy = null;
			ImagingFactory imagingFactory = null;
			Bitmap bitmap = null;
			BitmapEncoder bitmapEncoder = null;

			try
			{
				textureCopy = new Texture2D(texture.Device, new Texture2DDescription
				{
					Width = (int)texture.Description.Width,
					Height = (int)texture.Description.Height,
					MipLevels = 1,
					ArraySize = 1,
					Format = texture.Description.Format,
					Usage = ResourceUsage.Staging,
					SampleDescription = new SampleDescription(1, 0),
					BindFlags = BindFlags.None,
					CpuAccessFlags = CpuAccessFlags.Read,
					OptionFlags = ResourceOptionFlags.None
				});

				texture.Device.CopyResource(texture, textureCopy);

				DataRectangle dataRectangle = textureCopy.Map(0, MapMode.Read, SharpDX.Direct3D10.MapFlags.None);

				imagingFactory = new ImagingFactory();
				bitmap = new Bitmap(
						imagingFactory,
						textureCopy.Description.Width,
						textureCopy.Description.Height,
						PixelFormat.Format32bppBGRA,
						dataRectangle);

				toStream.Position = 0;

				if (imageFormat == System.Drawing.Imaging.ImageFormat.Png)
					bitmapEncoder = new PngBitmapEncoder(imagingFactory, toStream);
				else if (imageFormat == System.Drawing.Imaging.ImageFormat.Bmp)
					bitmapEncoder = new BmpBitmapEncoder(imagingFactory, toStream);
				else if (imageFormat == System.Drawing.Imaging.ImageFormat.Gif)
					bitmapEncoder = new GifBitmapEncoder(imagingFactory, toStream);
				else if (imageFormat == System.Drawing.Imaging.ImageFormat.Jpeg)
					bitmapEncoder = new JpegBitmapEncoder(imagingFactory, toStream);
				else if (imageFormat == System.Drawing.Imaging.ImageFormat.Tiff)
					bitmapEncoder = new TiffBitmapEncoder(imagingFactory, toStream);
				else
					bitmapEncoder = new PngBitmapEncoder(imagingFactory, toStream);

				using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder))
				{
					bitmapFrameEncode.Initialize();
					bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
					var pixelFormat = PixelFormat.FormatDontCare;
					bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
					bitmapFrameEncode.SetResolution(imageResolutionInDpi, imageResolutionInDpi);
					bitmapFrameEncode.WriteSource(bitmap);
					bitmapFrameEncode.Commit();
					bitmapEncoder.Commit();
				}
			}
			finally
			{
				bitmapEncoder?.Dispose();
				textureCopy?.Unmap(0);
				textureCopy?.Dispose();
				bitmap?.Dispose();
				imagingFactory?.Dispose();
			}
		}
Exemple #32
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();
        }
            private static bool CopyTextureToWICStream(IDeviceResources deviceResource, Texture2D staging, WICStream stream, Guid pfGuid, Guid containerFormat)
            {
                using (var encoder = new BitmapEncoder(deviceResource.WICImgFactory, containerFormat))
                {
                    var desc = staging.Description;
                    encoder.Initialize(stream);
                    var targetGuid = Guid.Empty;
                    using (var frame = new BitmapFrameEncode(encoder))
                    {
                        frame.Initialize();
                        frame.SetSize(desc.Width, desc.Height);
                        frame.SetResolution(72, 72);
                        switch (desc.Format)
                        {
                        case global::SharpDX.DXGI.Format.R32G32B32A32_Float:
                        case global::SharpDX.DXGI.Format.R16G16B16A16_Float:
                            targetGuid = PixelFormat.Format96bppRGBFloat;
                            break;

                        case global::SharpDX.DXGI.Format.R16G16B16A16_UNorm:
                            targetGuid = PixelFormat.Format48bppBGR;
                            break;

                        case global::SharpDX.DXGI.Format.R32_Float:
                        case global::SharpDX.DXGI.Format.R16_Float:
                        case global::SharpDX.DXGI.Format.R16_UNorm:
                        case global::SharpDX.DXGI.Format.R8_UNorm:
                        case global::SharpDX.DXGI.Format.A8_UNorm:
                            targetGuid = PixelFormat.Format48bppBGR;
                            break;

                        default:
                            targetGuid = PixelFormat.Format24bppBGR;
                            break;
                        }
                        frame.SetPixelFormat(ref targetGuid);
                        var databox = deviceResource.Device.ImmediateContext.MapSubresource(staging, 0, MapMode.Read, MapFlags.None);

                        try
                        {
                            if (targetGuid != pfGuid)
                            {
                                using (var bitmap = new Bitmap(deviceResource.WICImgFactory, desc.Width, desc.Height, pfGuid,
                                                               new global::SharpDX.DataRectangle(databox.DataPointer, databox.RowPitch)))
                                {
                                    using (var converter = new FormatConverter(deviceResource.WICImgFactory))
                                    {
                                        if (converter.CanConvert(pfGuid, targetGuid))
                                        {
                                            converter.Initialize(bitmap, targetGuid, BitmapDitherType.None, null, 0, BitmapPaletteType.MedianCut);
                                            frame.WriteSource(converter);
                                        }
                                        else
                                        {
                                            Debug.WriteLine("Cannot convert");
                                        }
                                    }
                                }
                            }
                            else
                            {
                                frame.WritePixels(desc.Height, new global::SharpDX.DataRectangle(databox.DataPointer, databox.RowPitch), databox.RowPitch * desc.Height);
                            }
                        }
                        finally
                        {
                            deviceResource.Device.ImmediateContext.UnmapSubresource(staging, 0);
                        }
                        frame.Commit();
                        encoder.Commit();
                        return(true);
                    }
                }
            }
Exemple #34
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);
            }
        }
Exemple #35
0
        private static void Save(Resource res, Stream stream, ImageFileFormat fmt)
        {
            var texture     = res as Texture2D;
            var textureCopy = new Texture2D(MyRender11.Device, new Texture2DDescription
            {
                Width             = (int)texture.Description.Width,
                Height            = (int)texture.Description.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = texture.Description.Format,
                Usage             = ResourceUsage.Staging,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags         = BindFlags.None,
                CpuAccessFlags    = CpuAccessFlags.Read,
                OptionFlags       = ResourceOptionFlags.None
            });

            RC.CopyResource(res, textureCopy);

            DataStream dataStream;
            var        dataBox = RC.MapSubresource(
                textureCopy,
                0,
                0,
                MapMode.Read,
                MapFlags.None,
                out dataStream);

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

            var bitmap = new Bitmap(
                MyRender11.WIC,
                textureCopy.Description.Width,
                textureCopy.Description.Height,
                PixelFormatFromFormat(textureCopy.Description.Format), // TODO: should use some conversion from textureCopy.Description.Format
                dataRectangle);

            using (var wicStream = new WICStream(MyRender11.WIC, stream))
            {
                BitmapEncoder bitmapEncoder;
                switch (fmt)
                {
                case ImageFileFormat.Png:
                    bitmapEncoder = new PngBitmapEncoder(MyRender11.WIC, wicStream);
                    break;

                case ImageFileFormat.Jpg:
                    bitmapEncoder = new JpegBitmapEncoder(MyRender11.WIC, wicStream);
                    break;

                case ImageFileFormat.Bmp:
                    bitmapEncoder = new BmpBitmapEncoder(MyRender11.WIC, wicStream);
                    break;

                default:
                    MyRenderProxy.Assert(false, "Unsupported file format.");
                    bitmapEncoder = null;
                    break;
                }
                if (bitmapEncoder != null)
                {
                    using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder))
                    {
                        bitmapFrameEncode.Initialize();
                        bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
                        var pixelFormat = PixelFormat.FormatDontCare;
                        bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
                        bitmapFrameEncode.WriteSource(bitmap);
                        bitmapFrameEncode.Commit();
                        bitmapEncoder.Commit();
                    }
                    bitmapEncoder.Dispose();
                }
            }

            RC.UnmapSubresource(textureCopy, 0);
            textureCopy.Dispose();
            bitmap.Dispose();
        }
Exemple #36
0
        internal CCTexture2D CreateTextSprite(string text, CCFontDefinition textDefinition)
        {
            if (string.IsNullOrEmpty(text))
                return new CCTexture2D();

            int imageWidth;
            int imageHeight;
            var textDef = textDefinition;
            var contentScaleFactorWidth = CCLabel.DefaultTexelToContentSizeRatios.Width;
            var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height;
            textDef.FontSize *= contentScaleFactorWidth;
            textDef.Dimensions.Width *= contentScaleFactorWidth;
            textDef.Dimensions.Height *= contentScaleFactorHeight;

            var font = CreateFont(textDef.FontName, textDef.FontSize);
            if (font == null)
            {
                CCLog.Log("Can not create font {0} with size {1}.", textDef.FontName, textDef.FontSize);
                return new CCTexture2D();
            }


            var _currentFontSizeEm = textDef.FontSize;
            var _currentDIP = ConvertPointSizeToDIP(_currentFontSizeEm);

            // color
            var foregroundColor = Color4.White;

            // alignment
            var horizontalAlignment = textDef.Alignment;
            var verticleAlignement = textDef.LineAlignment;

            var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? TextAlignment.Trailing
                : (CCTextAlignment.Center == horizontalAlignment) ? TextAlignment.Center
                : TextAlignment.Leading;

            var paragraphAlign = (CCVerticalTextAlignment.Bottom == vertAlignment) ? ParagraphAlignment.Far
                : (CCVerticalTextAlignment.Center == vertAlignment) ? ParagraphAlignment.Center
                : ParagraphAlignment.Near;

            // LineBreak
            var lineBreak = (CCLabelLineBreak.Character == textDef.LineBreak) ? WordWrapping.Wrap
                : (CCLabelLineBreak.Word == textDef.LineBreak) ? WordWrapping.Wrap
                : WordWrapping.NoWrap;

            // LineBreak
            // TODO: Find a way to specify the type of line breaking if possible.

            var dimensions = new CCSize(textDef.Dimensions.Width, textDef.Dimensions.Height);

            var layoutAvailable = true;
            if (dimensions.Width <= 0)
            {
                dimensions.Width = 8388608;
                layoutAvailable = false;
            }

            if (dimensions.Height <= 0)
            {
                dimensions.Height = 8388608;
                layoutAvailable = false;
            }

            var fontName = font.FontFamily.FamilyNames.GetString(0);
            var textFormat = new TextFormat(FactoryDWrite, fontName,
                _currentFontCollection, FontWeight.Regular, FontStyle.Normal, FontStretch.Normal, _currentDIP);

            textFormat.TextAlignment = textAlign;
            textFormat.ParagraphAlignment = paragraphAlign;

            var textLayout = new TextLayout(FactoryDWrite, text, textFormat, dimensions.Width, dimensions.Height);

            var boundingRect = new RectangleF();

            // Loop through all the lines so we can find our drawing offsets
            var textMetrics = textLayout.Metrics;
            var lineCount = textMetrics.LineCount;

            // early out if something went wrong somewhere and nothing is to be drawn
            if (lineCount == 0)
                return new CCTexture2D();

            // Fill out the bounding rect width and height so we can calculate the yOffset later if needed
            boundingRect.X = 0; 
            boundingRect.Y = 0; 
            boundingRect.Width = textMetrics.Width;
            boundingRect.Height = textMetrics.Height;

            if (!layoutAvailable)
            {
                if (dimensions.Width == 8388608)
                {
                    dimensions.Width = boundingRect.Width;
                }
                if (dimensions.Height == 8388608)
                {
                    dimensions.Height = boundingRect.Height;
                }
            }

            imageWidth = (int)dimensions.Width;
            imageHeight = (int)dimensions.Height;

            // Recreate our layout based on calculated dimensions so that we can draw the text correctly
            // in our image when Alignment is not Left.
            if (textAlign != TextAlignment.Leading)
            {
                textLayout.MaxWidth = dimensions.Width;
                textLayout.MaxHeight = dimensions.Height;
            }

            // Line alignment
            var yOffset = (CCVerticalTextAlignment.Bottom == verticleAlignement
                || boundingRect.Bottom >= dimensions.Height) ? dimensions.Height - boundingRect.Bottom  // align to bottom
                : (CCVerticalTextAlignment.Top == verticleAlignement) ? 0                    // align to top
                : (imageHeight - boundingRect.Bottom) * 0.5f;                                   // align to center


            SharpDX.WIC.Bitmap sharpBitmap = null;
            WicRenderTarget sharpRenderTarget = null;
            SolidColorBrush solidBrush = null;

            try
            {
                // Select our pixel format
                var pixelFormat = SharpDX.WIC.PixelFormat.Format32bppPRGBA;

                // create our backing bitmap
                sharpBitmap = new SharpDX.WIC.Bitmap(FactoryImaging, imageWidth, imageHeight, pixelFormat, BitmapCreateCacheOption.CacheOnLoad);

                // Create the render target that we will draw to
                sharpRenderTarget = new WicRenderTarget(Factory2D, sharpBitmap, new RenderTargetProperties());
                // Create our brush to actually draw with
                solidBrush = new SolidColorBrush(sharpRenderTarget, foregroundColor);

                // Begin the drawing
                sharpRenderTarget.BeginDraw();

                if (textDefinition.isShouldAntialias)
                    sharpRenderTarget.AntialiasMode = AntialiasMode.Aliased;

                // Clear it
                sharpRenderTarget.Clear(TransparentColor);

                // Draw the text to the bitmap
                sharpRenderTarget.DrawTextLayout(new Vector2(boundingRect.X, yOffset), textLayout, solidBrush);

                // End our drawing which will commit the rendertarget to the bitmap
                sharpRenderTarget.EndDraw();

                // Debugging purposes
                //var s = "Label4";
                //SaveToFile(@"C:\Xamarin\" + s + ".png", _bitmap, _renderTarget);

                // The following code creates a .png stream in memory of our Bitmap and uses it to create our Textue2D
                Texture2D tex = null;

                using (var memStream = new MemoryStream())
                {
                    using (var encoder = new PngBitmapEncoder(FactoryImaging, memStream))
                    using (var frameEncoder = new BitmapFrameEncode(encoder))
                    {
                        frameEncoder.Initialize();
                        frameEncoder.WriteSource(sharpBitmap);
                        frameEncoder.Commit();
                        encoder.Commit();
                    }
                    // Create the Texture2D from the png stream
                    tex = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, memStream);
                }

                // Return our new CCTexture2D created from the Texture2D which will have our text drawn on it.
                return new CCTexture2D(tex);
            }
            catch (Exception exc)
            {
                CCLog.Log("CCLabel-Windows: Unable to create the backing image of our text.  Message: {0}", exc.StackTrace);
            }
            finally
            {
                if (sharpBitmap != null)
                {
                    sharpBitmap.Dispose();
                    sharpBitmap = null;
                }

                if (sharpRenderTarget != null)
                {
                    sharpRenderTarget.Dispose();
                    sharpRenderTarget = null;
                }

                if (solidBrush != null)
                {
                    solidBrush.Dispose();
                    solidBrush = null;
                }

                if (textFormat != null)
                {
                    textFormat.Dispose();
                    textFormat = null;
                }

                if (textLayout != null)
                {
                    textLayout.Dispose();
                    textLayout = null;
                }
            }

            // If we have reached here then something has gone wrong.
            return new CCTexture2D();
        }
        private static void Save(IResource res, Stream stream, ImageFileFormat fmt)
        {
            var texture = res.Resource as Texture2D;
            var textureCopy = new Texture2D(MyRender11.Device, new Texture2DDescription
            {
                Width = (int)texture.Description.Width,
                Height = (int)texture.Description.Height,
                MipLevels = 1,
                ArraySize = 1,
                Format = texture.Description.Format,
                Usage = ResourceUsage.Staging,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags = BindFlags.None,
                CpuAccessFlags = CpuAccessFlags.Read,
                OptionFlags = ResourceOptionFlags.None
            });
            RC.CopyResource(res, textureCopy);

            DataStream dataStream;
            var dataBox = RC.MapSubresource(
                textureCopy,
                0,
                0,
                MapMode.Read,
                MapFlags.None,
                out dataStream);

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

            var bitmap = new Bitmap(
                MyRender11.WIC,
                textureCopy.Description.Width,
                textureCopy.Description.Height,
                PixelFormatFromFormat(textureCopy.Description.Format), // TODO: should use some conversion from textureCopy.Description.Format
                dataRectangle);

            using (var wicStream = new WICStream(MyRender11.WIC, stream))
            {
                BitmapEncoder bitmapEncoder;
                switch (fmt)
                {
                    case ImageFileFormat.Png:
                        bitmapEncoder = new PngBitmapEncoder(MyRender11.WIC, wicStream);
                        break;
                    case ImageFileFormat.Jpg:
                        bitmapEncoder = new JpegBitmapEncoder(MyRender11.WIC, wicStream);
                        break;
                    case ImageFileFormat.Bmp:
                        bitmapEncoder = new BmpBitmapEncoder(MyRender11.WIC, wicStream);
                        break;
                    default:
                        MyRenderProxy.Assert(false, "Unsupported file format.");
                        bitmapEncoder = null;
                        break;
                }
                if (bitmapEncoder != null)
                {
                    using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder))
                    {
                        bitmapFrameEncode.Initialize();
                        bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
                        var pixelFormat = PixelFormat.FormatDontCare;
                        bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
                        bitmapFrameEncode.WriteSource(bitmap);
                        bitmapFrameEncode.Commit();
                        bitmapEncoder.Commit();
                    }
                    bitmapEncoder.Dispose();
                }
            }

            RC.UnmapSubresource(textureCopy, 0);
            textureCopy.Dispose();
            bitmap.Dispose();
        }
Exemple #38
0
        void colorFrameReader_FrameArrived(object sender, ColorFrameArrivedEventArgs e)
        {
            var colorFrame = e.FrameReference.AcquireFrame();

            if (colorFrame != null)
            {
                using (colorFrame)
                {
                    lastColorGain = colorFrame.ColorCameraSettings.Gain;
                    lastColorExposureTimeTicks = colorFrame.ColorCameraSettings.ExposureTime.Ticks;

                    if (yuvFrameReady.Count > 0)
                    {
                        lock (yuvByteBuffer)
                            colorFrame.CopyRawFrameDataToArray(yuvByteBuffer);
                        lock (yuvFrameReady)
                            foreach (var autoResetEvent in yuvFrameReady)
                            {
                                autoResetEvent.Set();
                            }
                    }

                    if ((rgbFrameReady.Count > 0) || (jpegFrameReady.Count > 0))
                    {
                        lock (rgbByteBuffer)
                            colorFrame.CopyConvertedFrameDataToArray(rgbByteBuffer, ColorImageFormat.Bgra);
                        lock (rgbFrameReady)
                            foreach (var autoResetEvent in rgbFrameReady)
                            {
                                autoResetEvent.Set();
                            }
                    }

                    if (jpegFrameReady.Count > 0)
                    {
                        // should be put in a separate thread?

                        stopWatch.Restart();

                        var bitmapSource = new Bitmap(imagingFactory, Kinect2Calibration.colorImageWidth, Kinect2Calibration.colorImageHeight, SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad);
                        var bitmapLock   = bitmapSource.Lock(BitmapLockFlags.Write);
                        Marshal.Copy(rgbByteBuffer, 0, bitmapLock.Data.DataPointer, Kinect2Calibration.colorImageWidth * Kinect2Calibration.colorImageHeight * 4);
                        bitmapLock.Dispose();

                        var memoryStream = new MemoryStream();

                        //var fileStream = new FileStream("test" + frame++ + ".jpg", FileMode.Create);
                        //var stream = new WICStream(imagingFactory, "test" + frame++ + ".jpg", SharpDX.IO.NativeFileAccess.Write);

                        var stream = new WICStream(imagingFactory, memoryStream);

                        var jpegBitmapEncoder = new JpegBitmapEncoder(imagingFactory);
                        jpegBitmapEncoder.Initialize(stream);

                        var bitmapFrameEncode = new BitmapFrameEncode(jpegBitmapEncoder);
                        bitmapFrameEncode.Options.ImageQuality = 0.5f;
                        bitmapFrameEncode.Initialize();
                        bitmapFrameEncode.SetSize(Kinect2Calibration.colorImageWidth, Kinect2Calibration.colorImageHeight);
                        var pixelFormatGuid = PixelFormat.FormatDontCare;
                        bitmapFrameEncode.SetPixelFormat(ref pixelFormatGuid);
                        bitmapFrameEncode.WriteSource(bitmapSource);

                        bitmapFrameEncode.Commit();
                        jpegBitmapEncoder.Commit();

                        //fileStream.Close();
                        //fileStream.Dispose();

                        //Console.WriteLine(stopWatch.ElapsedMilliseconds + "ms " + memoryStream.Length + " bytes");

                        lock (jpegByteBuffer)
                        {
                            nJpegBytes = (int)memoryStream.Length;
                            memoryStream.Seek(0, SeekOrigin.Begin);
                            memoryStream.Read(jpegByteBuffer, 0, nJpegBytes);
                        }
                        lock (jpegFrameReady)
                            foreach (var autoResetEvent in jpegFrameReady)
                            {
                                autoResetEvent.Set();
                            }

                        //var file = new FileStream("test" + frame++ + ".jpg", FileMode.Create);
                        //file.Write(jpegByteBuffer, 0, nJpegBytes);
                        //file.Close();

                        bitmapSource.Dispose();
                        memoryStream.Close();
                        memoryStream.Dispose();
                        stream.Dispose();
                        jpegBitmapEncoder.Dispose();
                        bitmapFrameEncode.Dispose();
                    }
                }
            }
        }
Exemple #39
0
        internal CCTexture2D CreateTextSprite(string text, CCFontDefinition textDefinition)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(new CCTexture2D());
            }

            int imageWidth;
            int imageHeight;
            var textDef = textDefinition;
            var contentScaleFactorWidth  = CCLabel.DefaultTexelToContentSizeRatios.Width;
            var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height;

            textDef.FontSize          *= (int)contentScaleFactorWidth;
            textDef.Dimensions.Width  *= contentScaleFactorWidth;
            textDef.Dimensions.Height *= contentScaleFactorHeight;

            bool hasPremultipliedAlpha;

            var font = CreateFont(textDef.FontName, textDef.FontSize);

            var _currentFontSizeEm = textDef.FontSize;
            var _currentDIP        = ConvertPointSizeToDIP(_currentFontSizeEm);

            var fontColor       = textDef.FontFillColor;
            var fontAlpha       = textDef.FontAlpha;
            var foregroundColor = new Color4(fontColor.R / 255.0f,
                                             fontColor.G / 255.0f,
                                             fontColor.B / 255.0f,
                                             fontAlpha / 255.0f);

            // alignment
            var horizontalAlignment = textDef.Alignment;
            var verticleAlignement  = textDef.LineAlignment;

            var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? TextAlignment.Trailing
                : (CCTextAlignment.Center == horizontalAlignment) ? TextAlignment.Center
                : TextAlignment.Leading;

            var paragraphAlign = (CCVerticalTextAlignment.Bottom == vertAlignment) ? ParagraphAlignment.Far
                : (CCVerticalTextAlignment.Center == vertAlignment) ? ParagraphAlignment.Center
                : ParagraphAlignment.Near;

            // LineBreak
            var lineBreak = (CCLabelLineBreak.Character == textDef.LineBreak) ? WordWrapping.Wrap
                : (CCLabelLineBreak.Word == textDef.LineBreak) ? WordWrapping.Wrap
                : WordWrapping.NoWrap;

            // LineBreak
            // TODO: Find a way to specify the type of line breaking if possible.

            var dimensions = new CCSize(textDef.Dimensions.Width, textDef.Dimensions.Height);

            var layoutAvailable = true;

            if (dimensions.Width <= 0)
            {
                dimensions.Width = 8388608;
                layoutAvailable  = false;
            }

            if (dimensions.Height <= 0)
            {
                dimensions.Height = 8388608;
                layoutAvailable   = false;
            }

            var fontName   = font.FontFamily.FamilyNames.GetString(0);
            var textFormat = new TextFormat(FactoryDWrite, fontName,
                                            _currentFontCollection, FontWeight.Regular, FontStyle.Normal, FontStretch.Normal, _currentDIP);

            textFormat.TextAlignment      = textAlign;
            textFormat.ParagraphAlignment = paragraphAlign;

            var textLayout = new TextLayout(FactoryDWrite, text, textFormat, dimensions.Width, dimensions.Height);

            var boundingRect = new RectangleF();

            // Loop through all the lines so we can find our drawing offsets
            var textMetrics = textLayout.Metrics;
            var lineCount   = textMetrics.LineCount;

            // early out if something went wrong somewhere and nothing is to be drawn
            if (lineCount == 0)
            {
                return(new CCTexture2D());
            }

            // Fill out the bounding rect width and height so we can calculate the yOffset later if needed
            boundingRect.X      = 0;
            boundingRect.Y      = 0;
            boundingRect.Width  = textMetrics.Width;
            boundingRect.Height = textMetrics.Height;

            if (!layoutAvailable)
            {
                if (dimensions.Width == 8388608)
                {
                    dimensions.Width = boundingRect.Width;
                }
                if (dimensions.Height == 8388608)
                {
                    dimensions.Height = boundingRect.Height;
                }
            }

            imageWidth  = (int)dimensions.Width;
            imageHeight = (int)dimensions.Height;

            // Recreate our layout based on calculated dimensions so that we can draw the text correctly
            // in our image when Alignment is not Left.
            if (textAlign != TextAlignment.Leading)
            {
                textLayout.MaxWidth  = dimensions.Width;
                textLayout.MaxHeight = dimensions.Height;
            }

            // Line alignment
            var yOffset = (CCVerticalTextAlignment.Bottom == verticleAlignement ||
                           boundingRect.Bottom >= dimensions.Height) ? dimensions.Height - boundingRect.Bottom // align to bottom
                : (CCVerticalTextAlignment.Top == verticleAlignement) ? 0                                      // align to top
                : (imageHeight - boundingRect.Bottom) * 0.5f;                                                  // align to center


            SharpDX.WIC.Bitmap sharpBitmap       = null;
            WicRenderTarget    sharpRenderTarget = null;
            SolidColorBrush    solidBrush        = null;

            try
            {
                // Select our pixel format
                var pixelFormat = SharpDX.WIC.PixelFormat.Format32bppPRGBA;

                // create our backing bitmap
                sharpBitmap = new SharpDX.WIC.Bitmap(FactoryImaging, imageWidth, imageHeight, pixelFormat, BitmapCreateCacheOption.CacheOnLoad);

                // Create the render target that we will draw to
                sharpRenderTarget = new WicRenderTarget(Factory2D, sharpBitmap, new RenderTargetProperties());
                // Create our brush to actually draw with
                solidBrush = new SolidColorBrush(sharpRenderTarget, foregroundColor);

                // Begin the drawing
                sharpRenderTarget.BeginDraw();

                if (textDefinition.isShouldAntialias)
                {
                    sharpRenderTarget.AntialiasMode = AntialiasMode.Aliased;
                }

                // Clear it
                sharpRenderTarget.Clear(TransparentColor);

                // Draw the text to the bitmap
                sharpRenderTarget.DrawTextLayout(new Vector2(boundingRect.X, yOffset), textLayout, solidBrush);

                // End our drawing which will commit the rendertarget to the bitmap
                sharpRenderTarget.EndDraw();

                // Debugging purposes
                //var s = "Label4";
                //SaveToFile(@"C:\Xamarin\" + s + ".png", _bitmap, _renderTarget);

                // The following code creates a .png stream in memory of our Bitmap and uses it to create our Textue2D
                Texture2D tex = null;

                using (var memStream = new MemoryStream())
                {
                    using (var encoder = new PngBitmapEncoder(FactoryImaging, memStream))
                        using (var frameEncoder = new BitmapFrameEncode(encoder))
                        {
                            frameEncoder.Initialize();
                            frameEncoder.WriteSource(sharpBitmap);
                            frameEncoder.Commit();
                            encoder.Commit();
                        }
                    // Create the Texture2D from the png stream
                    tex = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, memStream);
                }

                // Return our new CCTexture2D created from the Texture2D which will have our text drawn on it.
                return(new CCTexture2D(tex));
            }
            catch (Exception exc)
            {
                CCLog.Log("CCLabel-Windows: Unable to create the backing image of our text.  Message: {0}", exc.StackTrace);
            }
            finally
            {
                if (sharpBitmap != null)
                {
                    sharpBitmap.Dispose();
                    sharpBitmap = null;
                }

                if (sharpRenderTarget != null)
                {
                    sharpRenderTarget.Dispose();
                    sharpRenderTarget = null;
                }

                if (solidBrush != null)
                {
                    solidBrush.Dispose();
                    solidBrush = null;
                }

                if (textFormat != null)
                {
                    textFormat.Dispose();
                    textFormat = null;
                }

                if (textLayout != null)
                {
                    textLayout.Dispose();
                    textLayout = null;
                }
            }

            // If we have reached here then something has gone wrong.
            return(new CCTexture2D());
        }
Exemple #40
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();
            }
        }
    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;
      }
    }
Exemple #42
0
        private static void FlushCurrentFrame(GifBitmapEncoder encoder,
            ImagingFactory factory,
            BitmapFrame bitmap)
        {
            // nothing to flush.
            if (bitmap == null)
            {
                return;
            }

            using (var frameEncoder = new BitmapFrameEncode(encoder))
            {
                frameEncoder.Initialize();
                frameEncoder.SetSize(bitmap.Data.Width, bitmap.Data.Height);
                frameEncoder.SetResolution(bitmap.Data.HorizontalResolution, bitmap.Data.VerticalResolution);

                // embed frame metadata.
                var metadataWriter = frameEncoder.MetadataQueryWriter;
                metadataWriter.SetMetadataByName("/grctlext/Delay", Convert.ToUInt16(bitmap.Delay/100));
                metadataWriter.SetMetadataByName("/imgdesc/Left", Convert.ToUInt16(bitmap.XPos));
                metadataWriter.SetMetadataByName("/imgdesc/Top", Convert.ToUInt16(bitmap.YPos));
                metadataWriter.SetMetadataByName("/imgdesc/Width", Convert.ToUInt16(bitmap.Data.Width));
                metadataWriter.SetMetadataByName("/imgdesc/Height", Convert.ToUInt16(bitmap.Data.Height));

                using (var bitmapSource = new WicBitmap(
                    factory,
                    bitmap.Data,
                    BitmapAlphaChannelOption.UsePremultipliedAlpha))
                {
                    var converter = new FormatConverter(factory);
                    converter.Initialize(bitmapSource,
                        PixelFormat.Format8bppIndexed,
                        BitmapDitherType.Solid,
                        null,
                        0.8,
                        BitmapPaletteType.MedianCut);

                    frameEncoder.WriteSource(converter);
                    frameEncoder.Commit();
                }
            }
        }
        void colorFrameReader_FrameArrived(object sender, ColorFrameArrivedEventArgs e)
        {
            var colorFrame = e.FrameReference.AcquireFrame();
            if (colorFrame != null)
            {
                using (colorFrame)
                {
                    lastColorGain = colorFrame.ColorCameraSettings.Gain;
                    lastColorExposureTimeTicks = colorFrame.ColorCameraSettings.ExposureTime.Ticks;

                    if (yuvFrameReady.Count > 0)
                    {
                        lock (yuvByteBuffer)
                            colorFrame.CopyRawFrameDataToArray(yuvByteBuffer);
                        lock (yuvFrameReady)
                            foreach (var autoResetEvent in yuvFrameReady)
                                autoResetEvent.Set();
                    }

                    if ((rgbFrameReady.Count > 0) || (jpegFrameReady.Count > 0))
                    {
                        lock (rgbByteBuffer)
                            colorFrame.CopyConvertedFrameDataToArray(rgbByteBuffer, ColorImageFormat.Bgra);
                        lock (rgbFrameReady)
                            foreach (var autoResetEvent in rgbFrameReady)
                                autoResetEvent.Set();
                    }

                    if (jpegFrameReady.Count > 0)
                    {
                        // should be put in a separate thread?

                        stopWatch.Restart();

                        var bitmapSource = new Bitmap(imagingFactory, Kinect2Calibration.colorImageWidth, Kinect2Calibration.colorImageHeight, SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad);
                        var bitmapLock = bitmapSource.Lock(BitmapLockFlags.Write);
                        Marshal.Copy(rgbByteBuffer, 0, bitmapLock.Data.DataPointer, Kinect2Calibration.colorImageWidth * Kinect2Calibration.colorImageHeight * 4);
                        bitmapLock.Dispose();

                        var memoryStream = new MemoryStream();

                        //var fileStream = new FileStream("test" + frame++ + ".jpg", FileMode.Create);
                        //var stream = new WICStream(imagingFactory, "test" + frame++ + ".jpg", SharpDX.IO.NativeFileAccess.Write);

                        var stream = new WICStream(imagingFactory, memoryStream);

                        var jpegBitmapEncoder = new JpegBitmapEncoder(imagingFactory);
                        jpegBitmapEncoder.Initialize(stream);

                        var bitmapFrameEncode = new BitmapFrameEncode(jpegBitmapEncoder);
                        bitmapFrameEncode.Options.ImageQuality = 0.5f;
                        bitmapFrameEncode.Initialize();
                        bitmapFrameEncode.SetSize(Kinect2Calibration.colorImageWidth, Kinect2Calibration.colorImageHeight);
                        var pixelFormatGuid = PixelFormat.FormatDontCare;
                        bitmapFrameEncode.SetPixelFormat(ref pixelFormatGuid);
                        bitmapFrameEncode.WriteSource(bitmapSource);

                        bitmapFrameEncode.Commit();
                        jpegBitmapEncoder.Commit();

                        //fileStream.Close();
                        //fileStream.Dispose();

                        //Console.WriteLine(stopWatch.ElapsedMilliseconds + "ms " + memoryStream.Length + " bytes");

                        lock (jpegByteBuffer)
                        {
                            nJpegBytes = (int)memoryStream.Length;
                            memoryStream.Seek(0, SeekOrigin.Begin);
                            memoryStream.Read(jpegByteBuffer, 0, nJpegBytes);
                        }
                        lock (jpegFrameReady)
                            foreach (var autoResetEvent in jpegFrameReady)
                                autoResetEvent.Set();

                        //var file = new FileStream("test" + frame++ + ".jpg", FileMode.Create);
                        //file.Write(jpegByteBuffer, 0, nJpegBytes);
                        //file.Close();

                        bitmapSource.Dispose();
                        memoryStream.Close();
                        memoryStream.Dispose();
                        stream.Dispose();
                        jpegBitmapEncoder.Dispose();
                        bitmapFrameEncode.Dispose();
                    }
                }
            }
        }
Exemple #44
0
        private static void EncodeImage(ImagingFactory imagingFactory, Image image, WicFlags flags, Guid containerFormat, BitmapFrameEncode frame)
        {
            Guid pfGuid = ToWic(image.Format, false);

              frame.Initialize();
              frame.SetSize(image.Width, image.Height);
              frame.SetResolution(72, 72);
              Guid targetGuid = pfGuid;
              frame.SetPixelFormat(ref targetGuid);

              EncodeMetadata(frame, containerFormat, image.Format);

              if (targetGuid != pfGuid)
              {
            // Conversion required to write.
            GCHandle handle = GCHandle.Alloc(image.Data, GCHandleType.Pinned);
            using (var source = new Bitmap(imagingFactory, image.Width, image.Height, pfGuid, new DataRectangle(handle.AddrOfPinnedObject(), image.RowPitch), image.Data.Length))
            {
              using (var converter = new FormatConverter(imagingFactory))
              {
            if (!converter.CanConvert(pfGuid, targetGuid))
              throw new NotSupportedException("Format conversion is not supported.");

            converter.Initialize(source, targetGuid, GetWicDither(flags), null, 0, BitmapPaletteType.Custom);
            frame.WriteSource(converter, new Rectangle(0, 0, image.Width, image.Height));
              }
            }

            handle.Free();
              }
              else
              {
            // No conversion required.
            frame.WritePixels(image.Height, image.RowPitch, image.Data);
              }

              frame.Commit();
        }