Exemple #1
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();
            }
        }
        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
        /// <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();
                    }
                }
            }
        }
        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)
        {
            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
        private Stream EncodeBitmap(Bitmap1 bitmap, Guid containerFormat)
        {
            using (var bitmapEncoder = new BitmapEncoder(WicFactory, containerFormat))
            {
                var memoryStream = new MemoryStream();
                bitmapEncoder.Initialize(memoryStream);
                using (var frameEncode = new BitmapFrameEncode(bitmapEncoder))
                {
                    frameEncode.Initialize();
                    var wicPixelFormat = ImagePixelFormat;
                    frameEncode.SetPixelFormat(ref wicPixelFormat);

                    var imageParams = new ImageParameters()
                    {
                        PixelFormat = DevicePixelFormat,
                        DpiX        = Dpi,
                        DpiY        = Dpi,
                        PixelWidth  = bitmap.PixelSize.Width,
                        PixelHeight = bitmap.PixelSize.Height
                    };

                    WicImageEncoder.WriteFrame(bitmap, frameEncode, imageParams);

                    frameEncode.Commit();
                    bitmapEncoder.Commit();
                }

                memoryStream.Position = 0;
                return(memoryStream);
            }
        }
        /// <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();
                    }
                }
            }
        }
 /// <summary>
 /// 将 Direct2D 位图保存到文件中。
 /// </summary>
 /// <param name="image">要保存的位图。</param>
 /// <param name="fileName">要保存的文件名。</param>
 public void SaveBitmapToFile(Bitmap image, string fileName)
 {
     using (ImagingFactory2 factory = new ImagingFactory2())
     {
         using (WICStream stream = new WICStream(factory, fileName, NativeFileAccess.Write))
         {
             using (BitmapEncoder encoder = new PngBitmapEncoder(factory))
             {
                 encoder.Initialize(stream);
                 using (BitmapFrameEncode bitmapFrameEncode = new BitmapFrameEncode(encoder))
                 {
                     bitmapFrameEncode.Initialize();
                     int width  = image.PixelSize.Width;
                     int height = image.PixelSize.Height;
                     bitmapFrameEncode.SetSize(width, height);
                     Guid wicPixelFormat = WICPixelFormat;
                     bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);
                     using (ImageEncoder imageEncoder = new ImageEncoder(factory, this.d2DDevice))
                     {
                         imageEncoder.WriteFrame(image, bitmapFrameEncode,
                                                 new ImageParameters(D2PixelFormat, 96, 96, 0, 0, width, height));
                         bitmapFrameEncode.Commit();
                         encoder.Commit();
                     }
                 }
             }
         }
     }
 }
Exemple #9
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);
                    }
                }
            }
        }
Exemple #10
0
        //-------------------------------------------------------------------------------------
        // Encodes a single frame
        //-------------------------------------------------------------------------------------
        private static void EncodeImage(PixelBuffer image, WICFlags flags, BitmapFrameEncode frame)
        {
            Guid pfGuid;

            if (!ToWIC(image.Format, out pfGuid))
            {
                throw new NotSupportedException("Format not supported");
            }

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

            frame.SetPixelFormat(ref targetGuid);

            if (targetGuid != pfGuid)
            {
                using (var source = new Bitmap(Factory, image.Width, image.Height, pfGuid, new DataRectangle(image.DataPointer, image.RowStride), image.BufferStride))
                {
                    using (var converter = new FormatConverter(Factory))
                    {
                        using (var palette = new Palette(Factory))
                        {
                            palette.Initialize(source, 256, true);
                            converter.Initialize(source, targetGuid, GetWICDither(flags), palette, 0, BitmapPaletteType.Custom);

                            int bpp = GetBitsPerPixel(targetGuid);
                            if (bpp == 0)
                            {
                                throw new NotSupportedException("Unable to determine the Bpp for the target format");
                            }

                            int rowPitch   = (image.Width * bpp + 7) / 8;
                            int slicePitch = rowPitch * image.Height;

                            var temp = Utilities.AllocateMemory(slicePitch);
                            try
                            {
                                converter.CopyPixels(rowPitch, temp, slicePitch);
                                frame.Palette = palette;
                                frame.WritePixels(image.Height, temp, rowPitch, slicePitch);
                            }
                            finally
                            {
                                Utilities.FreeMemory(temp);
                            }
                        }
                    }
                }
            }
            else
            {
                // No conversion required
                frame.WritePixels(image.Height, image.DataPointer, image.RowStride, image.BufferStride);
            }

            frame.Commit();
        }
Exemple #11
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 #12
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)));
        }
Exemple #13
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);
    }
        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 #15
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 #17
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 #20
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 #21
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 #23
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 #24
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 #25
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 #26
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 #28
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();
                    }
                }
            }
        }
Exemple #29
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();
        }
Exemple #30
0
        //-------------------------------------------------------------------------------------
        // Encodes a single frame
        //-------------------------------------------------------------------------------------
        private static void EncodeImage( PixelBuffer image, WICFlags flags, BitmapFrameEncode frame)
        {
            Guid pfGuid;
            if (! ToWIC(image.Format, out pfGuid))
                throw new NotSupportedException("Format not supported");

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

            if (targetGuid != pfGuid)
            {
                using (var source = new Bitmap(Factory, image.Width, image.Height, pfGuid, new DataRectangle(image.DataPointer, image.RowStride), image.BufferStride))
                {
                    using (var converter = new FormatConverter(Factory))
                    {
                        using (var palette = new Palette(Factory))
                        {
                            palette.Initialize(source, 256, true);
                            converter.Initialize(source, targetGuid, GetWICDither(flags), palette, 0, BitmapPaletteType.Custom);

                            int bpp = GetBitsPerPixel(targetGuid);
                            if (bpp == 0) throw new NotSupportedException("Unable to determine the Bpp for the target format");

                            int rowPitch = (image.Width * bpp + 7) / 8;
                            int slicePitch = rowPitch * image.Height;

                            var temp = Utilities.AllocateMemory(slicePitch);
                            try
                            {
                                converter.CopyPixels(rowPitch, temp, slicePitch);
                                frame.Palette = palette;
                                frame.WritePixels(image.Height, temp, rowPitch, slicePitch);
                            }
                            finally
                            {
                                Utilities.FreeMemory(temp);
                            }
                        }
                    }
                }
            }
            else
            {
                // No conversion required
                frame.WritePixels(image.Height, image.DataPointer, image.RowStride, image.BufferStride);
            }

            frame.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 #32
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 #33
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();
        }
        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 #35
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();
                }
            }
        }
Exemple #36
0
        /// <summary>
        /// SharpDX WIC sample. Encode to JPG and decode.
        /// </summary>
        static void Main()
        {
            const int width = 512;
            const int height = 512;
            const string filename = "output.jpg";

            var factory = new ImagingFactory();

            WICStream stream = null;

            // ------------------------------------------------------
            // Encode a JPG image
            // ------------------------------------------------------

            // Create a WIC outputstream 
            if (File.Exists(filename))
                File.Delete(filename);

            stream = new WICStream(factory, filename, NativeFileAccess.Write);

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

            // Create a Frame encoder
            var bitmapFrameEncode = new BitmapFrameEncode(encoder);
            bitmapFrameEncode.Options.ImageQuality = 0.8f;
            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(width, height);
            var guid = PixelFormat.Format24bppBGR;
            bitmapFrameEncode.SetPixelFormat(ref guid);

            // Write a pseudo-plasma to a buffer
            int stride = PixelFormat.GetStride(PixelFormat.Format24bppBGR, width);
            var bufferSize = height * stride;
            var buffer = new DataStream(bufferSize, true, true);
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    buffer.WriteByte((byte)(x / 2.0 + 20.0 * Math.Sin(y / 40.0)));
                    buffer.WriteByte((byte)(y / 2.0 + 30.0 * Math.Sin(x / 80.0)));
                    buffer.WriteByte((byte)(x / 2.0));
                }
            }

            // Copy the pixels from the buffer to the Wic Bitmap Frame encoder
            bitmapFrameEncode.WritePixels(512, new DataRectangle(buffer.DataPointer, stride));

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

            // ------------------------------------------------------
            // Decode the previous JPG image
            // ------------------------------------------------------

            // Read input
            stream = new WICStream(factory, filename, NativeFileAccess.Read);
            var decoder = new JpegBitmapDecoder(factory);
            decoder.Initialize(stream, DecodeOptions.CacheOnDemand);
            var bitmapFrameDecode = decoder.GetFrame(0);
            var queryReader = bitmapFrameDecode.MetadataQueryReader;

            // Dump MetadataQueryreader
            queryReader.Dump(Console.Out);
            queryReader.Dispose();

            bitmapFrameDecode.Dispose();
            decoder.Dispose();
            stream.Dispose();

            // Dispose
            factory.Dispose();

            System.Diagnostics.Process.Start(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, filename)));
        }
Exemple #37
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();
                    }
                }
            }
        }
        public async Task<System.IO.MemoryStream> RenderLabelToStream(
            float imageWidth,
            float imageHeight,
            Color4 foregroundColor,
            Vector2 origin,
            TextLayout textLayout,
            float dpi = DEFAULT_DPI,
            SharpDX.DXGI.Format format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
            SharpDX.Direct2D1.AlphaMode alpha = AlphaMode.Premultiplied)
        {

            // Get stream
            var pngStream = new MemoryStream();

            using (var renderTarget = RenderLabel(
                imageWidth,
                imageHeight,
                foregroundColor,
                origin,
                textLayout,
                dpi,
                format,
                alpha))
            {

                pngStream.Position = 0;

                // Create a WIC outputstream
                using (var wicStream = new WICStream(FactoryImaging, pngStream))
                {

                    var size = renderTarget.PixelSize;

                    // Initialize a Png encoder with this stream
                    using (var wicBitmapEncoder = new PngBitmapEncoder(FactoryImaging, wicStream))
                    {

                        // Create a Frame encoder
                        using (var wicFrameEncoder = new BitmapFrameEncode(wicBitmapEncoder))
                        {
                            wicFrameEncoder.Initialize();

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


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

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

                            wicImageEncoder.WriteFrame(renderTarget, wicFrameEncoder, imgParams);

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

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

            return pngStream;
        }
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());
        }
        // 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 #41
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();
			}
		}
        //
        // 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);
        }
		/// <summary>
		/// 将 Direct2D 位图保存到文件中。
		/// </summary>
		/// <param name="image">要保存的位图。</param>
		/// <param name="fileName">要保存的文件名。</param>
		public void SaveBitmapToFile(Bitmap image, string fileName)
		{
			using (ImagingFactory2 factory = new ImagingFactory2())
			{
				using (WICStream stream = new WICStream(factory, fileName, NativeFileAccess.Write))
				{
					using (BitmapEncoder encoder = new PngBitmapEncoder(factory))
					{
						encoder.Initialize(stream);
						using (BitmapFrameEncode bitmapFrameEncode = new BitmapFrameEncode(encoder))
						{
							bitmapFrameEncode.Initialize();
							int width = image.PixelSize.Width;
							int height = image.PixelSize.Height;
							bitmapFrameEncode.SetSize(width, height);
							Guid wicPixelFormat = WICPixelFormat;
							bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);
							using (ImageEncoder imageEncoder = new ImageEncoder(factory, this.d2DDevice))
							{
								imageEncoder.WriteFrame(image, bitmapFrameEncode,
									new ImageParameters(D2PixelFormat, 96, 96, 0, 0, width, height));
								bitmapFrameEncode.Commit();
								encoder.Commit();
							}
						}
					}
				}
			}
		}
Exemple #44
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();
            }
        }
Exemple #45
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();
        }
    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 #47
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();
        }
        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 #49
0
        public void Start()
        {
            if (ProcessStarted != null)
                ProcessStarted();

            int index           = 0;
            var rendererUtil    = new RendererUtil();

            // obtain file list
            var regionList      = Directory.GetFiles(Path.Combine(worldLocation, "region"), "*.mca").ToList();
            var regionEntries   = new List<RegionEntry>();

            foreach (string region in regionList)
            {
                try
                {
                    // load the region
                    using (RegionFile regionFile = RegionFile.OpenRegion(File.OpenRead(region)))
                    {
                        var renderedChunks = new List<ChunkEntry>();

                        if (RegionLoaded != null)
                            RegionLoaded(regionFile);

                        Debug.WriteLine("Rendering region");

                        DateTime sTime = DateTime.Now;

                        #region Chunk render

                        using (var renderTarget = new BitmapRenderTarget(rendererUtil.D2DDeviceContext, CompatibleRenderTargetOptions.None, new DrawingSizeF(16, 16), new DrawingSize(16, 16), new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)))
                        {
                            foreach (var anvilChunk in regionFile.Content.Select(chunk => new Anvil(chunk)))
                            {
                                ChunkEntry entry;
                                RenderSegment(anvilChunk, renderTarget, out entry);

                                renderedChunks.Add(entry);
                            }
                        }

                        #endregion

                        #region Region compositor

                        using (var renderTarget = new BitmapRenderTarget(rendererUtil.D2DDeviceContext, CompatibleRenderTargetOptions.None, new DrawingSizeF(512, 512), new DrawingSize(512, 512), new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)))
                        {
                            renderTarget.BeginDraw();

                            renderTarget.Clear(Color.Transparent);

                            // compose the images
                            foreach (ChunkEntry chunk in renderedChunks)
                            {
                                int cxPos = chunk.XPos % 32;
                                int czPos = chunk.ZPos % 32;

                                if (cxPos < 0)
                                    cxPos = 32 + cxPos;

                                if (czPos < 0)
                                    czPos = 32 + czPos;

                                int xPos = cxPos * 16;
                                int zPos = czPos * 16;

                                renderTarget.Transform = Matrix3x2.Translation(xPos, zPos);
                                renderTarget.DrawBitmap(chunk.RenderedChunk, 1, BitmapInterpolationMode.Linear);
                            }

                            // ReSharper disable PossibleNullReferenceException
                            string[] info = Path.GetFileNameWithoutExtension(region).Split('.');
                            // ReSharper restore PossibleNullReferenceException

                            regionEntries.Add(new RegionEntry
                            {
                                RenderedRegion  = renderTarget.Bitmap,
                                XPos            = Convert.ToInt32(info[1]),
                                ZPos            = Convert.ToInt32(info[2])
                            });

                            renderTarget.EndDraw();
                        }

                        #endregion

                        Debug.WriteLine("Render time is: " + (DateTime.Now - sTime).Seconds + " seconds.");

                        if (RegionRendered != null)
                            RegionRendered();

                        #region Cleanup

                        foreach (ChunkEntry chunk in renderedChunks)
                            chunk.RenderedChunk.Dispose();

                        renderedChunks.Clear();

                        #endregion
                    }
                }
                catch (Exception exception)
                {
                    if (ProcessFailed != null)
                        ProcessFailed(exception.Message + "\nAt:\n" + exception);
                }

                if (ProgressChanged != null)
                    ProgressChanged(++index / (float)regionList.Count);
            }

            #region Extrema processor

            int xMin = 0;
            int zMin = 0;

            int xMax = 0;
            int zMax = 0;

            foreach (RegionEntry entry in regionEntries)
            {
                if (xMin > entry.XPos)
                    xMin = entry.XPos;

                if (xMax < entry.XPos)
                    xMax = entry.XPos;

                if (zMin > entry.ZPos)
                    zMin = entry.ZPos;

                if (zMax < entry.ZPos)
                    zMax = entry.ZPos;
            }

            int wSizeX = (xMax - xMin) * 512 + 512;
            int wSizeZ = (zMax - zMin) * 512 + 512;

            xMin = Math.Abs(xMin);
            zMin = Math.Abs(zMin);

            #endregion

            #region World compositor

            var ResultingBitmap = new Bitmap1(rendererUtil.D2DDeviceContext,
                                              new DrawingSize(wSizeX, wSizeZ),
                                              new BitmapProperties1
                                              {
                                                  BitmapOptions = BitmapOptions.Target,
                                                  PixelFormat   = new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)
                                              });

            rendererUtil.D2DDeviceContext.Target = ResultingBitmap;

            rendererUtil.D2DDeviceContext.BeginDraw();

            rendererUtil.D2DDeviceContext.Clear(Color.Transparent);

            foreach (RegionEntry entry in regionEntries)
            {
                int xPos = ((xMin + entry.XPos) * 512);
                int zPos = ((zMin + entry.ZPos) * 512);

                rendererUtil.D2DDeviceContext.Transform = Matrix3x2.Translation(xPos, zPos);
                rendererUtil.D2DDeviceContext.DrawBitmap(entry.RenderedRegion, 1, BitmapInterpolationMode.Linear);
            }

            rendererUtil.D2DDeviceContext.EndDraw();

            #endregion

            #region File save

            FileStream file = File.OpenWrite(Path.GetFileName(worldLocation) + ".png");

            var encoder = new PngBitmapEncoder(rendererUtil.ImagingFactory);
            encoder.Initialize(file);

            var frameEncode = new BitmapFrameEncode(encoder);
            frameEncode.Initialize();

            var imageEncoder = new ImageEncoder(rendererUtil.ImagingFactory, rendererUtil.D2DDevice);
            imageEncoder.WriteFrame(ResultingBitmap,
                                    frameEncode,
                                    new ImageParameters(
                                        new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied),
                                        96,
                                        96,
                                        0,
                                        0,
                                        wSizeX,
                                        wSizeZ));

            frameEncode.Commit();
            encoder.Commit();

            #endregion

            #region Cleanup

            file.Close();
            file.Dispose();

            foreach (RegionEntry bitmap in regionEntries)
            {
                bitmap.RenderedRegion.Dispose();
            }

            regionEntries.Clear();

            rendererUtil.Dispose();
            theBlocks.Dispose();

            ResultingBitmap.Dispose();

            #endregion

            if (ProcessComplete != null)
                ProcessComplete();
        }