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

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

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

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

        //var format = WicPixelFormat.FormatDontCare;
        frameEncoder.SetPixelFormat(ref format);
        frameEncoder.WriteSource(wicBitmap);
        frameEncoder.Commit();
        encoder.Commit();
        frameEncoder.Dispose();
        encoder.Dispose();
        stream.Dispose();
        ms.Position = 0;
        return(ms);
    }
예제 #3
0
        public override 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();
        }
예제 #4
0
        public static void WritePngToStream(this Bitmap bitmap, Stream stream, int width = -1, int height = -1)
        {
            if (width <= 0)
            {
                width = bitmap.Size.Width;
            }

            if (height <= 0)
            {
                height = bitmap.Size.Height;
            }

            // ------------------------------------------------------
            // Encode a PNG image
            // ------------------------------------------------------

            // Create a WIC outputstream
            var wicStream = new WICStream(DXGraphicsService.FactoryImaging, stream);

            // Initialize a Jpeg encoder with this stream
            var encoder = new PngBitmapEncoder(DXGraphicsService.FactoryImaging);

            encoder.Initialize(wicStream);

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

            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(width, height);
            Guid guid = PixelFormat.Format32bppRGBA;

            bitmapFrameEncode.SetPixelFormat(ref guid);

            bitmapFrameEncode.WriteSource(bitmap);

            // Commit changes
            bitmapFrameEncode.Commit();
            encoder.Commit();

            // Cleanup
            bitmapFrameEncode.Options.Dispose();
            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            wicStream.Dispose();
        }
예제 #5
0
        public void Save(string fileName)
        {
            if (Path.GetExtension(fileName) != ".png")
            {
                // Yeah, we need to support other formats.
                throw new NotSupportedException("Use PNG, stoopid.");
            }

            using (FileStream s = new FileStream(fileName, FileMode.Create))
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder(factory);
                encoder.Initialize(s);

                BitmapFrameEncode frame = new BitmapFrameEncode(encoder);
                frame.Initialize();
                frame.WriteSource(this.WicImpl);
                frame.Commit();
                encoder.Commit();
            }
        }
예제 #6
0
        //
        // 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);
        }
예제 #7
0
        /// <summary>
        /// 从rss生成图像
        /// </summary>
        /// <param name="channel">从rss源获得的数据</param>
        /// <param name="path">保存图像的路径</param>
        private void GetImageFromRss(object obj)
        {
            ImageObj image    = (ImageObj)obj;
            RssInfo  rssInfo  = image.rssInfo;
            RssMedia rssMedia = image.rssMedia;
            string   fileName = "";

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

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

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

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

            try
            {
                int count = 0;

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

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

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

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

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

                    d2dRenderTarget.EndDraw();

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

                    Console.WriteLine("*********image count is : " + count++);
                    //发送单个图片生成事件
                    if (SingleGenerateCompleteEvent != null)
                    {
                        SingleGenerateCompleteEvent(fileName);
                    }
                }
                //发送生成完成事件
                if (GenerateCompleteEvent != null)
                {
                    GenerateCompleteEvent(path);
                    //停止线程,从字典删除
                    StopGenerate(rssMedia.CachePath);
                }
            }
            catch (ThreadAbortException aborted)
            {
                Trace.WriteLine("rss 图片生成线程终止 : " + aborted.Message);
            }
            catch (Exception ex)
            {
                Trace.WriteLine("rss 图片生成遇到bug : " + ex.Message);
            }
            finally
            {
                wicFactory.Dispose();
                d2dFactory.Dispose();
                dwFactory.Dispose();
                wicBitmap.Dispose();
                d2dRenderTarget.Dispose();
                solidColorBrush.Dispose();
                textBodyBrush.Dispose();
                titleColorBrush.Dispose();
                publishDateColorBrush.Dispose();
                rssInfo.Dispose();
                rssMedia.Dispose();
                wicFactory            = null;
                d2dFactory            = null;
                dwFactory             = null;
                wicBitmap             = null;
                d2dRenderTarget       = null;
                solidColorBrush       = null;
                textBodyBrush         = null;
                titleColorBrush       = null;
                publishDateColorBrush = null;
                rssInfo  = null;
                rssMedia = null;
                pages.Clear();
                pages = null;
            }
        }