// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.IO; using Perspex.Platform; using SharpDX.WIC; namespace Perspex.Direct2D1.Media { /// /// A Direct2D implementation of a . /// public class BitmapImpl : IBitmapImpl { private readonly ImagingFactory _factory; private SharpDX.Direct2D1.Bitmap _direct2D; /// /// Initializes a new instance of the class. /// /// The WIC imaging factory to use. /// The filename of the bitmap to load. public BitmapImpl(ImagingFactory factory, string fileName) { _factory = factory; using (BitmapDecoder decoder = new BitmapDecoder(factory, fileName, DecodeOptions.CacheOnDemand)) { WicImpl = new Bitmap(factory, decoder.GetFrame(0), BitmapCreateCacheOption.CacheOnDemand); } } /// /// Initializes a new instance of the class. /// /// The WIC imaging factory to use. /// The stream to read the bitmap from. public BitmapImpl(ImagingFactory factory, Stream stream) { _factory = factory; using (BitmapDecoder decoder = new BitmapDecoder(factory, stream, DecodeOptions.CacheOnLoad)) { WicImpl = new Bitmap(factory, decoder.GetFrame(0), BitmapCreateCacheOption.CacheOnLoad); } } /// /// Initializes a new instance of the class. /// /// The WIC imaging factory to use. /// The width of the bitmap. /// The height of the bitmap. public BitmapImpl(ImagingFactory factory, int width, int height) { _factory = factory; WicImpl = new Bitmap( factory, width, height, PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnLoad); } /// /// Gets the width of the bitmap, in pixels. /// public int PixelWidth => WicImpl.Size.Width; /// /// Gets the height of the bitmap, in pixels. /// public int PixelHeight => WicImpl.Size.Height; public virtual void Dispose() { WicImpl.Dispose(); } /// /// Gets the WIC implementation of the bitmap. /// public Bitmap WicImpl { get; } /// /// Gets a Direct2D bitmap to use on the specified render target. /// /// The render target. /// The Direct2D bitmap. public SharpDX.Direct2D1.Bitmap GetDirect2DBitmap(SharpDX.Direct2D1.RenderTarget renderTarget) { if (_direct2D == null) { FormatConverter converter = new FormatConverter(_factory); converter.Initialize(WicImpl, PixelFormat.Format32bppPBGRA); _direct2D = SharpDX.Direct2D1.Bitmap.FromWicBitmap(renderTarget, converter); } return _direct2D; } /// /// Saves the bitmap to a file. /// /// The filename. public void Save(string fileName) { if (Path.GetExtension(fileName) != ".png") { // Yeah, we need to support other formats. throw new NotSupportedException("Use PNG, stoopid."); } using (FileStream s = new FileStream(fileName, FileMode.Create)) { PngBitmapEncoder encoder = new PngBitmapEncoder(_factory); encoder.Initialize(s); BitmapFrameEncode frame = new BitmapFrameEncode(encoder); frame.Initialize(); frame.WriteSource(WicImpl); frame.Commit(); encoder.Commit(); } } } }