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 #2
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 SharpDX.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 #3
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 #4
0
    public MemoryStream RenderToPngStream(FrameworkElement fe)
    {
        var width  = (int)Math.Ceiling(fe.ActualWidth);
        var height = (int)Math.Ceiling(fe.ActualHeight);
        // pixel format with transparency/alpha channel and RGB values premultiplied by alpha
        var pixelFormat = WicPixelFormat.Format32bppPRGBA;
        // pixel format without transparency, but one that works with Cleartype antialiasing
        //var pixelFormat = WicPixelFormat.Format32bppBGR;
        var wicBitmap = new Bitmap(
            this.WicFactory,
            width,
            height,
            pixelFormat,
            BitmapCreateCacheOption.CacheOnLoad);
        var renderTargetProperties = new RenderTargetProperties(
            RenderTargetType.Default,
            new D2DPixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied),
            //new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), // use this for non-alpha, cleartype antialiased text
            0,
            0,
            RenderTargetUsage.None,
            FeatureLevel.Level_DEFAULT);
        var renderTarget = new WicRenderTarget(
            this.D2DFactory,
            wicBitmap,
            renderTargetProperties)
        {
            //TextAntialiasMode = TextAntialiasMode.Cleartype // this only works with the pixel format with no alpha channel
            TextAntialiasMode = TextAntialiasMode.Grayscale     // this is the best we can do for bitmaps with alpha channels
        };

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

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

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

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

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

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

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

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

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

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

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

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

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

            encoder.Initialize(stream);

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

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

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

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

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

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

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

            Guid m_PixelFormat = PixelFormat.Format64bppRGBAHalf;

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

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

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

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

            using (var s = new FileStream(path, FileMode.OpenOrCreate)) {//CREATE
                s.Position = 0;
                using (var bitmapEncoder = new PngBitmapEncoder(Factory, s)) {
                    using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder)) {
                        bitmapFrameEncode.Initialize();
                        bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
                        var pixelFormat = PixelFormat.FormatDontCare;
                        bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
                        bitmapFrameEncode.WriteSource(bitmap);
                        bitmapFrameEncode.Commit();
                        bitmapEncoder.Commit();
                    }
                }
            }
            bitmap.Dispose();
            context.UnmapSubresource(textureCopy, 0);
        }
Exemple #7
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 #9
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 #10
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 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 #12
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 #13
0
        public static Result SaveTextureToStream(Device d3dDevice, Resource source, Stream stream, Guid containerFormat, Guid targetFormatGuid)
        {
            Result result = Result.Fail;

            if (source == null || d3dDevice == null || stream == null)
            {
                return(Result.InvalidArg);
            }
            result = CreateStagingTexture(d3dDevice.ImmediateContext, source, out Texture2DDescription desc, out Texture2D staging);
            if (!result.Success)
            {
                return(result);
            }

            Guid sourceFormat = desc.Format.ConvertDXGIToWICFormat();

            if (sourceFormat == Guid.Empty)
            {
                return(Result.InvalidArg);
            }

            if (ImagingFactory == null)
            {
                return(Result.NoInterface);
            }

            Guid targetFormat = targetFormatGuid;

            if (targetFormat == Guid.Empty)
            {
                switch (desc.Format)
                {
                case DXGI.Format.R32G32B32A32_Float:
                case DXGI.Format.R16G16B16A16_Float:
                    if (WIC2)
                    {
                        targetFormat = PixelFormat.Format96bppRGBFloat;
                    }
                    else
                    {
                        targetFormat = PixelFormat.Format24bppBGR;
                    }
                    break;

                case DXGI.Format.R16G16B16A16_UNorm:
                    targetFormat = PixelFormat.Format48bppBGR;
                    break;

                case DXGI.Format.B5G5R5A1_UNorm:
                    targetFormat = PixelFormat.Format16bppBGR555;
                    break;

                case DXGI.Format.B5G6R5_UNorm:
                    targetFormat = PixelFormat.Format16bppBGR565;
                    break;

                case DXGI.Format.R32_Float:
                case DXGI.Format.R16_Float:
                case DXGI.Format.R16_UNorm:
                case DXGI.Format.R8_UNorm:
                case DXGI.Format.A8_UNorm:
                    targetFormat = PixelFormat.Format8bppGray;
                    break;

                default:
                    targetFormat = PixelFormat.Format24bppBGR;
                    break;
                }
            }

            if (targetFormatGuid != Guid.Empty && targetFormatGuid != targetFormat)
            {
                return(result);
            }

            try {
                // Create a new file
                if (stream.CanWrite)
                {
                    using (BitmapEncoder encoder = new BitmapEncoder(ImagingFactory, containerFormat)) {
                        encoder.Initialize(stream);

                        using (BitmapFrameEncode frameEncode = new BitmapFrameEncode(encoder)) {
                            frameEncode.Initialize();
                            frameEncode.SetSize(desc.Width, desc.Height);
                            frameEncode.SetResolution(72.0, 72.0);


                            frameEncode.SetPixelFormat(ref targetFormat);

                            if (targetFormatGuid == Guid.Empty || targetFormat == targetFormatGuid)
                            {
                                int subresource = 0;

                                // 讓CPU存取顯存貼圖
                                // MapSubresource 在 deferred context 下不支援 MapMode.Read
                                DataBox db = d3dDevice.ImmediateContext.MapSubresource(staging, subresource, MapMode.Read, MapFlags.None, out var dataStream);

                                if (sourceFormat != targetFormat)
                                {
                                    // BGRA格式轉換
                                    using (FormatConverter formatCoverter = new FormatConverter(ImagingFactory)) {
                                        if (formatCoverter.CanConvert(sourceFormat, targetFormat))
                                        {
                                            Bitmap src = new Bitmap(ImagingFactory, desc.Width, desc.Height, sourceFormat, new DataRectangle(db.DataPointer, db.RowPitch));
                                            formatCoverter.Initialize(src, targetFormat, BitmapDitherType.None, null, 0, BitmapPaletteType.Custom);
                                            frameEncode.WriteSource(formatCoverter, new Rectangle(0, 0, desc.Width, desc.Height));
                                        }
                                    }
                                }
                                else
                                {
                                    frameEncode.WritePixels(desc.Height, new DataRectangle(db.DataPointer, db.RowPitch));
                                }

                                // 控制權歸還
                                d3dDevice.ImmediateContext.UnmapSubresource(staging, subresource);

                                frameEncode.Commit();
                                encoder.Commit();
                                result = Result.Ok;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                System.Diagnostics.Debug.WriteLine(e.ToString());
                result = Result.Fail;
            }

            Utilities.Dispose(ref staging);

            return(result);
        }
Exemple #14
0
        void colorFrameReader_FrameArrived(object sender, ColorFrameArrivedEventArgs e)
        {
            var colorFrame = e.FrameReference.AcquireFrame();

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

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

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

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

                        stopWatch.Restart();

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

                        var memoryStream = new MemoryStream();

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

                        var stream = new WICStream(imagingFactory, memoryStream);

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

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

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

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

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

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

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

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

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

				texture.Device.CopyResource(texture, textureCopy);

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

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

				toStream.Position = 0;

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

				using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder))
				{
					bitmapFrameEncode.Initialize();
					bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
					var pixelFormat = PixelFormat.FormatDontCare;
					bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
					bitmapFrameEncode.SetResolution(imageResolutionInDpi, imageResolutionInDpi);
					bitmapFrameEncode.WriteSource(bitmap);
					bitmapFrameEncode.Commit();
					bitmapEncoder.Commit();
				}
			}
			finally
			{
				bitmapEncoder?.Dispose();
				textureCopy?.Unmap(0);
				textureCopy?.Dispose();
				bitmap?.Dispose();
				imagingFactory?.Dispose();
			}
		}
Exemple #16
0
        public bool GetThumbnail(Stream stream, int width, int height, bool cachedOnly, out byte[] imageData, out ImageType imageType)
        {
            imageData = null;
            imageType = ImageType.Unknown;
            // No support for cache
            if (cachedOnly)
            {
                return(false);
            }

            Bitmap cachedBitmap = null; // used only for rotation

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

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

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

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

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

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

                                                case 3: bitmapTransformationOptions = BitmapTransformOptions.Rotate180; break;

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

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

                                                case 6: bitmapTransformationOptions = BitmapTransformOptions.Rotate90; break;

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

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

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

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

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

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

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

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

                                        using (var encoder = new BitmapEncoder(factory, formatGuid))
                                        {
                                            encoder.Initialize(output);
                                            using (var bitmapFrameEncode = new BitmapFrameEncode(encoder))
                                            {
                                                // Create image encoder
                                                var wicPixelFormat = PixelFormat.FormatDontCare;
                                                bitmapFrameEncode.Initialize();
                                                bitmapFrameEncode.SetSize(source.Size.Width, source.Size.Height);
                                                bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);
                                                bitmapFrameEncode.WriteSource(source);
                                                bitmapFrameEncode.Commit();
                                                encoder.Commit();
                                            }
                                        }
                                        imageData = output.ToArray();
                                        return(true);
                                    }
            }
            catch (Exception)
            {
                //ServiceRegistration.Get<ILogger>().Warn("WICThumbnailProvider: Error loading bitmapSource from file data stream", ex);
                return(false);
            }
            finally
            {
                cachedBitmap?.Dispose();
            }
        }
Exemple #17
0
        //create a bitmap from a texture2D. DOES NOT WORK
        public static System.Drawing.Bitmap GetTextureBitmap(Device device, Texture2D tex, int mipSlice)
        {
            int w = tex.Description.Width;
            int h = tex.Description.Height;

            var textureCopy = new Texture2D(device, new Texture2DDescription
            {
                Width             = w,
                Height            = h,
                MipLevels         = tex.Description.MipLevels,
                ArraySize         = 1,
                Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                Usage             = ResourceUsage.Staging,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags         = BindFlags.None,
                CpuAccessFlags    = CpuAccessFlags.Read,
                OptionFlags       = ResourceOptionFlags.None
            });
            DataStream dataStream;// = new DataStream(8 * tex.Description.Width * tex.Description.Height, true, true);

            DeviceContext context = device.ImmediateContext;

            //context.CopyResource(tex, textureCopy);
            context.CopySubresourceRegion(tex, mipSlice, null, textureCopy, 0);


            var dataBox = context.MapSubresource(
                textureCopy,
                mipSlice,
                0,
                MapMode.Read,
                SharpDX.Direct3D11.MapFlags.None,
                out dataStream);

            //int bytesize = w * h * 4;
            //byte[] pixels = new byte[bytesize];
            //dataStream.Read(pixels, 0, bytesize);
            //dataStream.Position = 0;

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


            ImagingFactory wicf = new ImagingFactory();

            var b = new SharpDX.WIC.Bitmap(wicf, w, h, SharpDX.WIC.PixelFormat.Format32bppBGRA, dataRectangle);


            var s = new MemoryStream();

            using (var bitmapEncoder = new PngBitmapEncoder(wicf, s))
            {
                using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder))
                {
                    bitmapFrameEncode.Initialize();
                    bitmapFrameEncode.SetSize(b.Size.Width, b.Size.Height);
                    var pixelFormat = PixelFormat.FormatDontCare;
                    bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
                    bitmapFrameEncode.WriteSource(b);
                    bitmapFrameEncode.Commit();
                    bitmapEncoder.Commit();
                }
            }

            context.UnmapSubresource(textureCopy, 0);
            textureCopy.Dispose();
            b.Dispose();



            s.Position = 0;
            var bmp = new System.Drawing.Bitmap(s);



            //Palette pal = new Palette(wf);
            //b.CopyPalette(pal);

            //byte[] pixels = new byte[w * h * 4];
            //b.CopyPixels(pixels, w * 4);
            //GCHandle handle = GCHandle.Alloc(pixels, GCHandleType.Pinned);
            //var hptr = handle.AddrOfPinnedObject();
            //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(w, h, w * 4, System.Drawing.Imaging.PixelFormat.Format32bppArgb, hptr);
            //handle.Free();

            //System.Threading.Thread.Sleep(1000);

            //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
            //System.Drawing.Imaging.BitmapData data = bmp.LockBits(
            //  new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size),
            //  System.Drawing.Imaging.ImageLockMode.WriteOnly,
            //  System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
            ////b.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
            //b.CopyPixels(data.Stride, data.Scan0, data.Height * data.Stride);
            //bmp.UnlockBits(data);


            var c1 = bmp.GetPixel(10, 2);


            //dataStream.Dispose();


            return(bmp);
        }
Exemple #18
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 #19
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 #20
0
        /// <summary>
        /// Function to persist image data to a stream.
        /// </summary>
        /// <param name="imageData"><see cref="GorgonLibrary.Graphics.GorgonImageData">Gorgon image data</see> to persist.</param>
        /// <param name="stream">Stream that will contain the data.</param>
        protected internal override void SaveToStream(GorgonImageData imageData, Stream stream)
        {
            int frameCount = 1;

            // Wrap the stream so WIC doesn't mess up the position.
            using (var wrapperStream = new GorgonStreamWrapper(stream))
            {
                using (var wic = new GorgonWICImage())
                {
                    // Find a compatible format.
                    Guid targetFormat = wic.GetGUID(imageData.Settings.Format);

                    if (targetFormat == Guid.Empty)
                    {
                        throw new IOException(string.Format(Resources.GORGFX_FORMAT_NOT_SUPPORTED, imageData.Settings.Format));
                    }

                    Guid actualFormat = targetFormat;

                    using (var encoder = new BitmapEncoder(wic.Factory, SupportedFormat))
                    {
                        try
                        {
                            encoder.Initialize(wrapperStream);
                            AddCustomMetaData(encoder, null, 0, imageData.Settings, null);
                        }
                        catch (SharpDXException)
                        {
                            // Repackage this exception to keep in line with our API.
                            throw new IOException(string.Format(Resources.GORGFX_IMAGE_FILE_INCORRECT_ENCODER, Codec));
                        }

                        using (var encoderInfo = encoder.EncoderInfo)
                        {
                            if ((imageData.Settings.ArrayCount > 1) && (CodecUseAllFrames) && (encoderInfo.IsMultiframeSupported))
                            {
                                frameCount = imageData.Settings.ArrayCount;
                            }

                            for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
                            {
                                using (var frame = new BitmapFrameEncode(encoder))
                                {
                                    var buffer = imageData.Buffers[0, frameIndex];

                                    frame.Initialize();
                                    frame.SetSize(buffer.Width, buffer.Height);
                                    frame.SetResolution(72, 72);
                                    frame.SetPixelFormat(ref actualFormat);

                                    SetFrameOptions(frame);

                                    // If the image encoder doesn't like the format we've chosen, then we'll need to convert to
                                    // the best format for the codec.
                                    if (targetFormat != actualFormat)
                                    {
                                        var rect = new DataRectangle(buffer.Data.BasePointer, buffer.PitchInformation.RowPitch);
                                        using (var bitmap = new Bitmap(wic.Factory, buffer.Width, buffer.Height, targetFormat, rect))
                                        {
                                            // If we're using a codec that supports 8 bit indexed data, then get the palette info.
                                            var paletteInfo = GetPaletteInfo(wic, bitmap);

                                            if (paletteInfo == null)
                                            {
                                                throw new IOException(string.Format(Resources.GORGFX_IMAGE_FILE_INCORRECT_ENCODER, Codec));
                                            }

                                            try
                                            {
                                                using (var converter = new FormatConverter(wic.Factory))
                                                {
                                                    converter.Initialize(bitmap, actualFormat, (BitmapDitherType)Dithering, paletteInfo.Item1, paletteInfo.Item2, paletteInfo.Item3);
                                                    if (paletteInfo.Item1 != null)
                                                    {
                                                        frame.Palette = paletteInfo.Item1;
                                                    }

                                                    AddCustomMetaData(encoder, frame, frameIndex, imageData.Settings, (paletteInfo.Item1 != null) ? paletteInfo.Item1.Colors : null);
                                                    frame.WriteSource(converter);
                                                }
                                            }
                                            finally
                                            {
                                                if (paletteInfo.Item1 != null)
                                                {
                                                    paletteInfo.Item1.Dispose();
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        // No conversion was needed, just dump as-is.
                                        AddCustomMetaData(encoder, frame, frameIndex, imageData.Settings, null);
                                        frame.WritePixels(buffer.Height, buffer.Data.BasePointer, buffer.PitchInformation.RowPitch, buffer.PitchInformation.SlicePitch);
                                    }

                                    frame.Commit();
                                }
                            }
                        }

                        encoder.Commit();
                    }
                }
            }
        }
Exemple #21
0
        /// <summary>
        /// 从rss生成图像
        /// </summary>
        /// <param name="channel">从rss源获得的数据</param>
        /// <param name="path">保存图像的路径</param>
        private void GetImageFromRss(object obj)
        {
            ImageObj image    = (ImageObj)obj;
            RssInfo  rssInfo  = image.rssInfo;
            RssMedia rssMedia = image.rssMedia;
            string   fileName = "";

            if (rssInfo == null || rssMedia == null)
            {
                return;
            }

            List <Page> pages                  = GetPageListFromRss(rssInfo, rssMedia);
            var         wicFactory             = new ImagingFactory();
            var         d2dFactory             = new SharpDX.Direct2D1.Factory();
            var         dwFactory              = new SharpDX.DirectWrite.Factory();
            var         renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default,
                                                                            new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Unknown),
                                                                            0,
                                                                            0,
                                                                            RenderTargetUsage.None, FeatureLevel.Level_DEFAULT);

            var wicBitmap = new SharpDX.WIC.Bitmap(wicFactory,
                                                   pageWidth,
                                                   pageHeight,
                                                   SharpDX.WIC.PixelFormat.Format32bppBGR,
                                                   BitmapCreateCacheOption.CacheOnLoad);
            var d2dRenderTarget = new WicRenderTarget(d2dFactory,
                                                      wicBitmap,
                                                      renderTargetProperties);

            d2dRenderTarget.AntialiasMode = AntialiasMode.PerPrimitive;
            var solidColorBrush = new SolidColorBrush(d2dRenderTarget,
                                                      new SharpDX.Color(this.backgroundColor.R,
                                                                        this.backgroundColor.G,
                                                                        this.backgroundColor.B,
                                                                        this.backgroundColor.A));
            var textBodyBrush = new SolidColorBrush(d2dRenderTarget,
                                                    new SharpDX.Color(rssMedia.RssBodyProp.
                                                                      TextColor.R,
                                                                      rssMedia.RssBodyProp.TextColor.G,
                                                                      rssMedia.RssBodyProp.TextColor.B,
                                                                      rssMedia.RssBodyProp.TextColor.A));
            var titleColorBrush = new SolidColorBrush(d2dRenderTarget,
                                                      new SharpDX.Color(rssMedia.RssTitleProp.TextColor.R,
                                                                        rssMedia.RssTitleProp.TextColor.G,
                                                                        rssMedia.RssTitleProp.TextColor.B,
                                                                        rssMedia.RssTitleProp.TextColor.A));
            var publishDateColorBrush = new SolidColorBrush(d2dRenderTarget,
                                                            new SharpDX.Color(rssMedia.RssPublishTimeProp.TextColor.R,
                                                                              rssMedia.RssPublishTimeProp.TextColor.G,
                                                                              rssMedia.RssPublishTimeProp.TextColor.B,
                                                                              rssMedia.RssPublishTimeProp.TextColor.A));
            TextLayout textLayout;

            try
            {
                int count = 0;

                foreach (Page page in pages)
                {
                    d2dRenderTarget.BeginDraw();
                    d2dRenderTarget.Clear(new SharpDX.Color(this.backgroundColor.R,
                                                            this.backgroundColor.G,
                                                            this.backgroundColor.B,
                                                            this.backgroundColor.A));

                    foreach (Line line in page.lines)
                    {
                        foreach (Block block in line.content)
                        {
                            TextFormat textFormat = new TextFormat(dwFactory,
                                                                   block.font.FontFamily.Name,
                                                                   block.font.Size);
                            textLayout = new TextLayout(dwFactory,
                                                        block.content,
                                                        textFormat,
                                                        block.width,
                                                        block.height);
                            switch (block.type)
                            {
                            case RssBodyType.Title:
                                textLayout.SetUnderline(rssMedia.RssTitleProp.TextFont.Underline,
                                                        new TextRange(0, block.content.Length));
                                textLayout.SetFontStyle(rssMedia.RssTitleProp.TextFont.Italic ? FontStyle.Italic : FontStyle.Normal,
                                                        new TextRange(0, block.content.Length));
                                textLayout.SetFontWeight(rssMedia.RssTitleProp.TextFont.Bold ? FontWeight.Bold : FontWeight.Normal,
                                                         new TextRange(0, block.content.Length));
                                d2dRenderTarget.DrawTextLayout(new Vector2(block.left, block.top), textLayout, titleColorBrush);
                                break;

                            case RssBodyType.Time:
                                textLayout.SetUnderline(rssMedia.RssPublishTimeProp.TextFont.Underline,
                                                        new TextRange(0, block.content.Length));
                                textLayout.SetFontStyle(rssMedia.RssPublishTimeProp.TextFont.Italic ? FontStyle.Italic : FontStyle.Normal,
                                                        new TextRange(0, block.content.Length));
                                textLayout.SetFontWeight(rssMedia.RssPublishTimeProp.TextFont.Bold ? FontWeight.Bold : FontWeight.Normal,
                                                         new TextRange(0, block.content.Length));
                                d2dRenderTarget.DrawTextLayout(new Vector2(block.left, block.top), textLayout, publishDateColorBrush);
                                break;

                            case RssBodyType.Body:
                                textLayout.SetUnderline(rssMedia.RssBodyProp.TextFont.Underline,
                                                        new TextRange(0, block.content.Length));
                                textLayout.SetFontStyle(rssMedia.RssBodyProp.TextFont.Italic ? FontStyle.Italic : FontStyle.Normal,
                                                        new TextRange(0, block.content.Length));
                                textLayout.SetFontWeight(rssMedia.RssBodyProp.TextFont.Bold ? FontWeight.Bold : FontWeight.Normal,
                                                         new TextRange(0, block.content.Length));
                                d2dRenderTarget.DrawTextLayout(new Vector2(block.left, block.top), textLayout, textBodyBrush);
                                break;

                            default:
                                break;
                            }
                            textFormat.Dispose();
                            textFormat = null;
                        }
                    }

                    d2dRenderTarget.EndDraw();

                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    fileName = string.Format("{0}{1}.jpg", path, DateTime.Now.Ticks.ToString());
                    var stream  = new WICStream(wicFactory, fileName, NativeFileAccess.Write);
                    var encoder = new PngBitmapEncoder(wicFactory);
                    encoder.Initialize(stream);
                    var bitmapFrameEncode = new BitmapFrameEncode(encoder);
                    bitmapFrameEncode.Initialize();
                    bitmapFrameEncode.SetSize(pageWidth, pageHeight);
                    var pixelFormatGuid = SharpDX.WIC.PixelFormat.FormatDontCare;
                    bitmapFrameEncode.SetPixelFormat(ref pixelFormatGuid);
                    bitmapFrameEncode.WriteSource(wicBitmap);
                    bitmapFrameEncode.Commit();
                    encoder.Commit();
                    bitmapFrameEncode.Dispose();
                    encoder.Dispose();
                    stream.Dispose();

                    Console.WriteLine("*********image count is : " + count++);
                    //发送单个图片生成事件
                    if (SingleGenerateCompleteEvent != null)
                    {
                        SingleGenerateCompleteEvent(fileName);
                    }
                }
                //发送生成完成事件
                if (GenerateCompleteEvent != null)
                {
                    GenerateCompleteEvent(path);
                    //停止线程,从字典删除
                    StopGenerate(rssMedia.CachePath);
                }
            }
            catch (ThreadAbortException aborted)
            {
                Trace.WriteLine("rss 图片生成线程终止 : " + aborted.Message);
            }
            catch (Exception ex)
            {
                Trace.WriteLine("rss 图片生成遇到bug : " + ex.Message);
            }
            finally
            {
                wicFactory.Dispose();
                d2dFactory.Dispose();
                dwFactory.Dispose();
                wicBitmap.Dispose();
                d2dRenderTarget.Dispose();
                solidColorBrush.Dispose();
                textBodyBrush.Dispose();
                titleColorBrush.Dispose();
                publishDateColorBrush.Dispose();
                rssInfo.Dispose();
                rssMedia.Dispose();
                wicFactory            = null;
                d2dFactory            = null;
                dwFactory             = null;
                wicBitmap             = null;
                d2dRenderTarget       = null;
                solidColorBrush       = null;
                textBodyBrush         = null;
                titleColorBrush       = null;
                publishDateColorBrush = null;
                rssInfo  = null;
                rssMedia = null;
                pages.Clear();
                pages = null;
            }
        }
		/// <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 #23
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             = texture.Description.Width,
                    Height            = texture.Description.Height,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = texture.Description.Format,
                    Usage             = ResourceUsage.Staging,
                    SampleDescription = new SampleDescription(1, 0),
                    BindFlags         = BindFlags.None,
                    CpuAccessFlags    = CpuAccessFlags.Read,
                    OptionFlags       = ResourceOptionFlags.None
                });

                texture.Device.CopyResource(texture, textureCopy);

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

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

                toStream.Position = 0;

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

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

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

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

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

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

            RC.CopyResource(res, textureCopy);

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

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

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

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

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

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

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

            RC.UnmapSubresource(textureCopy, 0);
            textureCopy.Dispose();
            bitmap.Dispose();
        }
        // 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 #29
0
        private Result SaveWicTextureToFileFix(
            DeviceContext context,
            Texture2D source,
            ref Guid guidContainerFormat,
            string fileName)
        {
            if (fileName == null)
            {
                return(Result.InvalidArg);
            }

            var res = CaptureTextureFix(context, source, out var desc, out var staging);

            if (res.Failure)
            {
                return(res);
            }

            Guid pfGuid;
            //bool sRGB = false;
            Guid targetGuid;

            switch (desc.Format)
            {
            case Format.R32G32B32A32_Float: pfGuid = PixelFormat.Format128bppRGBAFloat; break;

            case Format.R16G16B16A16_Float: pfGuid = PixelFormat.Format64bppRGBAHalf; break;

            case Format.R16G16B16A16_UNorm: pfGuid = PixelFormat.Format64bppRGBA; break;

            case Format.R10G10B10_Xr_Bias_A2_UNorm: pfGuid = PixelFormat.Format32bppRGBA1010102XR; break;     // DXGI 1.1

            case Format.R10G10B10A2_UNorm: pfGuid = PixelFormat.Format32bppRGBA1010102; break;

            case Format.B5G5R5A1_UNorm: pfGuid = PixelFormat.Format16bppBGRA5551; break;

            case Format.B5G6R5_UNorm: pfGuid = PixelFormat.Format16bppBGR565; break;

            case Format.R32_Float: pfGuid = PixelFormat.Format32bppGrayFloat; break;

            case Format.R16_Float: pfGuid = PixelFormat.Format16bppGrayHalf; break;

            case Format.R16_UNorm: pfGuid = PixelFormat.Format16bppGray; break;

            case Format.R8_UNorm: pfGuid = PixelFormat.Format8bppGray; break;

            case Format.A8_UNorm: pfGuid = PixelFormat.Format8bppAlpha; break;

            case Format.R8G8B8A8_UNorm:
                pfGuid = PixelFormat.Format32bppRGBA;
                break;

            case Format.R8G8B8A8_UNorm_SRgb:
                pfGuid = PixelFormat.Format32bppRGBA;
                //sRGB = true;
                break;

            case Format.B8G8R8A8_UNorm:     // DXGI 1.1
                pfGuid = PixelFormat.Format32bppBGRA;
                break;

            case Format.B8G8R8A8_UNorm_SRgb:     // DXGI 1.1
                pfGuid = PixelFormat.Format32bppBGRA;
                //sRGB = true;
                break;

            case Format.B8G8R8X8_UNorm:     // DXGI 1.1
                pfGuid = PixelFormat.Format32bppBGR;
                break;

            case Format.B8G8R8X8_UNorm_SRgb:     // DXGI 1.1
                pfGuid = PixelFormat.Format32bppBGR;
                //sRGB = true;
                break;

            default:
                return(Result.GetResultFromWin32Error(unchecked ((int)0x80070032)));
            }

            // Create file
            var fs      = new FileStream(fileName, FileMode.Create);
            var encoder = new BitmapEncoder(Direct2D.ImageFactory, guidContainerFormat);

            encoder.Initialize(fs);


            var frameEncode = new BitmapFrameEncode(encoder);

            frameEncode.Initialize();
            frameEncode.SetSize(desc.Width, desc.Height);
            frameEncode.SetResolution(72.0, 72.0);


            switch (desc.Format)
            {
            case Format.R32G32B32A32_Float:
            case Format.R16G16B16A16_Float:
                targetGuid = PixelFormat.Format24bppBGR;
                break;

            case Format.R16G16B16A16_UNorm: targetGuid = PixelFormat.Format48bppBGR; break;

            case Format.B5G5R5A1_UNorm: targetGuid = PixelFormat.Format16bppBGR555; break;

            case Format.B5G6R5_UNorm: targetGuid = PixelFormat.Format16bppBGR565; break;

            case Format.R32_Float:
            case Format.R16_Float:
            case Format.R16_UNorm:
            case Format.R8_UNorm:
            case Format.A8_UNorm:
                targetGuid = PixelFormat.Format8bppGray;
                break;

            default:
                targetGuid = PixelFormat.Format24bppBGR;
                break;
            }

            frameEncode.SetPixelFormat(ref targetGuid);

            #region Write

            var db = context.MapSubresource(staging, 0, MapMode.Read, MapFlags.None, out _);

            if (pfGuid != targetGuid)
            {
                var formatConverter = new FormatConverter(Direct2D.ImageFactory);

                if (formatConverter.CanConvert(pfGuid, targetGuid))
                {
                    var src = new Bitmap(Direct2D.ImageFactory, desc.Width, desc.Height, pfGuid,
                                         new DataRectangle(db.DataPointer, db.RowPitch));
                    formatConverter.Initialize(src, targetGuid, BitmapDitherType.None, null, 0, BitmapPaletteType.Custom);
                    frameEncode.WriteSource(formatConverter, new Rectangle(0, 0, desc.Width, desc.Height));
                }
            }
            else
            {
                frameEncode.WritePixels(desc.Height, new DataRectangle(db.DataPointer, db.RowPitch));
            }

            context.UnmapSubresource(staging, 0);

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

            #endregion

            frameEncode.Dispose();
            encoder.Dispose();

            fs.Close();

            return(Result.Ok);
        }
    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;
      }
    }
        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();
        }
        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 #33
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();
        }