Ejemplo n.º 1
0
        public static Texture2D LoadTextureFromFile(SharpDX.Direct3D11.Device aDevice, string aFullPath)
        {
            Texture2D      result = null;
            ImagingFactory fac    = new ImagingFactory();

            BitmapDecoder     bc  = new SharpDX.WIC.BitmapDecoder(fac, aFullPath, DecodeOptions.CacheOnLoad);
            BitmapFrameDecode bfc = bc.GetFrame(0);
            FormatConverter   fc  = new FormatConverter(fac);

            System.Guid desiredFormat = PixelFormat.Format32bppBGRA;
            fc.Initialize(bfc, desiredFormat);

            float[] buffer = new float[fc.Size.Width * fc.Size.Height];

            bool canConvert = fc.CanConvert(bfc.PixelFormat, desiredFormat);

            fc.CopyPixels <float>(buffer);
            GCHandle handle      = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            float    sizeOfPixel = PixelFormat.GetBitsPerPixel(desiredFormat) / 8;

            if (sizeOfPixel != 4.0f)
            {
                throw new System.Exception("Unknown error");
            }

            DataBox db = new DataBox(handle.AddrOfPinnedObject(), fc.Size.Width * (int)sizeOfPixel, fc.Size.Width * fc.Size.Height * (int)sizeOfPixel);

            int width  = fc.Size.Width;
            int height = fc.Size.Height;

            Texture2DDescription fTextureDesc = new Texture2DDescription();

            fTextureDesc.CpuAccessFlags    = CpuAccessFlags.None;
            fTextureDesc.Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
            fTextureDesc.Width             = width;
            fTextureDesc.Height            = height;
            fTextureDesc.Usage             = ResourceUsage.Default;
            fTextureDesc.MipLevels         = 1;
            fTextureDesc.ArraySize         = 1;
            fTextureDesc.OptionFlags       = ResourceOptionFlags.None;
            fTextureDesc.BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource;
            fTextureDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);

            result = new Texture2D(aDevice, fTextureDesc, new DataBox[] { db });
            handle.Free();

            return(result);
        }
Ejemplo n.º 2
0
        public static Image2D LoadFromFile(string path, Canvas canvas)
        {
            ImagingFactory   imagingFactory = new ImagingFactory();
            NativeFileStream fileStream     = new NativeFileStream(path,
                                                                   NativeFileMode.Open, NativeFileAccess.Read);
            BitmapDecoder     bitmapDecoder = new BitmapDecoder(imagingFactory, fileStream, DecodeOptions.CacheOnDemand);
            BitmapFrameDecode frame         = bitmapDecoder.GetFrame(0);
            FormatConverter   converter     = new FormatConverter(imagingFactory);

            converter.Initialize(frame, PixelFormatWic.Format32bppPRGBA);

            var result = new Image2D();

            result.nativeBitmap = Bitmap2D.FromWicBitmap(canvas.NativeDeviceContext, converter);
            return(result);
        }
Ejemplo n.º 3
0
        public static D2DBitmap GetBitmap(BitmapData pBitmapData, RenderTarget pRenderer)
        {
            try
            {
                BitmapDecoder decoder = ImagingFactory.CreateDecoderFromFilename(pBitmapData.FilePath, DesiredAccess.Read, DecodeMetadataCacheOptions.OnDemand);//.CreateDecoderFromStream(pBitmapData.Data, DecodeMetadataCacheOptions.OnDemand);

                BitmapFrameDecode  frameDeocder    = decoder.GetFrame(0);
                WICFormatConverter formatConverter = ImagingFactory.CreateFormatConverter();
                BitmapSource       src             = frameDeocder.ToBitmapSource();
                formatConverter.Initialize(frameDeocder.ToBitmapSource(), PixelFormats.Pf32bppPBGRA, BitmapDitherType.None, BitmapPaletteType.MedianCut);

                return(pRenderer.CreateBitmapFromWicBitmap(formatConverter.ToBitmapSource()));
            }
            catch (Exception)
            {
                return(null);
            }
        }
Ejemplo n.º 4
0
        private Bitmap CreateBitmap([NotNull] IImage image)
        {
            using (Stream stream = image.GetStream())
                using (BitmapDecoder decoder = new BitmapDecoder(
                           _imagingFactory,
                           stream,
                           DecodeOptions.CacheOnDemand))
                    using (BitmapFrameDecode source = decoder.GetFrame(0))
                        using (FormatConverter converter = new FormatConverter(_imagingFactory))
                        {
                            converter.Initialize(source, SharpDX.WIC.PixelFormat.Format32bppPRGBA);

                            Bitmap bitmap = Bitmap.FromWicBitmap(_renderTarget, converter);

                            Debug.Assert(bitmap != null, "bitmap != null");
                            return(bitmap);
                        }
        }
Ejemplo n.º 5
0
        public static Bitmap1 GetBitmap(D2D.DeviceContext context, string filePath)
        {
            ImagingFactory imagingFactory = new ImagingFactory();

            NativeFileStream fileStream = new NativeFileStream(
                Package.Current.InstalledLocation.Path + filePath,
                NativeFileMode.Open, NativeFileAccess.Read);

            BitmapDecoder bitmapDecoder = new BitmapDecoder(
                imagingFactory, fileStream, DecodeOptions.CacheOnDemand);

            BitmapFrameDecode frame = bitmapDecoder.GetFrame(0);

            FormatConverter converter = new FormatConverter(imagingFactory);

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

            return(SharpDX.Direct2D1.Bitmap1.FromWicBitmap(context, converter));
        }
            //---------------------------------------------------------------------------------------------------------
            /// <summary>
            /// Загрузка рисунка из файла
            /// </summary>
            /// <param name="file_name">Имя файла</param>
            /// <returns>Рисунок Direct2D</returns>
            //---------------------------------------------------------------------------------------------------------
            public static Direct2D.Bitmap LoadFromFile(String file_name)
            {
                if (mD2DImagingFactory == null)
                {
                    mD2DImagingFactory = new ImagingFactory();
                }

                NativeFileStream file_stream = new NativeFileStream(file_name, NativeFileMode.Open, NativeFileAccess.Read);

                BitmapDecoder     bitmap_decoder = new BitmapDecoder(mD2DImagingFactory, file_stream, DecodeOptions.CacheOnDemand);
                BitmapFrameDecode frame          = bitmap_decoder.GetFrame(0);

                FormatConverter converter = new FormatConverter(mD2DImagingFactory);

                converter.Initialize(frame, PixelFormat.Format32bppPRGBA);

                Direct2D.Bitmap bitmap = Direct2D.Bitmap.FromWicBitmap(D2DRenderTarget, converter);
                return(bitmap);
            }
Ejemplo n.º 7
0
        public static WICBitmap LoadBitmap(string rele_path)
        {
            var Imgc     = new ImagingFactory();
            var Demcoder = new BitmapDecoder(Imgc, rele_path, SharpDX.IO.NativeFileAccess.Read, DecodeOptions.CacheOnLoad);

            BitmapFrameDecode nm_opb = Demcoder.GetFrame(0);
            var convert = new FormatConverter(Imgc);

            convert.Initialize(nm_opb, SharpDX.WIC.PixelFormat.Format32bppPBGRA);

            var Init_action = new WICBitmap(Imgc, convert, BitmapCreateCacheOption.CacheOnLoad);

            Imgc.Dispose();
            Demcoder.Dispose();
            nm_opb.Dispose();
            convert.Dispose();

            return(Init_action);
        }
 // Token: 0x060001A4 RID: 420 RVA: 0x0001465C File Offset: 0x0001285C
 public override void LoadFromStream(string textureKey, Stream stream)
 {
     try
     {
         using (BitmapDecoder bitmapDecoder = new BitmapDecoder(this.imagingFactory, stream, DecodeOptions.CacheOnDemand))
         {
             BitmapFrameDecode frame = bitmapDecoder.GetFrame(0);
             using (FormatConverter formatConverter = new FormatConverter(this.imagingFactory))
             {
                 formatConverter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA);
                 SharpDX.Direct2D1.Bitmap bitmap = SharpDX.Direct2D1.Bitmap.FromWicBitmap(this.renderContext.RenderTarget, formatConverter);
                 base.TextureCache[textureKey] = new D3D11Texture(bitmap, null);
             }
         }
     }
     catch (Exception exception)
     {
         Logger.Error(exception, textureKey);
     }
 }
Ejemplo n.º 9
0
        protected override Texture LoadStaging(Stream stream)
        {
            using var wicStream  = new WICStream(_wicFactory, stream);
            using var decoder    = new BitmapDecoder(_wicFactory, wicStream, DecodeOptions.CacheOnDemand);
            using var formatConv = new FormatConverter(_wicFactory);
            // Do NOT dispose the frame as it might lead to a crash.
            // Seems like it's owned by the decoder, so hopefully there should be no leaks.
            BitmapFrameDecode frame = decoder.GetFrame(0);

            formatConv.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppRGBA);

            uint    width          = (uint)frame.Size.Width;
            uint    height         = (uint)frame.Size.Height;
            Texture stagingTexture = _rf.CreateTexture(TextureDescription.Texture2D(
                                                           width, height, mipLevels: 1, arrayLayers: 1,
                                                           PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.Staging
                                                           ));

            MappedResource map      = _gd.Map(stagingTexture, MapMode.Write);
            uint           rowWidth = width * 4;

            if (rowWidth == map.RowPitch)
            {
                formatConv.CopyPixels((int)map.RowPitch, map.Data, (int)map.SizeInBytes);
            }
            else
            {
                for (uint y = 0; y < height; y++)
                {
                    byte *dstStart = (byte *)map.Data + y * map.RowPitch;
                    formatConv.CopyPixels(
                        new RawBox(x: 0, (int)y, (int)width, height: 1),
                        (int)map.RowPitch,
                        new SharpDX.DataPointer(dstStart, (int)map.RowPitch)
                        );
                }
            }

            _gd.Unmap(stagingTexture);
            return(stagingTexture);
        }
Ejemplo n.º 10
0
        private static bool ImagesAreIdentical(BitmapSource imageSource1, BitmapSource imageSource2)
        {
            // First compare images as objects - the luckiest case is when it's the same object
            BitmapFrameDecode imageBitmap1 = imageSource1 as BitmapFrameDecode;
            BitmapFrameDecode imageBitmap2 = imageSource2 as BitmapFrameDecode;

            if (imageBitmap1 != null && imageBitmap2 != null &&
                imageBitmap1.Decoder.Frames.Count == 1 && imageBitmap2.Decoder.Frames.Count == 1 &&
                imageBitmap1.Decoder.Frames[0] == imageBitmap2.Decoder.Frames[0])
            {
                return(true); // ImageSources have the same instance of bitmap data. They are obviousely identical.
            }

            if (imageSource1.Format.BitsPerPixel != imageSource2.Format.BitsPerPixel ||
                imageSource1.PixelWidth != imageSource2.PixelWidth ||
                imageSource1.PixelHeight != imageSource2.PixelHeight ||
                imageSource1.DpiX != imageSource2.DpiX ||
                imageSource1.DpiY != imageSource2.DpiY ||
                imageSource1.Palette != imageSource2.Palette)
            {
                return(false); // Images have different characteristics
            }

            int stride     = ((imageSource1.PixelWidth * imageSource1.Format.BitsPerPixel) + 7) / 8;
            int bufferSize = (stride * (imageSource1.PixelHeight - 1)) + stride;

            Byte[] buffer1 = new Byte[bufferSize];
            Byte[] buffer2 = new Byte[bufferSize];

            imageSource1.CopyPixels(buffer1, stride, /*offset:*/ 0);
            imageSource2.CopyPixels(buffer2, stride, /*offset:*/ 0);
            for (int i = 0; i < bufferSize; i++)
            {
                if (buffer1[i] != buffer2[i])
                {
                    return(false); // Images have different pixels
                }
            }

            return(true); // Images are equal
        }
Ejemplo n.º 11
0
        public void Play(string gifPath, int fps = 24)
        {
            DisposeImage();
            _fpsMilliseconds = 1000 / fps;
            _currentImage    = new List <SharpDX.Direct2D1.Bitmap>();

            BitmapDecoder decoder = new BitmapDecoder(_imgFactory, gifPath, NativeFileAccess.Read, DecodeOptions.CacheOnLoad);

            for (int i = 0; i < decoder.FrameCount; i++)
            {
                using (FormatConverter imgConvert = new FormatConverter(_imgFactory))
                {
                    BitmapFrameDecode source = decoder.GetFrame(i);
                    imgConvert.Initialize(source, SharpDX.WIC.PixelFormat.Format32bppPBGRA);

                    _currentImage.Add(SharpDX.Direct2D1.Bitmap.FromWicBitmap(_renderTarget, imgConvert));
                }
            }
            _running = true;
            _thdMain.Start();
        }
Ejemplo n.º 12
0
        private static D2DBitmap CreateBitmapFromDecoder(RenderTarget renderTarget, ImagingFactory wicFactory, BitmapDecoder decoder)
        {
            // Create the initial frame.
            BitmapFrameDecode source = decoder.GetFrame(0);
            // Convert the image format to 32bppPBGRA -- which Direct2D expects.
            FormatConverter converter = wicFactory.CreateFormatConverter();

            converter.Initialize(
                source.ToBitmapSource(),
                PixelFormats.Pbgra32Bpp,
                BitmapDitherType.None,
                BitmapPaletteType.MedianCut
                );

            // Create a Direct2D bitmap from the WIC bitmap.
            D2DBitmap ret = renderTarget.CreateBitmapFromWicBitmap(converter.ToBitmapSource());

            converter.Dispose();
            source.Dispose();

            return(ret);
        }
        private static Bitmap Decode(RenderTarget device, BitmapDecoder decoder)
        {
            using (BitmapFrameDecode frame = decoder.GetFrame(0))
            {
                FormatConverter converter = new FormatConverter(imageFactory); // Converter get clobbered on failure so we're not wrapping this in a using.
                foreach (Guid format in PixelFormatEnumerator)
                {
                    try
                    {
                        converter.Initialize(frame, format);
                        return(Bitmap.FromWicBitmap(device, converter));
                    }
                    catch // Ignore error here, just try another format. We'll throw an error below if we exhaust all options.
                    {
                        converter?.Dispose();
                        converter = new FormatConverter(imageFactory);
                    }
                }
                converter?.Dispose();
            }

            throw new Exception("Unsupported Image Format!");
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Determines metadata for image
        /// </summary>
        /// <param name="flags">The flags.</param>
        /// <param name="decoder">The decoder.</param>
        /// <param name="frame">The frame.</param>
        /// <param name="pixelFormat">The pixel format.</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">If pixel format is not supported.</exception>
        private static ImageDescription?DecodeMetadata(WICFlags flags, BitmapDecoder decoder, BitmapFrameDecode frame, out Guid pixelFormat)
        {
            var size = frame.Size;

            var metadata = new ImageDescription
            {
                Dimension = TextureDimension.Texture2D,
                Width     = size.Width,
                Height    = size.Height,
                Depth     = 1,
                MipLevels = 1,
                ArraySize = (flags & WICFlags.AllFrames) != 0 ? decoder.FrameCount : 1,
                Format    = DetermineFormat(frame.PixelFormat, flags, out pixelFormat)
            };

            if (metadata.Format == DXGI.Format.Unknown)
            {
                return(null);
            }

            return(metadata);
        }
Ejemplo n.º 15
0
        public Texture LoadTextureFromFile(string fileName, bool generateMip, SamplerState samplerState)
        {
            BitmapDecoder     decoder          = new BitmapDecoder(_imagingFactory, fileName, DecodeOptions.CacheOnDemand);
            BitmapFrameDecode bitmapFirstFrame = decoder.GetFrame(0);

            Utilities.Dispose(ref decoder);

            FormatConverter imageFormatConverter = new FormatConverter(_imagingFactory);

            imageFormatConverter.Initialize(
                bitmapFirstFrame,
                PixelFormat.Format32bppRGBA,
                BitmapDitherType.None, null, 0.0, BitmapPaletteType.Custom);

            int        stride = imageFormatConverter.Size.Width * 4;
            DataStream buffer = new DataStream(imageFormatConverter.Size.Height * stride, true, true);

            imageFormatConverter.CopyPixels(stride, buffer);

            int width  = imageFormatConverter.Size.Width;
            int height = imageFormatConverter.Size.Height;

            Texture2DDescription textureDescription = new Texture2DDescription()
            {
                Width             = width,
                Height            = height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.R8G8B8A8_UNorm,
                SampleDescription = _directX3DGraphics.SampleDescription, // new SampleDescription(1,0)
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = (generateMip ? ResourceOptionFlags.GenerateMipMaps : ResourceOptionFlags.None)
            };
            Texture2D textureObject = new Texture2D(_directX3DGraphics.Device, textureDescription, new DataRectangle(buffer.DataPointer, stride));

            int mipLevels = (int)Math.Log(width, 2) + 1;
            ShaderResourceViewDescription shaderResourceViewDescription = new ShaderResourceViewDescription();

            shaderResourceViewDescription.Dimension = ShaderResourceViewDimension.Texture2D;
            shaderResourceViewDescription.Format    = Format.R8G8B8A8_UNorm;
            shaderResourceViewDescription.Texture2D = new ShaderResourceViewDescription.Texture2DResource
            {
                MostDetailedMip = 0,
                MipLevels       = -1 // (generateMip ? mipLevels : -1)
            };
            ShaderResourceView shaderResourceView = new ShaderResourceView(_directX3DGraphics.Device, textureObject, shaderResourceViewDescription);

            if (generateMip)
            {
                _directX3DGraphics.DeviceContext.GenerateMips(shaderResourceView);
            }

            Utilities.Dispose(ref imageFormatConverter);
            string[] path = fileName.Split('\\');
            fileName = path[path.Length - 1];

            Texture texture = new Texture(textureObject, shaderResourceView, width, height, fileName, samplerState);

            textures.Add(texture.Name, texture);

            return(texture);
        }
Ejemplo n.º 16
0
        private static ShaderResourceView LoadFromDecoder(D3DDevice device, ImagingFactory factory, BitmapDecoder bitmapDecoder)
        {
            if (bitmapDecoder.FrameCount == 0)
            {
                throw new ArgumentException("Image file successfully loaded, but it has no image frames.");
            }

            BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0);
            BitmapSource      bitmapSource      = bitmapFrameDecode.ToBitmapSource();

            // create texture description
            Texture2DDescription textureDescription = new Texture2DDescription()
            {
                Width             = bitmapSource.Size.Width,
                Height            = bitmapSource.Size.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.R8G8B8A8UNorm,
                SampleDescription = new SampleDescription()
                {
                    Count   = 1,
                    Quality = 0,
                },
                Usage                        = Usage.Dynamic,
                BindingOptions               = BindingOptions.ShaderResource,
                CpuAccessOptions             = CpuAccessOptions.Write,
                MiscellaneousResourceOptions = MiscellaneousResourceOptions.None
            };

            // create texture
            Texture2D texture = device.CreateTexture2D(textureDescription);

            // Create a format converter
            FormatConverter converter = factory.CreateFormatConverter();

            converter.Initialize(
                bitmapSource,
                PixelFormats.Prgba32Bpp,
                BitmapDitherType.None,
                BitmapPaletteType.Custom);

            // get bitmap data
            byte[] buffer = converter.CopyPixels();

            // Copy bitmap data to texture
            MappedTexture2D texmap = texture.Map(0, Map.WriteDiscard, Microsoft.WindowsAPICodePack.DirectX.Direct3D10.MapOptions.None);

            Marshal.Copy(buffer, 0, texmap.Data, buffer.Length);
            texture.Unmap(0);

            // create shader resource view description
            ShaderResourceViewDescription srvDescription = new ShaderResourceViewDescription()
            {
                Format        = textureDescription.Format,
                ViewDimension = ShaderResourceViewDimension.Texture2D,
                Texture2D     = new Texture2DShaderResourceView()
                {
                    MipLevels       = textureDescription.MipLevels,
                    MostDetailedMip = 0
                }
            };

            // create shader resource view from texture
            return(device.CreateShaderResourceView(texture, srvDescription));
        }
Ejemplo n.º 17
0
        public BitmapBrush makeBitmapBrush(string imgName, RenderTarget renderTarget, bool blankImage = false)
        {
            //TODO : 여기 바꿔라!
            string imageSrc = "";

            if (blankImage)
            {
                SharpDX.Direct2D1.PixelFormat pf = new SharpDX.Direct2D1.PixelFormat()
                {
                    AlphaMode = D3DHandler.ALPHA_MODE,
                    Format    = D3DHandler.RENDER_FORMAT
                };

                BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, pf);
                return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
            if (resourceCore.getFile(imgName, out ResFile resFile))
            {
                ImagingFactory imagingFactory = new ImagingFactory();

                /*NativeFileStream fileStream = new NativeFileStream(imageSrc,
                 *  NativeFileMode.Open, NativeFileAccess.Read);*/
                MemoryStream  ms            = new MemoryStream(resFile.rawData);
                BitmapDecoder bitmapDecoder = new BitmapDecoder(imagingFactory, ms, DecodeOptions.CacheOnDemand);

                BitmapFrameDecode frame = bitmapDecoder.GetFrame(0);

                FormatConverter converter = new FormatConverter(imagingFactory);
                converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA);

                Bitmap bitmap = Bitmap.FromWicBitmap(renderTarget, converter);

                Utilities.Dispose(ref bitmapDecoder);
                Utilities.Dispose(ref imagingFactory);
                Utilities.Dispose(ref converter);

                return(new BitmapBrush(renderTarget, bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
            else
            {
                Console.WriteLine("{0} missing", imageSrc);

                SharpDX.Direct2D1.PixelFormat pf = new SharpDX.Direct2D1.PixelFormat()
                {
                    AlphaMode = D3DHandler.ALPHA_MODE,
                    Format    = D3DHandler.RENDER_FORMAT
                };
                BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, new Size2F(30f, 30f), new Size2(1, 1), pf);

                pallete.BeginDraw();
                pallete.Clear(Color.Purple);
                pallete.EndDraw();

                return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
        }
Ejemplo n.º 18
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();
            }
        }
Ejemplo n.º 19
0
    private static TextureDescription DecodeMetadata(ImagingFactory imagingFactory, WicFlags flags, BitmapDecoder decoder, BitmapFrameDecode frame, out Guid pixelFormat)
    {
      var size = frame.Size;

      var description = new TextureDescription
      {
        Dimension = TextureDimension.Texture2D,
        Width = size.Width,
        Height = size.Height,
        Depth = 1,
        MipLevels = 1,
        ArraySize = (flags & WicFlags.AllFrames) != 0 ? decoder.FrameCount : 1,
        Format = DetermineFormat(imagingFactory, frame.PixelFormat, flags, out pixelFormat)
      };

      if (description.Format == DataFormat.Unknown)
        throw new NotSupportedException("The pixel format is not supported.");

      if ((flags & WicFlags.IgnoreSrgb) == 0)
      {
        // Handle sRGB.
#pragma warning disable 168
        try
        {
          Guid containerFormat = decoder.ContainerFormat;
          var metareader = frame.MetadataQueryReader;
          if (metareader != null)
          {
            // Check for sRGB color space metadata.
            bool sRgb = false;

            if (containerFormat == ContainerFormatGuids.Png)
            {
              // Check for sRGB chunk.
              if (metareader.GetMetadataByName("/sRGB/RenderingIntent") != null)
                sRgb = true;
            }
            else if (containerFormat == ContainerFormatGuids.Jpeg)
            {
              if (Equals(metareader.GetMetadataByName("/app1/ifd/exif/{ushort=40961}"), 1))
                sRgb = true;
            }
            else if (containerFormat == ContainerFormatGuids.Tiff)
            {
              if (Equals(metareader.GetMetadataByName("/ifd/exif/{ushort=40961}"), 1))
                sRgb = true;
            }
            else
            {
              if (Equals(metareader.GetMetadataByName("System.Image.ColorSpace"), 1))
                sRgb = true;
            }

            if (sRgb)
              description.Format = TextureHelper.MakeSRgb(description.Format);
          }
        }
        // ReSharper disable once EmptyGeneralCatchClause
        catch (Exception exception)
        {
          // Some formats just don't support metadata (BMP, ICO, etc.).
        }
      }
#pragma warning restore 168

      return description;
    }
Ejemplo n.º 20
0
        private static Bitmap LoadBitmapFromMemory(RenderTarget device, byte[] bytes)
        {
            if (device == null)
            {
                throw new ArgumentNullException(nameof(device));
            }
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes));
            }
            if (bytes.Length == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(bytes));
            }

            Bitmap            bmp       = null;
            MemoryStream      stream    = null;
            BitmapDecoder     decoder   = null;
            BitmapFrameDecode frame     = null;
            FormatConverter   converter = null;

            try
            {
                stream  = new MemoryStream(bytes);
                decoder = new BitmapDecoder(ImageFactory, stream, DecodeOptions.CacheOnDemand);

                var pixelFormat = ImagePixelFormats.GetBestPixelFormat(decoder.DecoderInfo?.PixelFormats);

                frame = decoder.GetFrame(0);

                converter = new FormatConverter(ImageFactory);

                try
                {
                    converter.Initialize(frame, pixelFormat);
                    bmp = Bitmap.FromWicBitmap(device, converter);
                }
                catch
                {
                    TryCatch(() => converter.Dispose());

                    converter = new FormatConverter(ImageFactory);
                    converter.Initialize(frame, PixelFormat.Format32bppRGB);
                    bmp = Bitmap.FromWicBitmap(device, converter);
                }

                converter.Dispose();
                frame.Dispose();
                decoder.Dispose();
                stream.Dispose();

                return(bmp);
            }
            catch
            {
                if (converter?.IsDisposed == false)
                {
                    converter.Dispose();
                }
                if (frame?.IsDisposed == false)
                {
                    frame.Dispose();
                }
                if (decoder?.IsDisposed == false)
                {
                    decoder.Dispose();
                }
                if (stream != null)
                {
                    TryCatch(() => stream.Dispose());
                }
                if (bmp?.IsDisposed == false)
                {
                    bmp.Dispose();
                }

                throw;
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 從WIC Frame建立貼圖資源(非DDS)
        /// </summary>
        /// <param name="d3dContext">If a Direct3D 11 device context is provided and the current device supports it for the given pixel format, it will auto-generate mipmaps.</param>
        private static Result CreateWICTexture(Device device, DeviceContext d3dContext, BitmapFrameDecode frame, int maxsize, ResourceUsage usage, BindFlags bind, CpuAccessFlags cpuAccess, ResourceOptionFlags option, LoadFlags load, out Resource texture, out ShaderResourceView textureView)
        {
            texture     = null;
            textureView = null;

            if (frame.Size.Width <= 0 || frame.Size.Height <= 0)
            {
                return(Result.InvalidArg);
            }

            if (maxsize == 0)
            {
                switch (device.FeatureLevel)
                {
                case FeatureLevel.Level_9_1:
                case FeatureLevel.Level_9_2:
                    maxsize = 2048 /*D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION*/;
                    break;

                case FeatureLevel.Level_9_3:
                    maxsize = 4096 /*D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION*/;
                    break;

                case FeatureLevel.Level_10_0:
                case FeatureLevel.Level_10_1:
                    maxsize = 8192 /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/;
                    break;

                default:
                    maxsize = Resource.MaximumTexture2DSize;     /*D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION*/
                    break;
                }
            }

            Size2 frameSize = frame.Size;
            Size2 targetSize;

            if (frameSize.Width > maxsize || frameSize.Height > maxsize)
            {
                double ratio = Convert.ToDouble(frameSize.Height) / Convert.ToDouble(frameSize.Width);
                if (frameSize.Width > frameSize.Height)
                {
                    targetSize.Width  = maxsize;
                    targetSize.Height = Math.Max(1, Convert.ToInt32(maxsize * ratio));
                }
                else
                {
                    targetSize.Height = maxsize;
                    targetSize.Width  = Math.Max(1, Convert.ToInt32(maxsize / ratio));
                }
            }
            else
            {
                targetSize = frameSize;
            }

            #region Determine format
            Guid        sourceFormat = frame.PixelFormat;
            Guid        targetFormat = sourceFormat;
            DXGI.Format format       = sourceFormat.ConvertWICToDXGIFormat();
            int         bpp          = 0;

            if (format == DXGI.Format.Unknown)
            {
                if (sourceFormat == PixelFormat.Format96bppRGBFixedPoint)
                {
                    if (WIC2)
                    {
                        targetFormat = PixelFormat.Format96bppRGBFloat;
                        format       = DXGI.Format.R32G32B32_Float;
                        bpp          = 96;
                    }
                    else
                    {
                        targetFormat = PixelFormat.Format128bppRGBAFloat;
                        format       = DXGI.Format.R32G32B32A32_Float;
                        bpp          = 128;
                    }
                }
                else
                {
                    targetFormat = sourceFormat.ConvertToNearest();
                    format       = targetFormat.ConvertWICToDXGIFormat();
                    bpp          = PixelFormat.GetBitsPerPixel(targetFormat);
                }
                if (format == DXGI.Format.Unknown)
                {
                    return(Result.GetResultFromWin32Error(unchecked ((int)0x80070032)));
                }
            }
            else
            {
                bpp = PixelFormat.GetBitsPerPixel(sourceFormat);
            }

            if (format == DXGI.Format.R32G32B32_Float && d3dContext != null)
            {
                // Special case test for optional device support for autogen mipchains for R32G32B32_FLOAT
                var formatSupport = device.CheckFormatSupport(format);
                if (!formatSupport.HasFlag(FormatSupport.MipAutogen))
                {
                    targetFormat = PixelFormat.Format128bppRGBAFloat;
                    format       = DXGI.Format.R32G32B32A32_Float;
                    bpp          = 128;
                }
            }
            if (bpp == 0)
            {
                return(Result.Fail);
            }

            if (load.HasFlag(LoadFlags.ForceSrgb))
            {
                format = format.MakeSRgb();
            }
            else if (!load.HasFlag(LoadFlags.ignoreSrgb))
            {
                bool sRGB = false;
                try {
                    var metareader      = frame.MetadataQueryReader;
                    var containerFormat = metareader.ContainerFormat;

                    if (containerFormat == ContainerFormatGuids.Png)
                    {
                        // Check for sRGB chunk
                        if (metareader.TryGetMetadataByName("/sRGB/RenderingIntent", out var value) == Result.Ok)
                        {
                            sRGB = true;
                        }
                    }
                    else if (metareader.TryGetMetadataByName("System.Image.ColorSpace", out var value) == Result.Ok)
                    {
                        sRGB = true;
                    }

                    if (sRGB)
                    {
                        format = format.MakeSRgb();
                    }
                } catch (SharpDXException) {
                    // BMP, ICO are not supported.
                }
            }

            // Verify our target format is supported by the current device
            var support = device.CheckFormatSupport(format);
            if (!support.HasFlag(FormatSupport.Texture2D))
            {
                targetFormat = PixelFormat.Format32bppRGBA;
                format       = DXGI.Format.R8G8B8A8_UNorm;
                bpp          = 32;
            }
            #endregion


            int    stride    = (targetSize.Width * bpp + 7) / 8; // round
            int    imageSize = stride * targetSize.Height;
            IntPtr temp      = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(imageSize);

            if (sourceFormat == targetFormat && frameSize == targetSize)   // 不需要格式轉換 且 不需要改變大小
            {
                frame.CopyPixels(stride, new DataPointer(temp, imageSize));
            }
            else if (frameSize == targetSize)     // 需要格式轉換
            {
                using (var factory = new ImagingFactory2())
                    using (var coverter = new FormatConverter(factory)) {
                        if (coverter.CanConvert(sourceFormat, targetFormat))
                        {
                            coverter.Initialize(frame, targetFormat, BitmapDitherType.ErrorDiffusion, null, 0, BitmapPaletteType.MedianCut);
                            coverter.CopyPixels(stride, new DataPointer(temp, imageSize));
                        }
                        else
                        {
                            return(Result.UnexpectedFailure);
                        }
                    }
            }
            else if (sourceFormat == targetFormat)     // 需要改變大小
            {
                using (var factory = new ImagingFactory2())
                    using (var scaler = new BitmapScaler(factory)) {
                        scaler.Initialize(frame, targetSize.Width, targetSize.Height, BitmapInterpolationMode.Fant);
                        var pfScaler = scaler.PixelFormat;
                        if (targetFormat == pfScaler)
                        {
                            scaler.CopyPixels(stride, new DataPointer(temp, imageSize));
                        }
                    }
            }
            else     // 需要格式轉換 且 需要改變大小
            {
                using (var factory = new ImagingFactory2())
                    using (var scaler = new BitmapScaler(factory))
                        using (var coverter = new FormatConverter(factory)) {
                            scaler.Initialize(frame, targetSize.Width, targetSize.Height, BitmapInterpolationMode.Fant);
                            var pfScaler = scaler.PixelFormat;

                            if (coverter.CanConvert(pfScaler, targetFormat))
                            {
                                coverter.Initialize(scaler, targetFormat, BitmapDitherType.ErrorDiffusion, null, 0, BitmapPaletteType.MedianCut);
                                coverter.CopyPixels(stride, new DataPointer(temp, imageSize));
                            }
                            else
                            {
                                return(Result.UnexpectedFailure);
                            }
                        }
            }

            var autogen = false;

            if (d3dContext != null)
            {
                var formatSupport = device.CheckFormatSupport(format);
                if (formatSupport.HasFlag(FormatSupport.MipAutogen))
                {
                    autogen = true;
                }
            }

            var texture2DDescription = new Texture2DDescription()
            {
                Width             = targetSize.Width,
                Height            = targetSize.Height,
                MipLevels         = autogen ? 0 : 1,
                ArraySize         = 1,
                Format            = format,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Usage             = usage,
                CpuAccessFlags    = cpuAccess,
            };

            if (autogen)
            {
                texture2DDescription.BindFlags   = bind | BindFlags.RenderTarget;
                texture2DDescription.OptionFlags = option | ResourceOptionFlags.GenerateMipMaps;
            }
            else
            {
                texture2DDescription.BindFlags   = bind;
                texture2DDescription.OptionFlags = option;
            }

            Result result = Result.Ok;

            // 建立Texture2D !!!
            try {
                if (autogen)
                {
                    texture = new Texture2D(device, texture2DDescription);
                }
                else
                {
                    texture = new Texture2D(device, texture2DDescription, new DataBox[] { new DataBox(temp, stride, imageSize) });
                }
            } catch (SharpDXException e) {
                System.Diagnostics.Debug.WriteLine(e.ToString());
                result = Result.Fail;
            }

            if (result.Success)
            {
                var SRVDesc = new ShaderResourceViewDescription()
                {
                    Format    = format,
                    Dimension = ShaderResourceViewDimension.Texture2D,
                    Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                    {
                        MipLevels = autogen ? -1 : 1
                    },
                };

                try {
                    textureView = new ShaderResourceView(device, texture, SRVDesc);
                    if (autogen)
                    {
                        DataBox data = new DataBox(temp, stride, imageSize);
                        d3dContext.UpdateSubresource(data, texture);
                        d3dContext.GenerateMips(textureView);
                    }
                } catch (Exception e) {
                    System.Diagnostics.Debug.WriteLine(e.ToString());
                    Utilities.Dispose(ref texture);
                    result = Result.Fail;
                }
            }

            // 釋放 Unmanaged 資源
            System.Runtime.InteropServices.Marshal.FreeCoTaskMem(temp);

            return(result);
        }
Ejemplo n.º 22
0
        public static BitmapBrush makeBitmapBrush(RenderTarget renderTarget, string imgName, bool blankImage = false)
        {
            string imageSrc = Program.spriteFileDir + imgName;

            if (blankImage)
            {
                var pf = new SharpDX.Direct2D1.PixelFormat()
                {
                    AlphaMode = SharpDX.Direct2D1.AlphaMode.Premultiplied,
                    Format    = Format.B8G8R8A8_UNorm
                };

                BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, pf);
                return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
            if (File.Exists(imageSrc))
            {
                ImagingFactory   imagingFactory = new ImagingFactory();
                NativeFileStream fileStream     = new NativeFileStream(imageSrc,
                                                                       NativeFileMode.Open, NativeFileAccess.Read);
                BitmapDecoder bitmapDecoder = new BitmapDecoder(imagingFactory, fileStream, DecodeOptions.CacheOnDemand);

                BitmapFrameDecode frame = bitmapDecoder.GetFrame(0);

                FormatConverter converter = new FormatConverter(imagingFactory);
                converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA);

                Bitmap bitmap = Bitmap.FromWicBitmap(renderTarget, converter);

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

                return(new BitmapBrush(renderTarget, bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
            else
            {
                Console.WriteLine("{0} missing", imageSrc);

                var pf = new SharpDX.Direct2D1.PixelFormat()
                {
                    AlphaMode = SharpDX.Direct2D1.AlphaMode.Premultiplied,
                    Format    = Format.B8G8R8A8_UNorm
                };
                BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, new Size2F(30f, 30f), new Size2(1, 1), pf);

                pallete.BeginDraw();
                pallete.Clear(Color.Purple);
                pallete.EndDraw();

                return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Function to read the data from a frame.
        /// </summary>
        /// <param name="wic">WIC interface.</param>
        /// <param name="data">Image data to populate.</param>
        /// <param name="srcFormat">Source image format.</param>
        /// <param name="convertFormat">Conversion format.</param>
        /// <param name="frame">Frame containing the image data.</param>
        private void ReadFrame(GorgonWICImage wic, GorgonImageData data, Guid srcFormat, Guid convertFormat, BitmapFrameDecode frame)
        {
            var buffer = data.Buffers[0];

            // We don't need to convert, so just leave.
            if ((convertFormat == Guid.Empty) || (srcFormat == convertFormat))
            {
                frame.CopyPixels(buffer.PitchInformation.RowPitch, buffer.Data.BasePointer, buffer.PitchInformation.SlicePitch);
                return;
            }

            // Perform conversion.
            using (var converter = new FormatConverter(wic.Factory))
            {
                bool isIndexed = ((frame.PixelFormat == PixelFormat.Format8bppIndexed) ||
                                  (frame.PixelFormat == PixelFormat.Format4bppIndexed) ||
                                  (frame.PixelFormat == PixelFormat.Format2bppIndexed) ||
                                  (frame.PixelFormat == PixelFormat.Format1bppIndexed));
                Tuple <Palette, double, BitmapPaletteType> paletteInfo = null;

                try
                {
                    // If the pixel format is indexed, then retrieve a palette.
                    if (isIndexed)
                    {
                        paletteInfo = GetPaletteInfo(wic, null);
                    }

                    // If we've defined a palette for an indexed image, then copy it to a bitmap and set its palette.
                    if ((paletteInfo != null) && (paletteInfo.Item1 != null))
                    {
                        using (var tempBitmap = new Bitmap(wic.Factory, frame, BitmapCreateCacheOption.CacheOnDemand))
                        {
                            tempBitmap.Palette = paletteInfo.Item1;
                            converter.Initialize(tempBitmap, convertFormat, (BitmapDitherType)Dithering, paletteInfo.Item1, paletteInfo.Item2, paletteInfo.Item3);
                            converter.CopyPixels(buffer.PitchInformation.RowPitch, buffer.Data.BasePointer, buffer.PitchInformation.SlicePitch);
                        }

                        return;
                    }

                    // Only apply palettes to indexed image data.
                    converter.Initialize(frame, convertFormat, (BitmapDitherType)Dithering, null, 0.0, BitmapPaletteType.Custom);
                    converter.CopyPixels(buffer.PitchInformation.RowPitch, buffer.Data.BasePointer, buffer.PitchInformation.SlicePitch);
                }
                finally
                {
                    if ((paletteInfo != null) && (paletteInfo.Item1 != null))
                    {
                        paletteInfo.Item1.Dispose();
                    }
                }
            }
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Function to retrieve meta data from the image.
 /// </summary>
 /// <param name="wic">WIC interface.</param>
 /// <param name="decoder">Decoder for the image.</param>
 /// <param name="frame">Frame in the image to decode.</param>
 /// <param name="bestFormatMatch">The best match for the pixel format.</param>
 /// <returns>Settings for the new image.</returns>
 internal IImageSettings ReadMetaData(GorgonWICImage wic, BitmapDecoder decoder, BitmapFrameDecode frame, out Guid bestFormatMatch)
 {
     return(new GorgonTexture2DSettings
     {
         Width = frame.Size.Width,
         Height = frame.Size.Height,
         MipCount = 1,
         ArrayCount = (CodecUseAllFrames && SupportsMultipleFrames) ? decoder.FrameCount : 1,
         Format = wic.FindBestFormat(frame.PixelFormat, DecodeFlags, out bestFormatMatch)
     });
 }
Ejemplo n.º 25
0
    private static Texture DecodeSingleframe(ImagingFactory imagingFactory, WicFlags flags, TextureDescription description, Guid convertGuid, BitmapFrameDecode frame)
    {
      var texture = new Texture(description);
      var image = texture.Images[0];

      if (convertGuid == Guid.Empty)
      {
        frame.CopyPixels(image.Data, image.RowPitch);
      }
      else
      {
        using (var converter = new FormatConverter(imagingFactory))
        {
          converter.Initialize(frame, convertGuid, GetWicDither(flags), null, 0, BitmapPaletteType.Custom);
          converter.CopyPixels(image.Data, image.RowPitch);
        }
      }

      return texture;
    }
Ejemplo n.º 26
0
        //-------------------------------------------------------------------------------------
        // Decodes a single frame
        //-------------------------------------------------------------------------------------
        private static Image DecodeSingleFrame(WICFlags flags, ImageDescription metadata, Guid convertGUID, BitmapFrameDecode frame)
        {
            var image = Image.New(metadata);

            var pixelBuffer = image.PixelBuffer[0];

            if (convertGUID == Guid.Empty)
            {
                frame.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride);
            }
            else
            {
                using (var converter = new FormatConverter(Factory))
                {
                    converter.Initialize(frame, convertGUID, GetWICDither(flags), null, 0, BitmapPaletteType.Custom);
                    converter.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride);
                }
            }

            return(image);
        }
Ejemplo n.º 27
0
        private unsafe BitmapSource GetBitmapFromImage()
        {
            var captureData = k4a_image_get_buffer(this.image.Handle);
            var captureSize = (int)this.image.Size;

            switch (image.Format)
            {
            case ImageFormat.ColorMJPG:
            {
                this.bitmapDecoder = new BitmapDecoder(this.imagingFactory, ContainerFormatGuids.Jpeg);
                this.stream        = new WICStream(this.imagingFactory, new DataPointer(captureData, captureSize));
                this.bitmapDecoder.Initialize(this.stream, DecodeOptions.CacheOnLoad);

                this.frame           = this.bitmapDecoder.GetFrame(0);
                this.formatConverter = new FormatConverter(this.imagingFactory);
                formatConverter.Initialize(frame, PixelFormat.Format32bppPBGRA, BitmapDitherType.None, null, 0.0, BitmapPaletteType.Custom);
                return(formatConverter);
            }

            case ImageFormat.ColorBGRA32:
                return(new Bitmap(this.imagingFactory,
                                  image.WidthPixels,
                                  image.HeightPixels,
                                  PixelFormat.Format32bppPBGRA,
                                  new DataRectangle(captureData, image.StrideBytes),
                                  captureSize));

            case ImageFormat.IR16:
            case ImageFormat.Depth16:
                return(new Bitmap(this.imagingFactory,
                                  image.WidthPixels,
                                  image.HeightPixels,
                                  PixelFormat.Format16bppGrayFixedPoint,
                                  new DataRectangle(captureData, image.StrideBytes),
                                  captureSize));

            case ImageFormat.ColorNV12:
            {
                int textureWidth  = this.image.WidthPixels;
                int textureHeight = this.image.HeightPixels;
                var imagePixels   = textureWidth * textureHeight;
                var nv12Span      = new Span <byte>(captureData.ToPointer(), captureSize);
                var nv12ySpan     = nv12Span.Slice(0, imagePixels);
                var nv12uvSpan    = nv12Span.Slice(nv12ySpan.Length, (int)(imagePixels * 0.5));

                var bitmap = new Bitmap(this.imagingFactory,
                                        image.WidthPixels,
                                        image.HeightPixels,
                                        PixelFormat.Format32bppPBGRA,
                                        BitmapCreateCacheOption.CacheOnLoad);
                using (var bitmapLock = bitmap.Lock(BitmapLockFlags.Write))
                {
                    var ptr = (byte *)bitmapLock.Data.DataPointer.ToPointer();
                    fixed(byte *yptr = nv12ySpan)
                    fixed(byte *uvptr = nv12uvSpan)
                    {
                        _ = LibYuv.NV12ToARGB(yptr, textureWidth, uvptr, textureWidth, ptr, textureWidth * 4, textureWidth, textureHeight);
                    }
                }

                return(bitmap);
            }

            case ImageFormat.ColorYUY2:
            {
                int textureWidth  = this.image.WidthPixels;
                int textureHeight = this.image.HeightPixels;
                var imagePixels   = textureWidth * textureHeight;
                var yuv2Span      = new Span <byte>(captureData.ToPointer(), captureSize);

                var bitmap = new Bitmap(this.imagingFactory,
                                        image.WidthPixels,
                                        image.HeightPixels,
                                        PixelFormat.Format32bppPBGRA,
                                        BitmapCreateCacheOption.CacheOnLoad);
                using (var bitmapLock = bitmap.Lock(BitmapLockFlags.Write))
                {
                    var ptr = (byte *)bitmapLock.Data.DataPointer.ToPointer();
                    fixed(byte *yuv2ptr = yuv2Span)
                    {
                        _ = LibYuv.YUY2ToARGB(yuv2ptr, textureWidth * 2, ptr, textureWidth * 4, textureWidth, textureHeight);
                    }
                }

                return(bitmap);
            }

            case ImageFormat.Custom8:
            case ImageFormat.Custom16:
            case ImageFormat.Custom:
            default:
                throw new NotImplementedException($"Format not implemented: {image.Format}.");
            }
        }
        private Texture LoadTextureFromFile(string fileName, bool generateMips, int mipLevels = -1)
        {
            BitmapDecoder decoder = new BitmapDecoder(_imagingFactory,
                                                      fileName, DecodeOptions.CacheOnDemand);
            BitmapFrameDecode bitmapFirstFrame = decoder.GetFrame(0);

            Utilities.Dispose(ref decoder);

            FormatConverter formatConverter = new FormatConverter(_imagingFactory);

            formatConverter.Initialize(bitmapFirstFrame, PixelFormat.Format32bppRGBA,
                                       BitmapDitherType.None, null, 0.0f, BitmapPaletteType.Custom);

            int        stride = formatConverter.Size.Width * 4;
            DataStream buffer = new DataStream(
                formatConverter.Size.Height * stride, true, true);

            formatConverter.CopyPixels(stride, buffer);

            int width  = formatConverter.Size.Width;
            int height = formatConverter.Size.Height;
            Texture2DDescription texture2DDescription = new Texture2DDescription()
            {
                Width             = width,
                Height            = height,
                MipLevels         = (generateMips ? 0 : 1),
                ArraySize         = 1,
                Format            = Format.R8G8B8A8_UNorm,
                SampleDescription = _sampleDescription,
                Usage             = ResourceUsage.Default,
                BindFlags         = (
                    generateMips ?
                    BindFlags.ShaderResource | BindFlags.RenderTarget : BindFlags.ShaderResource
                    ),
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = (
                    generateMips ?
                    ResourceOptionFlags.GenerateMipMaps :
                    ResourceOptionFlags.None
                    )
            };

            Texture2D textureObject;

            if (generateMips)
            {
                textureObject = new Texture2D(_directX3DGraphics.Device, texture2DDescription);
            }
            else
            {
                DataRectangle dataRectangle = new DataRectangle(buffer.DataPointer, stride);
                textureObject = new Texture2D(_directX3DGraphics.Device, texture2DDescription, dataRectangle);
            }

            ShaderResourceViewDescription shaderResourceViewDescription =
                new ShaderResourceViewDescription()
            {
                Dimension = ShaderResourceViewDimension.Texture2D,
                Format    = Format.R8G8B8A8_UNorm,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource
                {
                    MostDetailedMip = 0,
                    MipLevels       = (generateMips ? mipLevels : 1)
                }
            };
            ShaderResourceView shaderResourceView =
                new ShaderResourceView(_directX3DGraphics.Device, textureObject, shaderResourceViewDescription);

            if (generateMips)
            {
                DataBox dataBox = new DataBox(buffer.DataPointer, stride, 1);
                _directX3DGraphics.DeviceContext.UpdateSubresource(dataBox, textureObject, 0);
                _directX3DGraphics.DeviceContext.GenerateMips(shaderResourceView);
            }

            Utilities.Dispose(ref formatConverter);

            return(new Texture(textureObject, shaderResourceView, width, height, samplerState));
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Function to retrieve the offset for the frame being decoded.
 /// </summary>
 /// <param name="frame">Frame to decode.</param>
 /// <returns>The position of the offset.</returns>
 internal virtual Point GetFrameOffset(BitmapFrameDecode frame)
 {
     return(Point.Empty);
 }