public void Save(Stream systemStream, Direct2DImageFormat format) { renderTarget.EndDraw(); var stream = new WICStream(factoryManager.WicFactory, systemStream); var encoder = new BitmapEncoder(factoryManager.WicFactory, Direct2DConverter.ConvertImageFormat(format)); encoder.Initialize(stream); var bitmapFrameEncode = new BitmapFrameEncode(encoder); bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(imageWidth, imageHeight); Guid fdc = SharpDX.WIC.PixelFormat.FormatDontCare; //fdc = Direct2DConverter.ConvertImageFormat(Direct2DImageFormat.Gif); bitmapFrameEncode.SetPixelFormat(ref fdc); bitmapFrameEncode.WriteSource(wicBitmap); bitmapFrameEncode.Commit(); try { encoder.Commit(); }catch(Exception ex){ var f = ex.Message; } bitmapFrameEncode.Dispose(); encoder.Dispose(); stream.Dispose(); }
public void Save(IEnumerable<BitmapFrame> frames, Stream stream) { this.wicImpl.Initialize(stream); foreach (WicBitmapSource source in frames.Select(x => x.PlatformImpl)) { BitmapFrameEncode frame = new BitmapFrameEncode(this.wicImpl); frame.Initialize(); frame.WriteSource(source.WicImpl); frame.Commit(); } this.wicImpl.Commit(); }
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))); }
private static void EncodeMetadata(BitmapFrameEncode frame, Guid containerFormat, DataFormat format) { var metawriter = frame.MetadataQueryWriter; if (metawriter != null) { bool sRgb = TextureHelper.IsSRgb(format); if (containerFormat == ContainerFormatGuids.Png) { metawriter.SetMetadataByName("/tEXt/{str=Software}", "DirectXTex"); if (sRgb) metawriter.SetMetadataByName("/sRGB/RenderingIntent", (byte)0); } else if (containerFormat == ContainerFormatGuids.Jpeg) { metawriter.SetMetadataByName("/app1/ifd/{ushort=305}", "DirectXTex"); if (sRgb) metawriter.SetMetadataByName("/app1/ifd/exif/{ushort=40961}", (ushort)1); } else if (containerFormat == ContainerFormatGuids.Tiff) { metawriter.SetMetadataByName("/ifd/{ushort=305}", "DirectXTex"); if (sRgb) metawriter.SetMetadataByName("/ifd/exif/{ushort=40961}", (ushort)1); } else { metawriter.SetMetadataByName("System.ApplicationName", "DirectXTex"); if (sRgb) metawriter.SetMetadataByName("System.Image.ColorSpace", (ushort)1); } } }
private static void EncodeImage(ImagingFactory imagingFactory, Image image, WicFlags flags, Guid containerFormat, BitmapFrameEncode frame) { Guid pfGuid = ToWic(image.Format, false); frame.Initialize(); frame.SetSize(image.Width, image.Height); frame.SetResolution(72, 72); Guid targetGuid = pfGuid; frame.SetPixelFormat(ref targetGuid); EncodeMetadata(frame, containerFormat, image.Format); if (targetGuid != pfGuid) { // Conversion required to write. GCHandle handle = GCHandle.Alloc(image.Data, GCHandleType.Pinned); using (var source = new Bitmap(imagingFactory, image.Width, image.Height, pfGuid, new DataRectangle(handle.AddrOfPinnedObject(), image.RowPitch), image.Data.Length)) { using (var converter = new FormatConverter(imagingFactory)) { if (!converter.CanConvert(pfGuid, targetGuid)) { throw new NotSupportedException("Format conversion is not supported."); } converter.Initialize(source, targetGuid, GetWicDither(flags), null, 0, BitmapPaletteType.Custom); frame.WriteSource(converter, new Rectangle(0, 0, image.Width, image.Height)); } } handle.Free(); } else { // No conversion required. frame.WritePixels(image.Height, image.RowPitch, image.Data); } frame.Commit(); }
private static void EncodeImage(ImagingFactory imagingFactory, Image image, WicFlags flags, Guid containerFormat, BitmapFrameEncode frame) { Guid pfGuid = ToWic(image.Format, false); frame.Initialize(); frame.SetSize(image.Width, image.Height); frame.SetResolution(72, 72); Guid targetGuid = pfGuid; frame.SetPixelFormat(ref targetGuid); EncodeMetadata(frame, containerFormat, image.Format); if (targetGuid != pfGuid) { // Conversion required to write. GCHandle handle = GCHandle.Alloc(image.Data, GCHandleType.Pinned); using (var source = new Bitmap(imagingFactory, image.Width, image.Height, pfGuid, new DataRectangle(handle.AddrOfPinnedObject(), image.RowPitch), image.Data.Length)) { using (var converter = new FormatConverter(imagingFactory)) { if (!converter.CanConvert(pfGuid, targetGuid)) throw new NotSupportedException("Format conversion is not supported."); converter.Initialize(source, targetGuid, GetWicDither(flags), null, 0, BitmapPaletteType.Custom); frame.WriteSource(converter, new Rectangle(0, 0, image.Width, image.Height)); } } handle.Free(); } else { // No conversion required. frame.WritePixels(image.Height, image.RowPitch, image.Data); } frame.Commit(); }
private static void EncodeSingleFrame( PixelBuffer pixelBuffer, WICFlags flags, Guid guidContainerFormat, Stream stream ) { using (var encoder = new BitmapEncoder(Factory, guidContainerFormat, stream)) { using (var frame = new BitmapFrameEncode(encoder)) { if (guidContainerFormat == ContainerFormatGuids.Bmp) { try { frame.Options.Set("EnableV5Header32bppBGRA", true); } catch { } } EncodeImage(pixelBuffer, flags, frame); 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(); } }
public void Save(string fileName) { if (Path.GetExtension(fileName) != ".png") { // Yeah, we need to support other formats. throw new NotSupportedException("Use PNG, stoopid."); } using (FileStream s = new FileStream(fileName, FileMode.Create)) { PngBitmapEncoder encoder = new PngBitmapEncoder(this.factory); encoder.Initialize(s); BitmapFrameEncode frame = new BitmapFrameEncode(encoder); frame.Initialize(); frame.WriteSource(this.WicImpl); frame.Commit(); encoder.Commit(); } }
public async Task<System.IO.MemoryStream> RenderLabelToStream( float imageWidth, float imageHeight, Color4 foregroundColor, Vector2 origin, TextLayout textLayout, float dpi = DEFAULT_DPI, SharpDX.DXGI.Format format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode alpha = AlphaMode.Premultiplied) { // Get stream var pngStream = new MemoryStream(); using (var renderTarget = RenderLabel( imageWidth, imageHeight, foregroundColor, origin, textLayout, dpi, format, alpha)) { pngStream.Position = 0; // Create a WIC outputstream using (var wicStream = new WICStream(FactoryImaging, pngStream)) { var size = renderTarget.PixelSize; // Initialize a Png encoder with this stream using (var wicBitmapEncoder = new PngBitmapEncoder(FactoryImaging, wicStream)) { // Create a Frame encoder using (var wicFrameEncoder = new BitmapFrameEncode(wicBitmapEncoder)) { wicFrameEncoder.Initialize(); // Create image encoder ImageEncoder wicImageEncoder; ImagingFactory2 factory2 = new ImagingFactory2(); wicImageEncoder = new ImageEncoder(factory2, D2DDevice); var imgParams = new ImageParameters(); imgParams.PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied); imgParams.PixelHeight = (int)size.Height; imgParams.PixelWidth = (int)size.Width; wicImageEncoder.WriteFrame(renderTarget, wicFrameEncoder, imgParams); //// Commit changes wicFrameEncoder.Commit(); wicBitmapEncoder.Commit(); byte[] buffer = new byte[pngStream.Length]; pngStream.Position = 0; await pngStream.ReadAsync(buffer, 0, (int)pngStream.Length); } } } } return pngStream; }
public void Save(Stream stream) { PngBitmapEncoder encoder = new PngBitmapEncoder(_factory); encoder.Initialize(stream); BitmapFrameEncode frame = new BitmapFrameEncode(encoder); frame.Initialize(); frame.WriteSource(WicImpl); frame.Commit(); encoder.Commit(); }
/// <summary> /// 将 Direct2D 位图保存到文件中。 /// </summary> /// <param name="image">要保存的位图。</param> /// <param name="fileName">要保存的文件名。</param> public void SaveBitmapToFile(Bitmap image, string fileName) { using (ImagingFactory2 factory = new ImagingFactory2()) { using (WICStream stream = new WICStream(factory, fileName, NativeFileAccess.Write)) { using (BitmapEncoder encoder = new PngBitmapEncoder(factory)) { encoder.Initialize(stream); using (BitmapFrameEncode bitmapFrameEncode = new BitmapFrameEncode(encoder)) { bitmapFrameEncode.Initialize(); int width = image.PixelSize.Width; int height = image.PixelSize.Height; bitmapFrameEncode.SetSize(width, height); Guid wicPixelFormat = WICPixelFormat; bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat); using (ImageEncoder imageEncoder = new ImageEncoder(factory, this.d2DDevice)) { imageEncoder.WriteFrame(image, bitmapFrameEncode, new ImageParameters(D2PixelFormat, 96, 96, 0, 0, width, height)); bitmapFrameEncode.Commit(); encoder.Commit(); } } } } } }
/// <summary> /// SharpDX WIC sample. Encode to JPG and decode. /// </summary> static void Main() { const int width = 512; const int height = 512; const string filename = "output.jpg"; var factory = new ImagingFactory(); WICStream stream = null; // ------------------------------------------------------ // Encode a JPG image // ------------------------------------------------------ // Create a WIC outputstream if (File.Exists(filename)) File.Delete(filename); stream = new WICStream(factory, filename, NativeFileAccess.Write); // Initialize a Jpeg encoder with this stream var encoder = new JpegBitmapEncoder(factory); encoder.Initialize(stream); // Create a Frame encoder var bitmapFrameEncode = new BitmapFrameEncode(encoder); bitmapFrameEncode.Options.ImageQuality = 0.8f; bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(width, height); var guid = PixelFormat.Format24bppBGR; bitmapFrameEncode.SetPixelFormat(ref guid); // Write a pseudo-plasma to a buffer int stride = PixelFormat.GetStride(PixelFormat.Format24bppBGR, width); var bufferSize = height * stride; var buffer = new DataStream(bufferSize, true, true); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { buffer.WriteByte((byte)(x / 2.0 + 20.0 * Math.Sin(y / 40.0))); buffer.WriteByte((byte)(y / 2.0 + 30.0 * Math.Sin(x / 80.0))); buffer.WriteByte((byte)(x / 2.0)); } } // Copy the pixels from the buffer to the Wic Bitmap Frame encoder bitmapFrameEncode.WritePixels(512, new DataRectangle(buffer.DataPointer, stride)); // Commit changes bitmapFrameEncode.Commit(); encoder.Commit(); bitmapFrameEncode.Dispose(); encoder.Dispose(); stream.Dispose(); // ------------------------------------------------------ // Decode the previous JPG image // ------------------------------------------------------ // Read input stream = new WICStream(factory, filename, NativeFileAccess.Read); var decoder = new JpegBitmapDecoder(factory); decoder.Initialize(stream, DecodeOptions.CacheOnDemand); var bitmapFrameDecode = decoder.GetFrame(0); var queryReader = bitmapFrameDecode.MetadataQueryReader; // Dump MetadataQueryreader queryReader.Dump(Console.Out); queryReader.Dispose(); bitmapFrameDecode.Dispose(); decoder.Dispose(); stream.Dispose(); // Dispose factory.Dispose(); System.Diagnostics.Process.Start(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, filename))); }
// // http://stackoverflow.com/questions/9151615/how-does-one-use-a-memory-stream-instead-of-files-when-rendering-direct2d-images // // Identical to above SO question, except that we are rendering to MemoryStream because it was added to the API // private MemoryStream RenderStaticTextToBitmap() { var width = 400; var height = 100; var pixelFormat = WicPixelFormat.Format32bppBGR; var wicFactory = new ImagingFactory(); var dddFactory = new SharpDX.Direct2D1.Factory(); var dwFactory = new SharpDX.DirectWrite.Factory(); var wicBitmap = new Bitmap( wicFactory, width, height, pixelFormat, BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new RenderTargetProperties( RenderTargetType.Default, new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); var renderTarget = new WicRenderTarget( dddFactory, wicBitmap, renderTargetProperties) { TextAntialiasMode = TextAntialiasMode.Cleartype }; renderTarget.BeginDraw(); var textFormat = new TextFormat(dwFactory, "Consolas", 48) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Center, ParagraphAlignment = ParagraphAlignment.Center }; var textBrush = new SharpDX.Direct2D1.SolidColorBrush( renderTarget, SharpDX.Colors.Blue); renderTarget.Clear(Colors.White); renderTarget.DrawText( "Hi, mom!", textFormat, new RectangleF(0, 0, width, height), textBrush); renderTarget.EndDraw(); var ms = new MemoryStream(); var stream = new WICStream( wicFactory, ms); var encoder = new PngBitmapEncoder(wicFactory); encoder.Initialize(stream); var frameEncoder = new BitmapFrameEncode(encoder); frameEncoder.Initialize(); frameEncoder.SetSize(width, height); frameEncoder.PixelFormat = WicPixelFormat.FormatDontCare; frameEncoder.WriteSource(wicBitmap); frameEncoder.Commit(); encoder.Commit(); frameEncoder.Dispose(); encoder.Dispose(); stream.Dispose(); ms.Position = 0; return ms; }
/// <summary> /// Function to set custom encoding options. /// </summary> /// <param name="frame">Frame encoder to use.</param> internal override void SetFrameOptions(BitmapFrameEncode frame) { frame.Options.CompressionQuality = _compressionQuality; frame.Options.TiffCompressionMethod = (TiffCompressionOption)CompressionType; }
private static bool CopyTextureToWICStream(IDeviceResources deviceResource, Texture2D staging, WICStream stream, Guid pfGuid, Guid containerFormat) { using (BitmapEncoder encoder = new BitmapEncoder(deviceResource.WICImgFactory, containerFormat)) { var desc = staging.Description; encoder.Initialize(stream); Guid targetGuid = Guid.Empty; using (BitmapFrameEncode frame = new BitmapFrameEncode(encoder)) { frame.Initialize(); frame.SetSize(desc.Width, desc.Height); frame.SetResolution(72, 72); switch (desc.Format) { case global::SharpDX.DXGI.Format.R32G32B32A32_Float: case global::SharpDX.DXGI.Format.R16G16B16A16_Float: targetGuid = PixelFormat.Format96bppRGBFloat; break; case global::SharpDX.DXGI.Format.R16G16B16A16_UNorm: targetGuid = PixelFormat.Format48bppBGR; break; case global::SharpDX.DXGI.Format.R32_Float: case global::SharpDX.DXGI.Format.R16_Float: case global::SharpDX.DXGI.Format.R16_UNorm: case global::SharpDX.DXGI.Format.R8_UNorm: case global::SharpDX.DXGI.Format.A8_UNorm: targetGuid = PixelFormat.Format48bppBGR; break; default: targetGuid = PixelFormat.Format24bppBGR; break; } frame.SetPixelFormat(ref targetGuid); var databox = deviceResource.Device.ImmediateContext.MapSubresource(staging, 0, MapMode.Read, MapFlags.None); try { if (targetGuid != pfGuid) { using (Bitmap bitmap = new Bitmap(deviceResource.WICImgFactory, desc.Width, desc.Height, pfGuid, new global::SharpDX.DataRectangle(databox.DataPointer, databox.RowPitch))) { using (FormatConverter converter = new FormatConverter(deviceResource.WICImgFactory)) { if (converter.CanConvert(pfGuid, targetGuid)) { converter.Initialize(bitmap, targetGuid, BitmapDitherType.None, null, 0, BitmapPaletteType.MedianCut); frame.WriteSource(converter); } else { Debug.WriteLine("Cannot convert"); } } } } else { frame.WritePixels(desc.Height, new global::SharpDX.DataRectangle(databox.DataPointer, databox.RowPitch), databox.RowPitch * desc.Height); } } finally { deviceResource.Device.ImmediateContext.UnmapSubresource(staging, 0); } frame.Commit(); encoder.Commit(); return(true); } } }
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; bool hasPremultipliedAlpha; var font = CreateFont(textDef.FontName, textDef.FontSize); 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()); }
private static void EncodeMultiframe(ImagingFactory imagingFactory, IList<Image> images, Stream stream, Guid containerFormat, WicFlags flags) { using (var encoder = new BitmapEncoder(imagingFactory, containerFormat)) { using (var encoderInfo = encoder.EncoderInfo) { if (!encoderInfo.IsMultiframeSupported) throw new NotSupportedException("The specified image format does not support multiple frames."); } encoder.Initialize(stream); for (int i = 0; i < images.Count; i++) { var image = images[i]; using (var frame = new BitmapFrameEncode(encoder)) EncodeImage(imagingFactory, image, flags, containerFormat, frame); } encoder.Commit(); } }
/// <summary> /// Function to set custom encoding options. /// </summary> /// <param name="frame">Frame encoder to use.</param> internal override void SetFrameOptions(BitmapFrameEncode frame) { frame.Options.ImageQuality = _imageQuality; }
private static void EncodeSingleframe(ImagingFactory imagingFactory, Image image, Stream stream, Guid containerFormat, WicFlags flags) { using (var encoder = new BitmapEncoder(imagingFactory, containerFormat, stream)) { using (var frame = new BitmapFrameEncode(encoder)) { if (containerFormat == ContainerFormatGuids.Bmp) { #pragma warning disable 168 // ReSharper disable once EmptyGeneralCatchClause try { frame.Options.Set("EnableV5Header32bppBGRA", true); } catch (Exception exception) { // WIC2 is available on Windows 8 and Windows 7 SP1 with KB 2670838 installed // SharpDX: ImagingFactory2 is only available in Windows 8 build. } #pragma warning restore 168 } EncodeImage(imagingFactory, image, flags, containerFormat, frame); encoder.Commit(); } } }
/// <summary> /// Saves a texture to a stream as an image. /// </summary> /// <param name="texture">The texture to save.</param> /// <param name="imageFormat">The image format of the saved image.</param> /// <param name="imageResolutionInDpi">The image resolution in dpi.</param> /// <param name="toStream">The stream to save the texture to.</param> public static void SaveToStream(this Texture2D texture, System.Drawing.Imaging.ImageFormat imageFormat, double imageResolutionInDpi, System.IO.Stream toStream) { Texture2D textureCopy = null; ImagingFactory imagingFactory = null; Bitmap bitmap = null; BitmapEncoder bitmapEncoder = null; try { textureCopy = new Texture2D(texture.Device, new Texture2DDescription { Width = (int)texture.Description.Width, Height = (int)texture.Description.Height, MipLevels = 1, ArraySize = 1, Format = texture.Description.Format, Usage = ResourceUsage.Staging, SampleDescription = new SampleDescription(1, 0), BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, OptionFlags = ResourceOptionFlags.None }); texture.Device.CopyResource(texture, textureCopy); DataRectangle dataRectangle = textureCopy.Map(0, MapMode.Read, SharpDX.Direct3D10.MapFlags.None); imagingFactory = new ImagingFactory(); bitmap = new Bitmap( imagingFactory, textureCopy.Description.Width, textureCopy.Description.Height, PixelFormat.Format32bppBGRA, dataRectangle); toStream.Position = 0; if (imageFormat == System.Drawing.Imaging.ImageFormat.Png) bitmapEncoder = new PngBitmapEncoder(imagingFactory, toStream); else if (imageFormat == System.Drawing.Imaging.ImageFormat.Bmp) bitmapEncoder = new BmpBitmapEncoder(imagingFactory, toStream); else if (imageFormat == System.Drawing.Imaging.ImageFormat.Gif) bitmapEncoder = new GifBitmapEncoder(imagingFactory, toStream); else if (imageFormat == System.Drawing.Imaging.ImageFormat.Jpeg) bitmapEncoder = new JpegBitmapEncoder(imagingFactory, toStream); else if (imageFormat == System.Drawing.Imaging.ImageFormat.Tiff) bitmapEncoder = new TiffBitmapEncoder(imagingFactory, toStream); else bitmapEncoder = new PngBitmapEncoder(imagingFactory, toStream); using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder)) { bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height); var pixelFormat = PixelFormat.FormatDontCare; bitmapFrameEncode.SetPixelFormat(ref pixelFormat); bitmapFrameEncode.SetResolution(imageResolutionInDpi, imageResolutionInDpi); bitmapFrameEncode.WriteSource(bitmap); bitmapFrameEncode.Commit(); bitmapEncoder.Commit(); } } finally { bitmapEncoder?.Dispose(); textureCopy?.Unmap(0); textureCopy?.Dispose(); bitmap?.Dispose(); imagingFactory?.Dispose(); } }
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 bool GetThumbnail(Stream stream, int width, int height, bool cachedOnly, out byte[] imageData, out ImageType imageType) { imageData = null; imageType = ImageType.Unknown; // No support for cache if (cachedOnly) return false; try { if (stream.CanSeek) stream.Seek(0, SeekOrigin.Begin); // open the image file for reading using (var factory = new ImagingFactory2()) using (var inputStream = new WICStream(factory, stream)) using (var decoder = new BitmapDecoder(factory, inputStream, DecodeOptions.CacheOnLoad)) using (var scaler = new BitmapScaler(factory)) using (var output = new MemoryStream()) using (var encoder = new BitmapEncoder(factory, ContainerFormatGuids.Jpeg)) { // decode the loaded image to a format that can be consumed by D2D BitmapSource source = decoder.GetFrame(0); // Scale down larger images int sourceWidth = source.Size.Width; int sourceHeight = source.Size.Height; if (width > 0 && height > 0 && (sourceWidth > width || sourceHeight > height)) { if (sourceWidth <= height) width = sourceWidth; int newHeight = sourceHeight * height / sourceWidth; if (newHeight > height) { // Resize with height instead width = sourceWidth * height / sourceHeight; newHeight = height; } scaler.Initialize(source, width, newHeight, BitmapInterpolationMode.Fant); source = scaler; } encoder.Initialize(output); using (var bitmapFrameEncode = new BitmapFrameEncode(encoder)) { // Create image encoder var wicPixelFormat = PixelFormat.FormatDontCare; bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(source.Size.Width, source.Size.Height); bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat); bitmapFrameEncode.WriteSource(source); bitmapFrameEncode.Commit(); encoder.Commit(); } imageData = output.ToArray(); imageType = ImageType.Jpeg; return true; } } catch (Exception e) { // ServiceRegistration.Get<ILogger>().Warn("WICThumbnailProvider: Error loading bitmapSource from file data stream", e); return false; } }
//------------------------------------------------------------------------------------- // Encodes a single frame //------------------------------------------------------------------------------------- private static void EncodeImage( PixelBuffer image, WICFlags flags, BitmapFrameEncode frame) { Guid pfGuid; if (! ToWIC(image.Format, out pfGuid)) throw new NotSupportedException("Format not supported"); frame.Initialize(); frame.SetSize(image.Width, image.Height); frame.SetResolution(72, 72); Guid targetGuid = pfGuid; frame.SetPixelFormat(ref targetGuid); if (targetGuid != pfGuid) { using (var source = new Bitmap(Factory, image.Width, image.Height, pfGuid, new DataRectangle(image.DataPointer, image.RowStride), image.BufferStride)) { using (var converter = new FormatConverter(Factory)) { using (var palette = new Palette(Factory)) { palette.Initialize(source, 256, true); converter.Initialize(source, targetGuid, GetWICDither(flags), palette, 0, BitmapPaletteType.Custom); int bpp = GetBitsPerPixel(targetGuid); if (bpp == 0) throw new NotSupportedException("Unable to determine the Bpp for the target format"); int rowPitch = (image.Width * bpp + 7) / 8; int slicePitch = rowPitch * image.Height; var temp = Utilities.AllocateMemory(slicePitch); try { converter.CopyPixels(rowPitch, temp, slicePitch); frame.Palette = palette; frame.WritePixels(image.Height, temp, rowPitch, slicePitch); } finally { Utilities.FreeMemory(temp); } } } } } else { // No conversion required frame.WritePixels(image.Height, image.DataPointer, image.RowStride, image.BufferStride); } frame.Commit(); }
private static void Save(Resource res, Stream stream, ImageFileFormat fmt) { var texture = res as Texture2D; var textureCopy = new Texture2D(MyRender11.Device, new Texture2DDescription { Width = (int)texture.Description.Width, Height = (int)texture.Description.Height, MipLevels = 1, ArraySize = 1, Format = texture.Description.Format, Usage = ResourceUsage.Staging, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, OptionFlags = ResourceOptionFlags.None }); MyRender11.DeviceContext.CopyResource(res, textureCopy); DataStream dataStream; var dataBox = MyRender11.DeviceContext.MapSubresource( textureCopy, 0, 0, MapMode.Read, MapFlags.None, out dataStream); var dataRectangle = new DataRectangle { DataPointer = dataStream.DataPointer, Pitch = dataBox.RowPitch }; var bitmap = new Bitmap( MyRender11.WIC, textureCopy.Description.Width, textureCopy.Description.Height, PixelFormatFromFormat(textureCopy.Description.Format), // TODO: should use some conversion from textureCopy.Description.Format dataRectangle); using (var wicStream = new WICStream(MyRender11.WIC, stream)) { BitmapEncoder bitmapEncoder; switch (fmt) { case ImageFileFormat.Png: bitmapEncoder = new PngBitmapEncoder(MyRender11.WIC, wicStream); break; case ImageFileFormat.Jpg: bitmapEncoder = new JpegBitmapEncoder(MyRender11.WIC, wicStream); break; case ImageFileFormat.Bmp: bitmapEncoder = new BmpBitmapEncoder(MyRender11.WIC, wicStream); break; default: MyRenderProxy.Assert(false, "Unsupported file format."); bitmapEncoder = null; break; } if (bitmapEncoder != null) { using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder)) { bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height); var pixelFormat = PixelFormat.FormatDontCare; bitmapFrameEncode.SetPixelFormat(ref pixelFormat); bitmapFrameEncode.WriteSource(bitmap); bitmapFrameEncode.Commit(); bitmapEncoder.Commit(); } bitmapEncoder.Dispose(); } } MyRender11.DeviceContext.UnmapSubresource(textureCopy, 0); textureCopy.Dispose(); bitmap.Dispose(); }
//------------------------------------------------------------------------------------- // Encodes an image array //------------------------------------------------------------------------------------- private static void EncodeMultiframe( PixelBuffer[] images, int count, WICFlags flags, Guid guidContainerFormat, Stream stream ) { if ( images.Length < 2 ) throw new ArgumentException("Cannot encode to multiple frame. Image doesn't have multiple frame"); using (var encoder = new BitmapEncoder(Factory, guidContainerFormat)) { using (var eInfo = encoder.EncoderInfo) { if (!eInfo.IsMultiframeSupported) throw new NotSupportedException("Cannot encode to multiple frame. Format is not supporting multiple frame"); } encoder.Initialize(stream); for (int i = 0; i < Math.Min(images.Length, count); i++) { var pixelBuffer = images[i]; using (var frame = new BitmapFrameEncode(encoder)) EncodeImage(pixelBuffer, flags, frame); } encoder.Commit(); } }
private static void Save(IResource res, Stream stream, ImageFileFormat fmt) { var texture = res.Resource as Texture2D; var textureCopy = new Texture2D(MyRender11.Device, new Texture2DDescription { Width = (int)texture.Description.Width, Height = (int)texture.Description.Height, MipLevels = 1, ArraySize = 1, Format = texture.Description.Format, Usage = ResourceUsage.Staging, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, OptionFlags = ResourceOptionFlags.None }); RC.CopyResource(res, textureCopy); DataStream dataStream; var dataBox = RC.MapSubresource( textureCopy, 0, 0, MapMode.Read, MapFlags.None, out dataStream); var dataRectangle = new DataRectangle { DataPointer = dataStream.DataPointer, Pitch = dataBox.RowPitch }; var bitmap = new Bitmap( MyRender11.WIC, textureCopy.Description.Width, textureCopy.Description.Height, PixelFormatFromFormat(textureCopy.Description.Format), // TODO: should use some conversion from textureCopy.Description.Format dataRectangle); using (var wicStream = new WICStream(MyRender11.WIC, stream)) { BitmapEncoder bitmapEncoder; switch (fmt) { case ImageFileFormat.Png: bitmapEncoder = new PngBitmapEncoder(MyRender11.WIC, wicStream); break; case ImageFileFormat.Jpg: bitmapEncoder = new JpegBitmapEncoder(MyRender11.WIC, wicStream); break; case ImageFileFormat.Bmp: bitmapEncoder = new BmpBitmapEncoder(MyRender11.WIC, wicStream); break; default: MyRenderProxy.Assert(false, "Unsupported file format."); bitmapEncoder = null; break; } if (bitmapEncoder != null) { using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder)) { bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height); var pixelFormat = PixelFormat.FormatDontCare; bitmapFrameEncode.SetPixelFormat(ref pixelFormat); bitmapFrameEncode.WriteSource(bitmap); bitmapFrameEncode.Commit(); bitmapEncoder.Commit(); } bitmapEncoder.Dispose(); } } RC.UnmapSubresource(textureCopy, 0); textureCopy.Dispose(); bitmap.Dispose(); }
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(); } } }
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(); } }
void colorFrameReader_FrameArrived(object sender, ColorFrameArrivedEventArgs e) { var colorFrame = e.FrameReference.AcquireFrame(); if (colorFrame != null) { using (colorFrame) { lastColorGain = colorFrame.ColorCameraSettings.Gain; lastColorExposureTimeTicks = colorFrame.ColorCameraSettings.ExposureTime.Ticks; if (yuvFrameReady.Count > 0) { lock (yuvByteBuffer) colorFrame.CopyRawFrameDataToArray(yuvByteBuffer); lock (yuvFrameReady) foreach (var autoResetEvent in yuvFrameReady) autoResetEvent.Set(); } if ((rgbFrameReady.Count > 0) || (jpegFrameReady.Count > 0)) { lock (rgbByteBuffer) colorFrame.CopyConvertedFrameDataToArray(rgbByteBuffer, ColorImageFormat.Bgra); lock (rgbFrameReady) foreach (var autoResetEvent in rgbFrameReady) autoResetEvent.Set(); } if (jpegFrameReady.Count > 0) { // should be put in a separate thread? stopWatch.Restart(); var bitmapSource = new Bitmap(imagingFactory, Kinect2Calibration.colorImageWidth, Kinect2Calibration.colorImageHeight, SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad); var bitmapLock = bitmapSource.Lock(BitmapLockFlags.Write); Marshal.Copy(rgbByteBuffer, 0, bitmapLock.Data.DataPointer, Kinect2Calibration.colorImageWidth * Kinect2Calibration.colorImageHeight * 4); bitmapLock.Dispose(); var memoryStream = new MemoryStream(); //var fileStream = new FileStream("test" + frame++ + ".jpg", FileMode.Create); //var stream = new WICStream(imagingFactory, "test" + frame++ + ".jpg", SharpDX.IO.NativeFileAccess.Write); var stream = new WICStream(imagingFactory, memoryStream); var jpegBitmapEncoder = new JpegBitmapEncoder(imagingFactory); jpegBitmapEncoder.Initialize(stream); var bitmapFrameEncode = new BitmapFrameEncode(jpegBitmapEncoder); bitmapFrameEncode.Options.ImageQuality = 0.5f; bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(Kinect2Calibration.colorImageWidth, Kinect2Calibration.colorImageHeight); var pixelFormatGuid = PixelFormat.FormatDontCare; bitmapFrameEncode.SetPixelFormat(ref pixelFormatGuid); bitmapFrameEncode.WriteSource(bitmapSource); bitmapFrameEncode.Commit(); jpegBitmapEncoder.Commit(); //fileStream.Close(); //fileStream.Dispose(); //Console.WriteLine(stopWatch.ElapsedMilliseconds + "ms " + memoryStream.Length + " bytes"); lock (jpegByteBuffer) { nJpegBytes = (int)memoryStream.Length; memoryStream.Seek(0, SeekOrigin.Begin); memoryStream.Read(jpegByteBuffer, 0, nJpegBytes); } lock (jpegFrameReady) foreach (var autoResetEvent in jpegFrameReady) autoResetEvent.Set(); //var file = new FileStream("test" + frame++ + ".jpg", FileMode.Create); //file.Write(jpegByteBuffer, 0, nJpegBytes); //file.Close(); bitmapSource.Dispose(); memoryStream.Close(); memoryStream.Dispose(); stream.Dispose(); jpegBitmapEncoder.Dispose(); bitmapFrameEncode.Dispose(); } } } }
public void Start() { if (ProcessStarted != null) ProcessStarted(); int index = 0; var rendererUtil = new RendererUtil(); // obtain file list var regionList = Directory.GetFiles(Path.Combine(worldLocation, "region"), "*.mca").ToList(); var regionEntries = new List<RegionEntry>(); foreach (string region in regionList) { try { // load the region using (RegionFile regionFile = RegionFile.OpenRegion(File.OpenRead(region))) { var renderedChunks = new List<ChunkEntry>(); if (RegionLoaded != null) RegionLoaded(regionFile); Debug.WriteLine("Rendering region"); DateTime sTime = DateTime.Now; #region Chunk render using (var renderTarget = new BitmapRenderTarget(rendererUtil.D2DDeviceContext, CompatibleRenderTargetOptions.None, new DrawingSizeF(16, 16), new DrawingSize(16, 16), new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied))) { foreach (var anvilChunk in regionFile.Content.Select(chunk => new Anvil(chunk))) { ChunkEntry entry; RenderSegment(anvilChunk, renderTarget, out entry); renderedChunks.Add(entry); } } #endregion #region Region compositor using (var renderTarget = new BitmapRenderTarget(rendererUtil.D2DDeviceContext, CompatibleRenderTargetOptions.None, new DrawingSizeF(512, 512), new DrawingSize(512, 512), new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied))) { renderTarget.BeginDraw(); renderTarget.Clear(Color.Transparent); // compose the images foreach (ChunkEntry chunk in renderedChunks) { int cxPos = chunk.XPos % 32; int czPos = chunk.ZPos % 32; if (cxPos < 0) cxPos = 32 + cxPos; if (czPos < 0) czPos = 32 + czPos; int xPos = cxPos * 16; int zPos = czPos * 16; renderTarget.Transform = Matrix3x2.Translation(xPos, zPos); renderTarget.DrawBitmap(chunk.RenderedChunk, 1, BitmapInterpolationMode.Linear); } // ReSharper disable PossibleNullReferenceException string[] info = Path.GetFileNameWithoutExtension(region).Split('.'); // ReSharper restore PossibleNullReferenceException regionEntries.Add(new RegionEntry { RenderedRegion = renderTarget.Bitmap, XPos = Convert.ToInt32(info[1]), ZPos = Convert.ToInt32(info[2]) }); renderTarget.EndDraw(); } #endregion Debug.WriteLine("Render time is: " + (DateTime.Now - sTime).Seconds + " seconds."); if (RegionRendered != null) RegionRendered(); #region Cleanup foreach (ChunkEntry chunk in renderedChunks) chunk.RenderedChunk.Dispose(); renderedChunks.Clear(); #endregion } } catch (Exception exception) { if (ProcessFailed != null) ProcessFailed(exception.Message + "\nAt:\n" + exception); } if (ProgressChanged != null) ProgressChanged(++index / (float)regionList.Count); } #region Extrema processor int xMin = 0; int zMin = 0; int xMax = 0; int zMax = 0; foreach (RegionEntry entry in regionEntries) { if (xMin > entry.XPos) xMin = entry.XPos; if (xMax < entry.XPos) xMax = entry.XPos; if (zMin > entry.ZPos) zMin = entry.ZPos; if (zMax < entry.ZPos) zMax = entry.ZPos; } int wSizeX = (xMax - xMin) * 512 + 512; int wSizeZ = (zMax - zMin) * 512 + 512; xMin = Math.Abs(xMin); zMin = Math.Abs(zMin); #endregion #region World compositor var ResultingBitmap = new Bitmap1(rendererUtil.D2DDeviceContext, new DrawingSize(wSizeX, wSizeZ), new BitmapProperties1 { BitmapOptions = BitmapOptions.Target, PixelFormat = new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied) }); rendererUtil.D2DDeviceContext.Target = ResultingBitmap; rendererUtil.D2DDeviceContext.BeginDraw(); rendererUtil.D2DDeviceContext.Clear(Color.Transparent); foreach (RegionEntry entry in regionEntries) { int xPos = ((xMin + entry.XPos) * 512); int zPos = ((zMin + entry.ZPos) * 512); rendererUtil.D2DDeviceContext.Transform = Matrix3x2.Translation(xPos, zPos); rendererUtil.D2DDeviceContext.DrawBitmap(entry.RenderedRegion, 1, BitmapInterpolationMode.Linear); } rendererUtil.D2DDeviceContext.EndDraw(); #endregion #region File save FileStream file = File.OpenWrite(Path.GetFileName(worldLocation) + ".png"); var encoder = new PngBitmapEncoder(rendererUtil.ImagingFactory); encoder.Initialize(file); var frameEncode = new BitmapFrameEncode(encoder); frameEncode.Initialize(); var imageEncoder = new ImageEncoder(rendererUtil.ImagingFactory, rendererUtil.D2DDevice); imageEncoder.WriteFrame(ResultingBitmap, frameEncode, new ImageParameters( new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied), 96, 96, 0, 0, wSizeX, wSizeZ)); frameEncode.Commit(); encoder.Commit(); #endregion #region Cleanup file.Close(); file.Dispose(); foreach (RegionEntry bitmap in regionEntries) { bitmap.RenderedRegion.Dispose(); } regionEntries.Clear(); rendererUtil.Dispose(); theBlocks.Dispose(); ResultingBitmap.Dispose(); #endregion if (ProcessComplete != null) ProcessComplete(); }