Framework / Web Forms / Direct Image Streaming

In This Topic
    Direct Image Streaming
    In This Topic
     Streaming an Image to the Browser

    There are two ways to directly create a chart/diagram image without having a web form with a Nevron Chart/Diagram control in it: via an HTTP handler and via an image generating ASP.NET page.

     HTTP Handler

    To render a chart/diagram from an HTTP handler, the following steps must be performed:

    1. Add the HTTP handler class to the App_Code folder of your web site. The HTTP handler class must implement the IHttpHandler.
    2. Add the required using statements:

      If you are using Nevron Chart for .NET:

      C#
      Copy Code
      using System.IO;
      using System.Drawing;
      
      using Nevron.UI.WebForm.Controls;
      using Nevron.GraphicsCore;
      using Nevron.Dom;
      
      using Nevron.Chart;
      using Nevron.Chart.WebForm;
      
      Visual Basic
      Copy Code
      Imports System.IO
      Imports System.Drawing
      
      Imports Nevron.UI.WebForm.Controls
      Imports Nevron.GraphicsCore
      Imports Nevron.Dom
      
      Imports Nevron.Chart
      Imports Nevron.Chart.WebForm
      

      If you are using Nevron Diagram for .NET:

      C#
      Copy Code
      using System.IO;
      using System.Drawing;
      
      using Nevron.GraphicsCore;
      using Nevron.Diagram;
      using Nevron.Diagram.Shapes;
      using Nevron.Diagram.WebForm;
      
      Visual Basic
      Copy Code
      Imports System.IO
      Imports System.Drawing
      
      Imports Nevron.GraphicsCore
      Imports Nevron.Diagram
      Imports Nevron.Diagram.Shapes
      Imports Nevron.Diagram.WebForm
      

      Make sure the corresponding Nevron assemblies are referenced by the web site.An easy way to achieve this is to drop a chart/diagram control to some web form that is part of the project and then to remove it. Visual Studio will add all required references to the web site automatically.

    3. In the ProcessRequest method read any possible request fields that will configure the chart/diagram, then add code that is similar to the following snippet:

      If you are using Nevron Chart for .NET:

      C#
      Copy Code
      MemoryStream ms = new MemoryStream();
      NSize chartSize = new NSize(500, 200);
      NDocument document = CreateDocument(chartSize);
      NPngImageFormat imageFormat = new NPngImageFormat();
      using(INImage image = CreateImage(document, chartSize, imageFormat))
      {
            document.Refresh();
            image.SaveToStream(ms, imageFormat);
      }
      
      byte[] bytes = ms.GetBuffer();
      context.Response.ContentType = "image/png";
      context.Response.OutputStream.Write(bytes, 0, bytes.Length);
      context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
      
      Visual Basic
      Copy Code
      Dim Ms As MemoryStream = New MemoryStream()
      Dim ChartSize As NSize  = New NSize(500, 200)
      Dim Document As NDocument = CreateDocument(ChartSize)
      Dim ImageFormat As NPngImageFormat = New NPngImageFormat()
      Using Image As INImage = CreateImage(Document, ChartSize, ImageFormat)
          Document.Refresh()
          Image.SaveToStream(Ms, ImageFormat)
      End Using
      
      Dim bytes() As Byte = Ms.GetBuffer()
      Context.Response.ContentType = "image/png"
      Context.Response.OutputStream.Write(bytes, 0, bytes.Length)
      Context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate)
      

      If you are using Nevron Diagram for .NET:

      C#
      Copy Code
      NDrawingDocument document = CreateDocument();
      NCanvas canvas = CreateCanvas(document);
      
      document.RefreshAllViews();
      canvas.DoLayout();
      
      MemoryStream ms = new MemoryStream();
      
      NPngImageFormat imageFormat = new NPngImageFormat();
      using(INImage image = CreateImage(document, canvas, canvas.Size, imageFormat))
      {
            image.SaveToStream(ms, imageFormat);
      }
      
      byte[] bytes = ms.GetBuffer();
      context.Response.ContentType = "image/png";
      context.Response.OutputStream.Write(bytes, 0, bytes.Length);
      context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
      
      Visual Basic
      Copy Code
      Dim Document As NDrawingDocument = CreateDocument()
      Dim Canvas As NCanvas = CreateCanvas(Document)
      
      Document.RefreshAllViews()
      Canvas.DoLayout()
      
      Dim Ms As MemoryStream = New MemoryStream()
      
      Dim ImageFormat As NPngImageFormat = New NPngImageFormat()
      Using Image As INImage = CreateImage(Document, Canvas, Canvas.Size, ImageFormat)
            Image.SaveToStream(Ms, ImageFormat)
      End Using
      
      Dim Bytes() As Byte = Ms.GetBuffer()
      Context.Response.ContentType = "image/png"
      Context.Response.OutputStream.Write(Bytes, 0, Bytes.Length)
      Context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate)
      
    4. Implement the CreateDocument, CreateImageand CreateCanvas(diagram only)  methods:

      If you are using Nevron Chart for .NET:

      C#
      Copy Code
      NDocument CreateDocument(NSize chartSize)
      {
          NDocument document = new NDocument();
          NChartchart = document.RootPanel.Charts[0];
          NLineSeries line = new NLineSeries();
      
          line.Values.Add(10);
          line.Values.Add(20);
          line.Values.Add(30);
          line.Values.Add(40);
      
          line.BorderStyles[0] = new NStrokeStyle(Color.Red);
          line.BorderStyles[1] = new NStrokeStyle(Color.Blue);
          line.BorderStyles[2] = new NStrokeStyle(Color.Green);
      
          chart.Series.Add(line);
          return document;
      }
      
      protected INImage CreateImage(NDocument document, NSize size, NPngImageFormat imageFormat)
      {
          INImageFormatProvider imageFormatProvider = new NChartRasterImageFormatProvider(document);
          return imageFormatProvider.ProvideImage(size, NResolution.ScreenResolution, imageFormat);
      }
      
      Visual Basic
      Copy Code
      Function CreateDocument(ByVal ChartSize As NSize) As NDocument 
          Dim Document As NDocument = New NDocument()
          NChartchart = Document.RootPanel.Charts(0)
          Dim Line As NLineSeries = New NLineSeries()
      
          Line.Values.Add(10)
          Line.Values.Add(20)
          Line.Values.Add(30)
          Line.Values.Add(40)
      
          Line.BorderStyles(0) = New NStrokeStyle(Color.Red)
          Line.BorderStyles(1) = New NStrokeStyle(Color.Blue)
          Line.BorderStyles(2) = New NStrokeStyle(Color.Green)
      
          chart.Series.Add(Line)
          return Document
      End Function
      
      Protected Function CreateImage(ByVal Document As NDocument, ByVal Size As NSize, ByValImageFormat As NPngImageFormat) As ProtectedINImage
          Dim ImageFormatProvider As INImageFormatProvider = New NChartRasterImageFormatProvider(Document)
          Return ImageFormatProvider.ProvideImage(Size, NResolution.ScreenResolution, ImageFormat)
      End Function
      

      If you are using Nevron Diagram for .NET:

      C#
      Copy Code
      NDrawingDocument CreateDocument()
      {
          NDrawingDocument document = new NDrawingDocument();
      
          document.MeasurementUnit = NGraphicsUnit.Pixel;
          document.ViewLayout = CanvasLayout.Fit;
          document.DocumentPadding = new Nevron.Diagram.NMargins(10);
      
          document.BeginInit();
      
          document.Bounds = new NRectangleF(0, 0, 420, 320);
          document.BackgroundStyle.FrameStyle.Visible = false;
          NBasicShapesFactory factory = new NBasicShapesFactory(document);
      
          NEllipseShape ellipse = factory.CreateShape((int)BasicShapes.Ellipse) as NEllipseShape;
          ellipse.Name = "myEllipse";
          ellipse.Width = 250f;
          ellipse.Height = 250f;
          ellipse.Center = new NPointF(200, 200);
          ellipse.Style.FillStyle = new NGradientFillStyle(GradientStyle.Horizontal, GradientVariant.Variant1, Color.Navy, Color.White);
      
          document.ActiveLayer.AddChild(ellipse);
          document.EndInit();
      
          document.SizeToContent();
          return document;
      }
      
      NCanvas CreateCanvas(NDrawingDocument document)
      {
          NCanvas canvas = new NCanvas(document);
          canvas.Layout = CanvasLayout.Normal;
          canvas.ScaleX = 1;
          canvas.ScaleY = 1;
          canvas.GlobalVisibility = new NGlobalVisibility();
          canvas.GlobalVisibility.ShowPorts = false;
          canvas.Size = new NSize((int)document.Width, (int)document.Height);
          canvas.GraphicsSettings = document.GraphicsSettings;
      
          return canvas;
      }
      
      protected INImage CreateImage(NDrawingDocument document, NCanvas canvas, NSize size, NPngImageFormat imageFormat)
      {
          INImageFormatProvider imageFormatProvider = new NDiagramRasterImageFormatProvider(document, canvas);
          return imageFormatProvider.ProvideImage(size, NResolution.ScreenResolution, imageFormat);
      }
      
      Visual Basic
      Copy Code
      Function CreateDocument() As NDrawingDocument 
          Dim Document As NDrawingDocument = New NDrawingDocument()
      
          Document.MeasurementUnit = NGraphicsUnit.Pixel
          Document.ViewLayout = CanvasLayout.Fit
          Document.DocumentPadding = New Nevron.Diagram.NMargins(10)
      
          Document.BeginInit()
      
          document.Bounds = new NRectangleF(0, 0, 420, 320)
          document.BackgroundStyle.FrameStyle.Visible = False
          Dim Factory As NBasicShapesFactory = New NBasicShapesFactory(Document)
      
          Dim Ellipse As NEllipseShape = TryCast(Factory.CreateShape(CInt(BasicShapes.Ellipse)), NEllipseShape)
          Ellipse.Name = "myEllipse"
          Ellipse.Width = 250F
          Ellipse.Height = 250F
          Ellipse.Center = New NPointF(200, 200)
          Ellipse.Style.FillStyle = New NGradientFillStyle(GradientStyle.Horizontal, GradientVariant.Variant1, Color.Navy, Color.White)
      
          Document.ActiveLayer.AddChild(Ellipse)
          Document.EndInit()
      
          Document.SizeToContent()
          return Document
      End Function
      
      Function CreateCanvas(ByVal Document As NDrawingDocument) As NCanvas
          Dim Canvas As NCanvas = New NCanvas(Document)
          Canvas.Layout = CanvasLayout.Normal
          Ccanvas.ScaleX = 1
          Canvas.ScaleY = 1
          Canvas.GlobalVisibility = New NGlobalVisibility()
          Canvas.GlobalVisibility.ShowPorts = False
          Canvas.Size = New NSize(CInt(Document.Width), CInt(Document.Height))
          Canvas.GraphicsSettings = Document.GraphicsSettings
      
          return Canvas
      End Function
      
      Protected Function CreateImage(ByVal Document As NDrawingDocument, ByVal Canvas As NCanvas, ByVal Size As NSize, ByVal ImageFormat As NPngImageFormat) As INImage
          Dim ImageFormatProvider As INImageFormatProvider = New NDiagramRasterImageFormatProvider(Document, Canvas)
          Return ImageFormatProvider.ProvideImage(Sze, NResolution.ScreenResolution, ImageFormat)
      End Function
      
    5. Define the HTTP handler from your web.config file:

      web.config
      Copy Code
      <system.web>
        <!—- IIS 5 and IIS 6 related configuration -->
          <httpHandlers>
            <add path="DirectImage.axd" verb="*" type="MyNamespace.MyImageHandler" validate="false" />
          </httpHandlers>
      </system.web>
       
      ...
       
      <system.webServer>
         <!—- IIS 7 related configuration -->
         <handlers>
            <remove name="DirectImage" />
         ...
            <add name="DirectImage" preCondition="integratedMode" verb="*" path="DirectImage.axd" type="MyNamespace.MyImageHandler" />
         </handlers>
      </system.webServer>
      
    6.   Run the web site and test the HTTP handler by entering an URL in the web browser, similar to the following:

      http://localhost:2222/WebSite1/DirectImage.axd?myField=value

      The web browser should display a sample chart or diagram.

     Image Generating ASP.NET Page

    The NImageResponse object has a property called StreamImageToBrowser which instructs the control to directly stream the image in the HTTP response rather than generating an image to the server. When the control streams an image to the browser it will automatically change the MIME type of the response. Directly streaming an image always involves two pages - the first page must contain an HTML img tag with a src attribute pointing to the second page that actually generates the component output. The second page must not have any content other than the chart itself. For example consider the following two pages:

     

    1. Page one containing the img tag (Page1.html)

    HTML
    Copy Code
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    
    <HTML>
       <HEAD>
          <TITLE></TITLE>
          <META NAME="GENERATOR" Content="Microsoft Visual Studio 7.0">
       </HEAD>
       <BODY>
          <DIV id="DIV1" ms_positioning="FlowLayout">
             <TABLE height="44" cellSpacing="0" cellPadding="0" width="400" border="0" ms_1d_layout="TRUE">
                <TR>
                   <TD>Demonstrates the ability of Nevron Chart for .NET to binary stream an
                   image to the browser without generating a file on the server</TD>
                </TR>
            </TABLE>
         </DIV>
         <IMG height="400" width="400" alt="" src="Page2.aspx" >
       </BODY>
    </HTML>
    

    2. Page two generating the chart image (Page2.aspx)

     

    HTML
    Copy Code
    <%@ Page language="c#" %>
    <%@ Register TagPrefix="ncwc" Namespace= "Nevron.Chart.WebForm" Assembly="Nevron.Chart.WebForm"%>
    <%@ Import namespace = "System.Drawing"%>
    <%@ Import namespace = "Nevron.Chart.WebForm"%>
    <%@ Import namespace = "Nevron.Chart"%>
    <%@ Import namespace = "Nevron"%>
    <%@ Import namespace = "Nevron.GraphicsCore"%>
    
    <%
    // initialize the output of the component
    // create either a drawing view or a chart
    // [theComponent] is a valid instance of either NChartControl or NDrawingView
    // update the server settings
    
    [theComponent].ServerSettings.BrowserResponseSettings.BrowserResponsePairs.Clear();
    
    NImageResponse imageResponse = new NImageResponse();
    imageResponse.StreamImageToBrowser = true;
    [theComponent].ServerSettings.BrowserResponseSettings.DefaultResponse = imageResponse;
    
    // by providing null as a HtmlTextWriter the control
    // will automatically change the MIME type of the page
    [theComponent].RenderControl(null);
    %>
    
    See Also