public unsafe SharpDX.WIC.Bitmap CreateWICBitmapFromGDI(System.Drawing.Bitmap gdiBitmap) { var wicFactory = new ImagingFactory(); var wicBitmap = new SharpDX.WIC.Bitmap(wicFactory, gdiBitmap.Width, gdiBitmap.Height, PixelFormat.Format32bppBGRA, BitmapCreateCacheOption.CacheOnLoad); System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, gdiBitmap.Width, gdiBitmap.Height); var btmpData = gdiBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); byte *pGDIData = (byte *)btmpData.Scan0; using (BitmapLock bl = wicBitmap.Lock(BitmapLockFlags.Write)) { byte *pWICData = (byte *)bl.Data.DataPointer; for (int y = 0; y < gdiBitmap.Height; y++) { int offsetWIC = y * bl.Stride; int offsetGDI = y * btmpData.Stride; for (int x = 0; x < gdiBitmap.Width; x++) { pWICData[offsetWIC + 0] = pGDIData[offsetGDI + 0]; pWICData[offsetWIC + 1] = pGDIData[offsetGDI + 1]; pWICData[offsetWIC + 2] = pGDIData[offsetGDI + 2]; pWICData[offsetWIC + 3] = pGDIData[offsetGDI + 3]; offsetWIC += 4; offsetGDI += 4; } } } gdiBitmap.UnlockBits(btmpData); return(wicBitmap); }
private static Direct2D.Bitmap LoadFromFile(string filename, Direct2D.RenderTarget Direct2DTarget) { var factory = new WIC.ImagingFactory(); // Decode image var decoder = new WIC.BitmapDecoder(factory, filename, WIC.DecodeOptions.CacheOnLoad); var frameDecode = decoder.GetFrame(0); var source = new WIC.BitmapSource(frameDecode.NativePointer); var fc = new WIC.FormatConverter(factory); fc.Initialize( source, SharpDX.WIC.PixelFormat.Format32bppPBGRA, SharpDX.WIC.BitmapDitherType.None, null, 0.0f, SharpDX.WIC.BitmapPaletteType.Custom ); double dpX = 96.0f; double dpY = 96.0f; fc.GetResolution(out dpX, out dpY); Direct2D.BitmapProperties props = new Direct2D.BitmapProperties( new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied)); WIC.Bitmap bmp = new WIC.Bitmap(factory, fc, WIC.BitmapCreateCacheOption.CacheOnLoad); // Формируем изображения var Direct2DBitmap = SharpDX.Direct2D1.Bitmap.FromWicBitmap(Direct2DTarget, fc, props); // Cleanup factory.Dispose(); decoder.Dispose(); source.Dispose(); fc.Dispose(); return(Direct2DBitmap); }
static GamingTheatre() { if (Directory.Exists("Temp")) { Directory.Delete("Temp", true); } VideoStreamDecoder vsd = new VideoStreamDecoder(@"assets.shine:movie/LOGO_32.mov"); while (true) { var res = vsd.TryDecodeNextFrame(out IntPtr dataPoint, out int pitch); if (!res) { break; } var ImGc = new ImagingFactory(); var WICBIT = new WICBitmap(ImGc, vsd.FrameSize.Width, vsd.FrameSize.Height, SharpDX.WIC.PixelFormat.Format32bppPBGRA, new DataRectangle(dataPoint, pitch)); // var mp = new System.Drawing.Bitmap(vsd.FrameSize.Width, vsd.FrameSize.Height, pitch, System.Drawing.Imaging.PixelFormat.Format32bppPArgb, dataPoint); // mp.Save("test/" + logo_frames.Count + ".png"); // mp.Dispose(); ImGc.Dispose(); logo_frames.Add(WICBIT); } vsd.Dispose(); }
protected RenderableImage(DeviceContext dc, WICBitmap im) { this._Pelete = D2DBitmap.FromWicBitmap(dc, im); pel_origin = _Pelete; this.rDc = dc; this._Size = new Size2(this._Pelete.PixelSize.Width, this._Pelete.PixelSize.Height); }
private static void DrawSmallRaw(Person person, WIC.ImagingFactory wic, D2D.Factory d2dFactory, WIC.FormatConverter converter) { var whRate = 1.0f * converter.Size.Width / converter.Size.Height; var smallRawSize = new Vector2(whRate * ImageDefines.SmallRawY, ImageDefines.SmallRawY); var scale = ImageDefines.SmallRawY / converter.Size.Height; using (var wicBitmap = new WIC.Bitmap(wic, (int)smallRawSize.X, (int)smallRawSize.Y, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand)) using (var target = new D2D.WicRenderTarget(d2dFactory, wicBitmap, new D2D.RenderTargetProperties())) using (var bmp = D2D.Bitmap.FromWicBitmap(target, converter)) using (var bmpBrush = new D2D.BitmapBrush(target, bmp)) { target.BeginDraw(); target.Transform = Matrix3x2.Scaling(scale, scale); target.DrawBitmap(bmp, 1.0f, D2D.BitmapInterpolationMode.Linear); target.EndDraw(); using (var file = File.Create(person.SmallRawImage)) { WicTools.SaveD2DBitmap(wic, wicBitmap, file); } } }
public void Save(Stream systemStream, Direct2DImageFormat format, string text, string faceName, float fontSize, out int width, out int height) { #if BENCHMARK using (var handler = Benchmark.Instance.Start("DirectWrite", "Save")) #endif using (var layout = new TextLayout(factoryManager.DwFactory, text, new TextFormat(factoryManager.DwFactory, faceName, fontSize * 1.3f), 4000, 4000)) { width = (int)Math.Ceiling(layout.Metrics.WidthIncludingTrailingWhitespace); height = (int)Math.Ceiling(layout.Metrics.Height); using (var wicBitmap = new SharpDX.WIC.Bitmap(factoryManager.WicFactory, width, height, SharpDX.WIC.PixelFormat.Format32bppPRGBA, BitmapCreateCacheOption.CacheOnLoad)) { var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Unknown), imageDpi, imageDpi, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); using (var renderTarget = new WicRenderTarget(factoryManager.D2DFactory, wicBitmap, renderTargetProperties)) using (var brush = new SolidColorBrush(renderTarget, SharpDX.Color.White)) using (var encoder = new BitmapEncoder(factoryManager.WicFactory, Direct2DConverter.ConvertImageFormat(format))) { renderTarget.BeginDraw(); renderTarget.Clear(new Color4(1, 1, 1, 0)); renderTarget.DrawTextLayout(Vector2.Zero, layout, brush); renderTarget.EndDraw(); var stream = new WICStream(factoryManager.WicFactory, systemStream); encoder.Initialize(stream); using (var bitmapFrameEncode = new BitmapFrameEncode(encoder)) { bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(width, height); bitmapFrameEncode.WriteSource(wicBitmap); bitmapFrameEncode.Commit(); } encoder.Commit(); } } } }
// 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(); } }
private RendererDirect2D Create(PxSize size, out WIC.Bitmap wicBitmap) { _bitmap = wicBitmap = new WIC.Bitmap( WicFactory, (int)(size.Width * 1.0f), (int)(size.Height * 1.0f), WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnLoad ); wicBitmap.SetResolution(200, 200); var renderProps = new D2D1.RenderTargetProperties( D2D1.RenderTargetType.Default, new D2D1.PixelFormat( DXGI.Format.B8G8R8A8_UNorm, D2D1.AlphaMode.Premultiplied ), 96, 96, D2D1.RenderTargetUsage.None, //GdiCompatible| D2D1.RenderTargetUsage.ForceBitmapRemoting, D2D1.FeatureLevel.Level_DEFAULT ); var wicRenderTarget = new D2D1.WicRenderTarget( D2DFactory, wicBitmap, renderProps ); // {DotsPerInch = new Size2F(600, 600)}; return(new RendererDirect2D(this, wicRenderTarget)); }
private Bitmap CreateOutputImage(Action <WicRenderTarget> action) { try { var bitmap = new Bitmap(deviceRes2D.WICImgFactory, OutputWidth, OutputHeight, global::SharpDX.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnDemand); using (var target = new WicRenderTarget(deviceRes2D.Factory2D, bitmap, new RenderTargetProperties() { DpiX = 96, DpiY = 96, MinLevel = FeatureLevel.Level_DEFAULT, PixelFormat = new global::SharpDX.Direct2D1.PixelFormat(global::SharpDX.DXGI.Format.Unknown, AlphaMode.Unknown) })) { target.Transform = Matrix3x2.Identity; target.BeginDraw(); action(target); target.EndDraw(); } return(bitmap); } catch { return(null); } }
public static void WatermarkText(Stream imageStream, Stream outputStream, string watermark, string font = "Times New Roman", float fontSize = 30.0f, int colorARGB = TransparentWhite) { using (var wic = new WIC.ImagingFactory2()) using (var d2d = new D2D.Factory()) using (var image = CreateWicImage(wic, imageStream)) using (var wicBitmap = new WIC.Bitmap(wic, image.Size.Width, image.Size.Height, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand)) using (var target = new D2D.WicRenderTarget(d2d, wicBitmap, new D2D.RenderTargetProperties())) using (var bmpPicture = D2D.Bitmap.FromWicBitmap(target, image)) using (var dwriteFactory = new DWrite.Factory()) using (var brush = new D2D.SolidColorBrush(target, new Color(colorARGB))) { target.BeginDraw(); { target.DrawBitmap(bmpPicture, new RectangleF(0, 0, target.Size.Width, target.Size.Height), 1.0f, D2D.BitmapInterpolationMode.Linear); target.DrawRectangle(new RectangleF(0, 0, target.Size.Width, target.Size.Height), brush); var textFormat = new DWrite.TextFormat(dwriteFactory, font, DWrite.FontWeight.Bold, DWrite.FontStyle.Normal, fontSize) { ParagraphAlignment = DWrite.ParagraphAlignment.Far, TextAlignment = DWrite.TextAlignment.Trailing, }; target.DrawText(watermark, textFormat, new RectangleF(0, 0, target.Size.Width, target.Size.Height), brush); } target.EndDraw(); SaveD2DBitmap(wic, wicBitmap, outputStream); } }
private void CreateBitmap(int width, int height) { if (_bitmap == null || (_bitmap.Size.Width < width || _bitmap.Size.Height < height)) { //RenderTargetProperties rtp = new RenderTargetProperties(RenderTargetType.Default, // new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied), // Factory2D.DesktopDpi.Width, // Factory2D.DesktopDpi.Height, // RenderTargetUsage.None, // FeatureLevel.Level_DEFAULT); try { var pixelFormat = SharpDX.WIC.PixelFormat.Format32bppPRGBA; _bitmap = new SharpDX.WIC.Bitmap(FactoryImaging, width, height, pixelFormat, BitmapCreateCacheOption.CacheOnLoad); _renderTarget = new WicRenderTarget(Factory2D, _bitmap, new RenderTargetProperties()); //_renderTarget = new WicRenderTarget(Factory2D, _bitmap, rtpGDI); if (_brush == null) { _brush = new SolidColorBrush(_renderTarget, new Color4(new Color3(1, 1, 1), 1.0f)); } } catch (Exception exc) { var ss = exc.Message; } } }
/// <summary> /// /// </summary> /// <param name="factory"></param> /// <param name="filename"></param> /// <param name="resource">null の場合、ファイル読み込み、nullでない場合リソース読み込み。リソースの場合、呼び出し後解放されます</param> /// <returns></returns> protected static unsafe BitmapSource LoadDDS(ImagingFactory2 factory, string filename, Stream resource = null) { IScratchImage si; if (resource == null) { si = DirectXTexNet.DirectXTex.LoadFromDDSFile(filename, DDSFlags.FORCE_RGB); } else { si = DirectXTexNet.DirectXTex.LoadFromDDSResource(filename, DDSFlags.FORCE_RGB); } var bff = si.GetRawBytes(0, 0); SharpDX.WIC.Bitmap descBmp = null; fixed(byte *pBff = bff) { descBmp = new SharpDX.WIC.Bitmap( factory, (int)si.MetaData.width, (int)si.MetaData.height, SharpDX.WIC.PixelFormat.Format32bppPRGBA, new DataRectangle((IntPtr)pBff, (int)si.MetaData.width * 4)); } return(descBmp); }
private MemoryStream GetBitmapAsStream(WIC.Bitmap wicBitmap) { int width = wicBitmap.Size.Width; int height = wicBitmap.Size.Height; var ms = new MemoryStream(); using (var stream = new WIC.WICStream( this.WicFactory, ms)) { using (var encoder = new WIC.PngBitmapEncoder(WicFactory)) { encoder.Initialize(stream); using (var frameEncoder = new WIC.BitmapFrameEncode(encoder)) { frameEncoder.Initialize(); frameEncoder.SetSize(width, height); var format = WIC.PixelFormat.Format32bppBGRA; frameEncoder.SetPixelFormat(ref format); frameEncoder.WriteSource(wicBitmap); frameEncoder.Commit(); } encoder.Commit(); } } ms.Position = 0; return(ms); }
//------------------------------------------------------------------------------------- // Encodes a single frame //------------------------------------------------------------------------------------- private static void EncodeImage(PixelBuffer image, WICFlags flags, WIC.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 WIC.Bitmap(Factory, image.Width, image.Height, pfGuid, new SDX.DataRectangle(image.DataPointer, image.RowStride), image.BufferStride)) { using (var converter = new WIC.FormatConverter(Factory)) { using (var palette = new WIC.Palette(Factory)) { palette.Initialize(source, 256, true); converter.Initialize(source, targetGuid, GetWICDither(flags), palette, 0, WIC.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 = SDX.Utilities.AllocateMemory(slicePitch); try { converter.CopyPixels(rowPitch, temp, slicePitch); frame.Palette = palette; frame.WritePixels(image.Height, temp, rowPitch, slicePitch); } finally { SDX.Utilities.FreeMemory(temp); } } } } } else { // No conversion required frame.WritePixels(image.Height, image.DataPointer, image.RowStride, image.BufferStride); } frame.Commit(); }
protected void ReleaseResources() { _bitmap.Dispose(); _bitmap = null; _renderTarget.Dispose(); _renderTarget = null; }
public RenderableImage(ImageSource im, DeviceContext DC) : base(DC) { Source = im; _Pelete = Source.Output; this._Size = new Size2(this._Pelete.Size.Width, this._Pelete.Size.Height); RotationPoint = new Point(this._Pelete.Size.Width / 2, this._Pelete.Size.Height / 2); }
static public RenderableImage CreateFromWIC(DeviceContext dc, WICBitmap im) { RenderableImage rt = new RenderableImage(dc, im); return(rt); }
public WICBitmapCanvas (WIC.Bitmap bmp, D2D1.RenderTargetProperties properties, Direct2DFactories factories = null) : base (new D2D1.WicRenderTarget ((factories ?? Direct2DFactories.Shared).D2DFactory, bmp, properties), factories) { this.Bmp = bmp; this.scale = properties.DpiX / 96.0; var bmpSize = bmp.Size; this.size = new Size (bmpSize.Width / scale, bmpSize.Height / scale); }
protected override sd.Bitmap CreateDrawableBitmap(sd.RenderTarget target) { using (var converter = new sw.FormatConverter(SDFactory.WicImagingFactory)) { converter.Initialize(Control, sw.PixelFormat.Format32bppPBGRA); var bmp = new sw.Bitmap(SDFactory.WicImagingFactory, converter, sw.BitmapCreateCacheOption.CacheOnLoad); return(sd.Bitmap.FromWicBitmap(target, bmp)); } }
public void ReLoad(string path) { var old = buffer; buffer = Direct2DHelper.LoadBitmap(path); PixelSize = new Size(buffer.Size.Width, buffer.Size.Height); old.Dispose(); Updated = true; }
public ProcessBar(DeviceContext DC) : base(DC) { using (WICBitmap sc = Direct2DHelper.LoadBitmap("assets\\process.bmp")) using (D2DBitmap sc_cv = D2DBitmap.FromWicBitmap(HostDC, sc)) { br = new BitmapBrush(HostDC, sc_cv); } br.ExtendModeX = ExtendMode.Mirror; }
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))); }
public WICBitmapCanvas(WIC.Bitmap bmp, D2D1.RenderTargetProperties properties, Direct2DFactories factories = null) : base(new D2D1.WicRenderTarget((factories ?? Direct2DFactories.Shared).D2DFactory, bmp, properties), factories) { this.Bmp = bmp; this.scale = properties.DpiX / 96.0; var bmpSize = bmp.Size; this.size = new Size(bmpSize.Width / scale, bmpSize.Height / scale); }
public override void Render() { if (Source.Updated) { _Pelete?.Dispose(); _Pelete = Source.Output; } using (Image PrepairedImage = Output(HostDC)) HostDC.DrawImage(PrepairedImage, new RawVector2(_Position.X, _Position.Y), null, SharpDX.Direct2D1.InterpolationMode.Linear, CompositeMode.SourceOver); }
/// <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(); } } } }
/// <summary> /// Creates a WIC bitmap from the given source. /// </summary> /// <param name="resourceLink">The source of the resource.</param> public static async Task <WicBitmap> FromResourceLinkAsync(ResourceLink resourceLink) { WIC.Bitmap wicBitmap = null; using (Stream inStream = await resourceLink.OpenInputStreamAsync()) using (WicBitmapSourceInternal bitmapSourceWrapper = await CommonTools.CallAsync(() => GraphicsHelper.LoadBitmapSource(inStream))) { wicBitmap = new WIC.Bitmap( GraphicsCore.Current.FactoryWIC, bitmapSourceWrapper.Converter, WIC.BitmapCreateCacheOption.CacheOnLoad); } return(new WicBitmap(wicBitmap)); }
public void Update(DrawProc Proc) { pw.WaitOne(); pw.Reset(); Proc?.Invoke(View); var old_proc = load_buffer; load_buffer = new WICBitmap(iFactory, buffer, BitmapCreateCacheOption.CacheOnLoad); old_proc?.Dispose(); Updated = true; pw.Set(); }
public SaveLoad(int _chapter, int frame, WICBitmap last_draw) { InitializeComponent(); this.Forgan.Loaded += (E, V) => { MainWindow.m_window.ResizeMode = ResizeMode.NoResize; }; this.Forgan.Unloaded += (E, V) => { MainWindow.m_window.ResizeMode = ResizeMode.CanResize; }; chapter = _chapter; _last_draw = last_draw; _frame = frame; try { SaveData.SaveInfo imp_save002 = SaveData.Save2; save_2_event.Background = new ImageBrush(BitmapToBitmapSource(imp_save002.imp)); save_2_content.Text = imp_save002.comment; } catch { } try { SaveData.SaveInfo imp_save003 = SaveData.Save3; save_3_event.Background = new ImageBrush(BitmapToBitmapSource(imp_save003.imp)); save_3_content.Text = imp_save003.comment; } catch { } try { SaveData.SaveInfo imp_save001 = SaveData.Save1; save_1_event.Background = new ImageBrush(BitmapToBitmapSource(imp_save001.imp)); save_1_content.Text = imp_save001.comment; } catch { } try { SaveData.SaveInfo imp_save004 = SaveData.Save4; save_4_event.Background = new ImageBrush(BitmapToBitmapSource(imp_save004.imp)); save_4_content.Text = imp_save004.comment; } catch { } }
public static async Task <WicBitmap> FromWicBitmapSourceAsync(WicBitmapSource bitmapSource, int width, int height) { WIC.Bitmap wicBitmap = null; await Task.Factory.StartNew(() => { wicBitmap = new WIC.Bitmap( GraphicsCore.Current.FactoryWIC, bitmapSource.BitmapSource, new SharpDX.Mathematics.Interop.RawBox(0, 0, width, height)); }); return(new WicBitmap(wicBitmap)); }
public void Create(Image image, int width, int height, ImageInterpolation interpolation) { var imageHandler = (ImageHandler <TWidget>)image.Handler; Control = new sw.Bitmap(SDFactory.WicImagingFactory, width, height, imageHandler.Control.PixelFormat, sw.BitmapCreateCacheOption.CacheOnLoad); using (var graphics = new Graphics(Widget as Bitmap)) { graphics.ImageInterpolation = interpolation; var rect = new Rectangle(0, 0, width, height); graphics.FillRectangle(Colors.Transparent, rect); graphics.DrawImage(image, rect); } }
public Direct2DImageEncoder(int imageWidth, int imageHeight, int imageDpi) { this.imageWidth = imageWidth; this.imageHeight = imageHeight; factoryManager = new Direct2DFactoryManager(); wicBitmap = new SharpDX.WIC.Bitmap(factoryManager.WicFactory, imageWidth, imageHeight, SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.Unknown, AlphaMode.Unknown), imageDpi, imageDpi, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); renderTarget = new WicRenderTarget(factoryManager.D2DFactory, wicBitmap, renderTargetProperties); renderTarget.BeginDraw(); renderTarget.Clear(SharpDX.Color.Yellow); }
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 IImage CreateImage(Color[] colors, int width, double scale = 1.0) { var factories = Direct2DFactories.Shared; var pf = WIC.PixelFormat.Format32bppBGRA; unsafe { fixed (Color* p = colors) { var data = new DataRectangle { Pitch = width * 4, DataPointer = (IntPtr)p, }; var bmp = new WIC.Bitmap (factories.WICFactory, width, colors.Length / width, pf, data); return new WICBitmapSourceImage (bmp, factories); } } }
public RenderTarget Create(Factory factory, Graphics g, Map map) { var wicBitmap = new WICBitmap(_wicFactory, map.Size.Width, map.Size.Height, SharpDX.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnDemand); var rtp = new RenderTargetProperties(RenderTargetType.Default, new D2D1PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); var res = new WicRenderTarget(factory, wicBitmap, rtp) {Tag = wicBitmap}; res.BeginDraw(); res.Clear(SharpDX.Color.Transparent); return res; }
private static System.Drawing.Bitmap ConvertToBitmap(WICBitmap wicBitmap) { var width = wicBitmap.Size.Width; var height = wicBitmap.Size.Height; var gdiBitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); var gdiBitmapData = gdiBitmap.LockBits( new System.Drawing.Rectangle(0, 0, gdiBitmap.Width, gdiBitmap.Height), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); var buffer = new int[width * height]; wicBitmap.CopyPixels(buffer); Marshal.Copy(buffer, 0, gdiBitmapData.Scan0, buffer.Length); gdiBitmap.UnlockBits(gdiBitmapData); return gdiBitmap; }
internal D2dWicGraphics(WicRenderTarget renderTarget, SharpDX.WIC.Bitmap wicBitmap) : base(renderTarget) { m_wicBitmap = wicBitmap; }
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 = WIC.PixelFormat.Format32bppPRGBA; // pixel format without transparency, but one that works with Cleartype antialiasing //var pixelFormat = WicPixelFormat.Format32bppBGR; var wicBitmap = new WIC.Bitmap( this.WicFactory, width, height, pixelFormat, WIC.BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new D2D.RenderTargetProperties( D2D.RenderTargetType.Default, new D2D.PixelFormat(Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied), //new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), // use this for non-alpha, cleartype antialiased text 0, 0, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT); var renderTarget = new D2D.WicRenderTarget( this.D2DFactory, wicBitmap, renderTargetProperties) { //TextAntialiasMode = TextAntialiasMode.Cleartype // this only works with the pixel format with no alpha channel TextAntialiasMode = D2D.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 WIC.WICStream( this.WicFactory, ms); var encoder = new WIC.PngBitmapEncoder(WicFactory); encoder.Initialize(stream); var frameEncoder = new WIC.BitmapFrameEncode(encoder); frameEncoder.Initialize(); frameEncoder.SetSize(width, height); var format = WIC.PixelFormat.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; }
public async Task<MemoryStream> RenderToPngStream(FrameworkElement fe) { var width = (int)Math.Ceiling(fe.ActualWidth); var height = (int)Math.Ceiling(fe.ActualHeight); if (width == 0 || height == 0) { throw new InvalidOperationException("Can't render an empty element. ActualWidth or ActualHeight equal 0. Consider awaiting a WaitForNonZeroSizeAsync() call or invoking Measure()/Arrange() before the call to Render()."); } // pixel format with transparency/alpha channel and RGB values premultiplied by alpha var pixelFormat = WIC.PixelFormat.Format32bppPRGBA; using (var wicBitmap = new WIC.Bitmap( this.WicFactory, width, height, pixelFormat, WIC.BitmapCreateCacheOption.CacheOnLoad)) { var renderTargetProperties = new D2D.RenderTargetProperties( D2D.RenderTargetType.Default, new D2D.PixelFormat( Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied), //new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), // use this for non-alpha, cleartype antialiased text 0, 0, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT); using (var renderTarget = new D2D.WicRenderTarget( this.D2DFactory, wicBitmap, renderTargetProperties) { //TextAntialiasMode = TextAntialiasMode.Cleartype // this only works with the pixel format with no alpha channel TextAntialiasMode = D2D.TextAntialiasMode.Grayscale // this is the best we can do for bitmaps with alpha channels }) { await 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. return GetBitmapAsStream(wicBitmap); } }
// // http://stackoverflow.com/questions/9151615/how-does-one-use-a-memory-stream-instead-of-files-when-rendering-direct2d-images // // Identical to above SO question, except that we are rendering to MemoryStream because it was added to the API // private MemoryStream RenderStaticTextToBitmap() { var width = 400; var height = 100; var pixelFormat = WicPixelFormat.Format32bppBGR; var wicFactory = new ImagingFactory(); var dddFactory = new SharpDX.Direct2D1.Factory(); var dwFactory = new SharpDX.DirectWrite.Factory(); var wicBitmap = new Bitmap( wicFactory, width, height, pixelFormat, BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new RenderTargetProperties( RenderTargetType.Default, new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); var renderTarget = new WicRenderTarget( dddFactory, wicBitmap, renderTargetProperties) { TextAntialiasMode = TextAntialiasMode.Cleartype }; renderTarget.BeginDraw(); var textFormat = new TextFormat(dwFactory, "Consolas", 48) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Center, ParagraphAlignment = ParagraphAlignment.Center }; var textBrush = new SharpDX.Direct2D1.SolidColorBrush( renderTarget, SharpDX.Colors.Blue); renderTarget.Clear(Colors.White); renderTarget.DrawText( "Hi, mom!", textFormat, new RectangleF(0, 0, width, height), textBrush); renderTarget.EndDraw(); var ms = new MemoryStream(); var stream = new WICStream( wicFactory, ms); var encoder = new PngBitmapEncoder(wicFactory); encoder.Initialize(stream); var frameEncoder = new BitmapFrameEncode(encoder); frameEncoder.Initialize(); frameEncoder.SetSize(width, height); frameEncoder.PixelFormat = WicPixelFormat.FormatDontCare; frameEncoder.WriteSource(wicBitmap); frameEncoder.Commit(); encoder.Commit(); frameEncoder.Dispose(); encoder.Dispose(); stream.Dispose(); ms.Position = 0; return ms; }
private static void FlushCurrentFrame(GifBitmapEncoder encoder, ImagingFactory factory, BitmapFrame bitmap) { // nothing to flush. if (bitmap == null) { return; } using (var frameEncoder = new BitmapFrameEncode(encoder)) { frameEncoder.Initialize(); frameEncoder.SetSize(bitmap.Data.Width, bitmap.Data.Height); frameEncoder.SetResolution(bitmap.Data.HorizontalResolution, bitmap.Data.VerticalResolution); // embed frame metadata. var metadataWriter = frameEncoder.MetadataQueryWriter; metadataWriter.SetMetadataByName("/grctlext/Delay", Convert.ToUInt16(bitmap.Delay/100)); metadataWriter.SetMetadataByName("/imgdesc/Left", Convert.ToUInt16(bitmap.XPos)); metadataWriter.SetMetadataByName("/imgdesc/Top", Convert.ToUInt16(bitmap.YPos)); metadataWriter.SetMetadataByName("/imgdesc/Width", Convert.ToUInt16(bitmap.Data.Width)); metadataWriter.SetMetadataByName("/imgdesc/Height", Convert.ToUInt16(bitmap.Data.Height)); using (var bitmapSource = new WicBitmap( factory, bitmap.Data, BitmapAlphaChannelOption.UsePremultipliedAlpha)) { var converter = new FormatConverter(factory); converter.Initialize(bitmapSource, PixelFormat.Format8bppIndexed, BitmapDitherType.Solid, null, 0.8, BitmapPaletteType.MedianCut); frameEncoder.WriteSource(converter); frameEncoder.Commit(); } } }
internal CCTexture2D CreateTextSprite(string text, CCFontDefinition textDefinition) { if (string.IsNullOrEmpty(text)) return new CCTexture2D(); int imageWidth; int imageHeight; var textDef = textDefinition; var contentScaleFactorWidth = CCLabel.DefaultTexelToContentSizeRatios.Width; var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height; textDef.FontSize *= contentScaleFactorWidth; textDef.Dimensions.Width *= contentScaleFactorWidth; textDef.Dimensions.Height *= contentScaleFactorHeight; var font = CreateFont(textDef.FontName, textDef.FontSize); if (font == null) { CCLog.Log("Can not create font {0} with size {1}.", textDef.FontName, textDef.FontSize); return new CCTexture2D(); } var _currentFontSizeEm = textDef.FontSize; var _currentDIP = ConvertPointSizeToDIP(_currentFontSizeEm); // color var foregroundColor = Color4.White; // alignment var horizontalAlignment = textDef.Alignment; var verticleAlignement = textDef.LineAlignment; var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? TextAlignment.Trailing : (CCTextAlignment.Center == horizontalAlignment) ? TextAlignment.Center : TextAlignment.Leading; var paragraphAlign = (CCVerticalTextAlignment.Bottom == vertAlignment) ? ParagraphAlignment.Far : (CCVerticalTextAlignment.Center == vertAlignment) ? ParagraphAlignment.Center : ParagraphAlignment.Near; // LineBreak var lineBreak = (CCLabelLineBreak.Character == textDef.LineBreak) ? WordWrapping.Wrap : (CCLabelLineBreak.Word == textDef.LineBreak) ? WordWrapping.Wrap : WordWrapping.NoWrap; // LineBreak // TODO: Find a way to specify the type of line breaking if possible. var dimensions = new CCSize(textDef.Dimensions.Width, textDef.Dimensions.Height); var layoutAvailable = true; if (dimensions.Width <= 0) { dimensions.Width = 8388608; layoutAvailable = false; } if (dimensions.Height <= 0) { dimensions.Height = 8388608; layoutAvailable = false; } var fontName = font.FontFamily.FamilyNames.GetString(0); var textFormat = new TextFormat(FactoryDWrite, fontName, _currentFontCollection, FontWeight.Regular, FontStyle.Normal, FontStretch.Normal, _currentDIP); textFormat.TextAlignment = textAlign; textFormat.ParagraphAlignment = paragraphAlign; var textLayout = new TextLayout(FactoryDWrite, text, textFormat, dimensions.Width, dimensions.Height); var boundingRect = new RectangleF(); // Loop through all the lines so we can find our drawing offsets var textMetrics = textLayout.Metrics; var lineCount = textMetrics.LineCount; // early out if something went wrong somewhere and nothing is to be drawn if (lineCount == 0) return new CCTexture2D(); // Fill out the bounding rect width and height so we can calculate the yOffset later if needed boundingRect.X = 0; boundingRect.Y = 0; boundingRect.Width = textMetrics.Width; boundingRect.Height = textMetrics.Height; if (!layoutAvailable) { if (dimensions.Width == 8388608) { dimensions.Width = boundingRect.Width; } if (dimensions.Height == 8388608) { dimensions.Height = boundingRect.Height; } } imageWidth = (int)dimensions.Width; imageHeight = (int)dimensions.Height; // Recreate our layout based on calculated dimensions so that we can draw the text correctly // in our image when Alignment is not Left. if (textAlign != TextAlignment.Leading) { textLayout.MaxWidth = dimensions.Width; textLayout.MaxHeight = dimensions.Height; } // Line alignment var yOffset = (CCVerticalTextAlignment.Bottom == verticleAlignement || boundingRect.Bottom >= dimensions.Height) ? dimensions.Height - boundingRect.Bottom // align to bottom : (CCVerticalTextAlignment.Top == verticleAlignement) ? 0 // align to top : (imageHeight - boundingRect.Bottom) * 0.5f; // align to center SharpDX.WIC.Bitmap sharpBitmap = null; WicRenderTarget sharpRenderTarget = null; SolidColorBrush solidBrush = null; try { // Select our pixel format var pixelFormat = SharpDX.WIC.PixelFormat.Format32bppPRGBA; // create our backing bitmap sharpBitmap = new SharpDX.WIC.Bitmap(FactoryImaging, imageWidth, imageHeight, pixelFormat, BitmapCreateCacheOption.CacheOnLoad); // Create the render target that we will draw to sharpRenderTarget = new WicRenderTarget(Factory2D, sharpBitmap, new RenderTargetProperties()); // Create our brush to actually draw with solidBrush = new SolidColorBrush(sharpRenderTarget, foregroundColor); // Begin the drawing sharpRenderTarget.BeginDraw(); if (textDefinition.isShouldAntialias) sharpRenderTarget.AntialiasMode = AntialiasMode.Aliased; // Clear it sharpRenderTarget.Clear(TransparentColor); // Draw the text to the bitmap sharpRenderTarget.DrawTextLayout(new Vector2(boundingRect.X, yOffset), textLayout, solidBrush); // End our drawing which will commit the rendertarget to the bitmap sharpRenderTarget.EndDraw(); // Debugging purposes //var s = "Label4"; //SaveToFile(@"C:\Xamarin\" + s + ".png", _bitmap, _renderTarget); // The following code creates a .png stream in memory of our Bitmap and uses it to create our Textue2D Texture2D tex = null; using (var memStream = new MemoryStream()) { using (var encoder = new PngBitmapEncoder(FactoryImaging, memStream)) using (var frameEncoder = new BitmapFrameEncode(encoder)) { frameEncoder.Initialize(); frameEncoder.WriteSource(sharpBitmap); frameEncoder.Commit(); encoder.Commit(); } // Create the Texture2D from the png stream tex = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, memStream); } // Return our new CCTexture2D created from the Texture2D which will have our text drawn on it. return new CCTexture2D(tex); } catch (Exception exc) { CCLog.Log("CCLabel-Windows: Unable to create the backing image of our text. Message: {0}", exc.StackTrace); } finally { if (sharpBitmap != null) { sharpBitmap.Dispose(); sharpBitmap = null; } if (sharpRenderTarget != null) { sharpRenderTarget.Dispose(); sharpRenderTarget = null; } if (solidBrush != null) { solidBrush.Dispose(); solidBrush = null; } if (textFormat != null) { textFormat.Dispose(); textFormat = null; } if (textLayout != null) { textLayout.Dispose(); textLayout = null; } } // If we have reached here then something has gone wrong. return new CCTexture2D(); }
public override IPlatformRenderTargetBitmap CreateRenderTargetBitmap( int pixelWidth, int pixelHeight, double dpiX, double dpiY, Avalonia.Media.PixelFormat pixelFormat) { SharpDX.WIC.Bitmap bitmap = new SharpDX.WIC.Bitmap( this.wicFactory, pixelWidth, pixelHeight, pixelFormat.ToSharpDX(), BitmapCreateCacheOption.CacheOnLoad); return new Direct2D1RenderTargetBitmap( this.Direct2DFactory, this.wicFactory, bitmap); }