working on it ...

Filters

Explore Public Snippets

Sort by

Found 653 snippets matching: formats

    public by marksimon232  283250  0  7  1

    Swift 2: Custom logger that mimics NSLog

    Using this initializer, you can easily build a custom logger that mimics NSLog:
    public func SWLog(format: String, _ args: CVarArgType...) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = 
            NSDateFormatter.dateFormatFromTemplate(
                "mm:ss:SSS", options: 0, 
                locale: NSLocale.currentLocale())
        let timeString = 
            dateFormatter.stringFromDate(NSDate())
        print("\(timeString): " + 
            String(format: format, arguments: args))
    }

    public by lbottaro  311387  3  6  0

    Get MAC address of current interface in Python

    This python uses uuid.getnode to get current mac address as an integer. It formats the number in a standard mac address form (i.e. bytes splitted by :)
    import uuid
    print ':'.join(['{:02x}'.format((uuid.getnode() >> i) & 0xff) for i in range(0,8*6,8)][::-1])
    

    public by sherazam  3170  0  6  0

    How to Convert a Visio Shape to Other File Formats inside .NET Applications

    // Enter here the actual content of the snippet.            The code snippets below show the complete source code for adding new shapes to a Visio diagram.
    
    // [C# Code Sample]
    
    double shapeWidth = 0;
    double shapeHeight = 0;
    
    // load Visio diagram
    Diagram srcVisio = new Diagram("C:/temp/MyVisio.vsd");
    // get Visio page
    Aspose.Diagram.Page srcPage = srcVisio.Pages[1];
    // remove background page
    srcPage.BackPage = null;
    
    // get hash table of shapes, it holds id and name
    Hashtable remShapes = new Hashtable();
    //Hashtable<Long, String> remShapes = new Hashtable<Long, String>();
    foreach (Aspose.Diagram.Shape shape in srcPage.Shapes)
        // for the normal shape
        remShapes.Add(shape.ID, shape.Name);
    
    // iterate through the hash table
    foreach (DictionaryEntry shapeEntry in remShapes)
    {
        long key = (long)shapeEntry.Key;
        string val = (string)shapeEntry.Value;
        Aspose.Diagram.Shape shape = srcPage.Shapes.GetShape(key);
        // check of the shape name
        if (val.Equals("GroupShape1"))
        {
            // move shape to the origin corner
            shapeWidth = shape.XForm.Width.Value;
            shapeHeight = shape.XForm.Height.Value;
            shape.MoveTo(shapeWidth * 0.5, shapeHeight * 0.5);
            // trim page size
            srcPage.PageSheet.PageProps.PageWidth.Value = shapeWidth;
            srcPage.PageSheet.PageProps.PageHeight.Value = shapeHeight;
        }
        else
        {
            // remove shape from the Visio page and hash table
            srcPage.Shapes.Remove(shape);
        }
    }
    remShapes.Clear();
    
    // specify saving options
    Aspose.Diagram.Saving.PdfSaveOptions opts = new Aspose.Diagram.Saving.PdfSaveOptions();
    // set page count to save
    opts.PageCount = 1;
    // set starting index of the page
    opts.PageIndex = 1;
    // save it
    srcVisio.Save("C:/temp/Output.pdf", opts);
    
    
    // [VB.NET Code Sample]
    
    Dim shapeWidth As Double = 0
    Dim shapeHeight As Double = 0
    
    ' load Visio diagram
    Dim srcVisio As New Diagram("C:/temp/MyVisio.vsd")
    ' get Visio page
    Dim srcPage As Aspose.Diagram.Page = srcVisio.Pages(1)
    ' remove background page
    srcPage.BackPage = Nothing
    
    ' get hash table of shapes, it holds id and name
    Dim remShapes As New Hashtable()
    'Hashtable<Long, String> remShapes = new Hashtable<Long, String>();
    For Each shape As Aspose.Diagram.Shape In srcPage.Shapes
        ' for the normal shape
        remShapes.Add(shape.ID, shape.Name)
    Next
    
    ' iterate through the hash table
    For Each shapeEntry As DictionaryEntry In remShapes
        Dim key As Long = CLng(shapeEntry.Key)
        Dim val As String = DirectCast(shapeEntry.Value, String)
        Dim shape As Aspose.Diagram.Shape = srcPage.Shapes.GetShape(key)
        ' check of the shape name
        If val.Equals("GroupShape1") Then
    	' move shape to the origin corner
    	shapeWidth = shape.XForm.Width.Value
    	shapeHeight = shape.XForm.Height.Value
    	shape.MoveTo(shapeWidth * 0.5, shapeHeight * 0.5)
    	' trim page size
    	srcPage.PageSheet.PageProps.PageWidth.Value = shapeWidth
    	srcPage.PageSheet.PageProps.PageHeight.Value = shapeHeight
        Else
    	' remove shape from the Visio page and hash table
    	srcPage.Shapes.Remove(shape)
        End If
    Next
    remShapes.Clear()
    
    ' specify saving options
    Dim opts As New Aspose.Diagram.Saving.PdfSaveOptions()
    ' set page count to save
    opts.PageCount = 1
    ' set starting index of the page
    opts.PageIndex = 1
    ' save it
    srcVisio.Save("C:/temp/Output.pdf", opts)
    
    

    public by Geometry  777  0  4  0

    ToFloatingPointBinaryString: Formats a double as a floating point binary string, e.g. 0.25 -> 0.01

    Formats a double as a floating point binary string, e.g. 0.25 - 0.01 4 = 1.2^2 - 100 0.25 = 1.2^-2 - 0.01
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Text.RegularExpressions;
    
    /// <summary>
    /// Formats a double as a floating point binary string, e.g. 0.25 -> 0.01
    /// </summary>
    /// <param name="d"></param>
    /// <returns></returns>
    /// <example>4    = 1.2^2    -> 100
    /// 0.25 = 1.2^-2   -> 0.01
    /// </example>
    public static string ToFloatingPointBinaryString(this double d)
    {
        var dc = new DoubleComponents(d);
        dc.MaximizeExponent();
    
        var revChars = new List<char>();
    
        while (dc.Exponent < 0)
        {
            revChars.Add(((dc.Mantissa & 1L) == 1L) ? '1' : '0');
            dc.Exponent++;
            dc.Mantissa >>= 1;
        }
        revChars.Add('.');
        // Write out 0s as long as the exponent suggests
        while (dc.Exponent > 0)
        {
            revChars.Add('0');
            dc.Exponent--;
        }
        // write out the rest of the Mantissa
        while (dc.Mantissa != 0L)
        {
            revChars.Add( ((dc.Mantissa & 1L) == 1L) ? '1' : '0');
            dc.Mantissa >>= 1;
        }
                
        // Before we reverse - add a '0' to the end (which will go in front) if needed
        if (revChars.Last() == '.') revChars.Add('0');
                
        // Prepend the sign (by adding before we reverse)
        if (dc.Negative) revChars.Add('-');
        revChars.Reverse();
                
        // Now a '0' after the '.' if needed (alternative would be to strip to '.')
        if (revChars.Last() == '.') revChars.Add('0');
    
        return new string(revChars.ToArray());
    }

    public by johansonkatherine  3649  1  6  3

    Convert Email to Other Formats using Cloud API in Ruby

    This technical tip shows how developers can convert email messages to other formats like EML, MSG & MHT in cloud using ruby language.
    require 'path/to/lib/asposecloudsdk'
    
    app_sid = '****'
    app_key = '****'
    
    Aspose::Cloud::Common::AsposeApp.app_key = app_key
    Aspose::Cloud::Common::AsposeApp.app_sid = app_sid
    Aspose::Cloud::Common::AsposeApp.output_location = ''
    Aspose::Cloud::Common::Product.set_base_product_uri('http://api.aspose.com/v1.1')
    
    # Create Object of folder class
    folder = Aspose::Cloud::AsposeStorage::Folder.new
    folder.upload_file 'path/to/storage/email_test.eml'
    
    # Create object of converter
    con_obj = Aspose::Cloud::Email::Converter.new('path/to/storage/email_test.eml')
    con_obj.convert('msg')
    

    public by marksimon232  2964  0  7  1

    Swift: Revisiting printing with string formats

    You pass NSLog a format string followed by a variadic list of Objective-C-compatible parameters. 
    The parameters map to specifiers embedded within the format string.
    
    NSLog("Dictionary: %@, Double: %0.2f", ["Hello":3], 2.7)            

    public by sherazam  2657  2  5  0

    How to Control Export of Hidden Visio Pages to PDF HTML Image & Other Formats using .NET

    This tutorial shows how .NET developers can Control the Export of Hidden Visio Pages on Saving inside .NET applications. Aspose.Diagram for .NET API allows developers to include or exclude hidden Visio pages on saving diagram to PDF, HTML, Image (PNG, JPEG, GIF), SVG, and XPS files.
    // Enter here the actual content of the snippet.            //Set the Export Option for PDF
    
    // [C# Code Sample]
    
    string dataDir = @"c:\temp\";
    // load an existing Visio
    Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx");
    // get a particular page
    Page page = diagram.Pages.GetPage("Page-2");
    // set Visio page visiblity
    page.PageSheet.PageProps.UIVisibility.Value = BOOL.False;
    
    // initialize PDF save options
    PdfSaveOptions options = new PdfSaveOptions();
    // set export option of hidden Visio pages
    options.ExportHiddenPage = false;
    
    //Save the Visio diagram
    diagram.Save(dataDir + "Output.pdf", options);
    
    // [VB.NET Code Sample]
    
    Dim dataDir As String = "c:\temp\"
    ' load an existing Visio
    Dim diagram As New Diagram(dataDir & Convert.ToString("Drawing1.vsdx"))
    ' get a particular page
    Dim page As Page = diagram.Pages.GetPage("Page-2")
    ' set Visio page visiblity
    page.PageSheet.PageProps.UIVisibility.Value = BOOL.[False]
    
    ' initialize PDF save options
    Dim options As New PdfSaveOptions()
    ' set export option of hidden Visio pages
    options.ExportHiddenPage = False
    
    'Save the Visio diagram
    diagram.Save(dataDir & Convert.ToString("Output.pdf"), options)
    
    //Set the Export Option for HTML
    
    // [C# Code Sample]
    
    string dataDir = @"c:\temp\";
    // load an existing Visio
    Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx");
    // get a particular page
    Page page = diagram.Pages.GetPage("Page-2");
    // set Visio page visiblity
    page.PageSheet.PageProps.UIVisibility.Value = BOOL.False;
    
    // initialize PDF save options
    HTMLSaveOptions options = new HTMLSaveOptions();
    // set export option of hidden Visio pages
    options.ExportHiddenPage = false;
    
    //Save the Visio diagram
    diagram.Save(dataDir + "Output.html", options);
    
    // [VB.NET Code Sample]
    
    Dim dataDir As String = "c:\temp\"
    ' load an existing Visio
    Dim diagram As New Diagram(dataDir & Convert.ToString("Drawing1.vsdx"))
    ' get a particular page
    Dim page As Page = diagram.Pages.GetPage("Page-2")
    ' set Visio page visiblity
    page.PageSheet.PageProps.UIVisibility.Value = BOOL.[False]
    
    ' initialize PDF save options
    Dim options As New HTMLSaveOptions()
    ' set export option of hidden Visio pages
    options.ExportHiddenPage = False
    
    'Save the Visio diagram
    diagram.Save(dataDir & Convert.ToString("Output.html"), options)
     
    
    //Set the Export Option for Image
    
    // [C# Code Sample]
    
    string dataDir = @"c:\temp\";
    // load an existing Visio
    Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx");
    // get a particular page
    Page page = diagram.Pages.GetPage("Page-2");
    // set Visio page visiblity
    page.PageSheet.PageProps.UIVisibility.Value = BOOL.False;
    
    // initialize PDF save options
    ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.JPEG);
    // set export option of hidden Visio pages
    options.ExportHiddenPage = false;
    
    //Save the Visio diagram
    diagram.Save(dataDir + "Output.jpeg", options);
     
    // [VB.NET Code Sample]
    
    Dim dataDir As String = "c:\temp\"
    ' load an existing Visio
    Dim diagram As New Diagram(dataDir & Convert.ToString("Drawing1.vsdx"))
    ' get a particular page
    Dim page As Page = diagram.Pages.GetPage("Page-2")
    ' set Visio page visiblity
    page.PageSheet.PageProps.UIVisibility.Value = BOOL.[False]
    
    ' initialize PDF save options
    Dim options As New ImageSaveOptions(SaveFileFormat.JPEG)
    ' set export option of hidden Visio pages
    options.ExportHiddenPage = False
    
    'Save the Visio diagram
    diagram.Save(dataDir & Convert.ToString("Output.jpeg"), options)
     
    
    //Set the Export Option for SVG
    
    // [C# Code Sample]
    
    string dataDir = @"c:\temp\";
    // load an existing Visio
    Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx");
    // get a particular page
    Page page = diagram.Pages.GetPage("Page-2");
    // set Visio page visiblity
    page.PageSheet.PageProps.UIVisibility.Value = BOOL.False;
    
    // initialize PDF save options
    SVGSaveOptions options = new SVGSaveOptions();
    // set export option of hidden Visio pages
    options.ExportHiddenPage = false;
    
    //Save the Visio diagram
    diagram.Save(dataDir + "Output.svg", options);
     
    
    // [VB.NET Code Sample]
    
    Dim dataDir As String = "c:\temp\"
    ' load an existing Visio
    Dim diagram As New Diagram(dataDir & Convert.ToString("Drawing1.vsdx"))
    ' get a particular page
    Dim page As Page = diagram.Pages.GetPage("Page-2")
    ' set Visio page visiblity
    page.PageSheet.PageProps.UIVisibility.Value = BOOL.[False]
    
    ' initialize PDF save options
    Dim options As New SVGSaveOptions()
    ' set export option of hidden Visio pages
    options.ExportHiddenPage = False
    
    'Save the Visio diagram
    diagram.Save(dataDir & Convert.ToString("Output.svg"), options)
     
    
    //Set the Export Option for XPS
    
    // [C# Code Sample]
    
    string dataDir = @"c:\temp\";
    // load an existing Visio
    Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx");
    // get a particular page
    Page page = diagram.Pages.GetPage("Page-2");
    // set Visio page visiblity
    page.PageSheet.PageProps.UIVisibility.Value = BOOL.False;
    
    // initialize PDF save options
    XPSSaveOptions options = new XPSSaveOptions();
    // set export option of hidden Visio pages
    options.ExportHiddenPage = false;
    
    //Save the Visio diagram
    diagram.Save(dataDir + "Output.xps", options);
     
    
    // [VB.NET Code Sample]
    
    Dim dataDir As String = "c:\temp\"
    ' load an existing Visio
    Dim diagram As New Diagram(dataDir & Convert.ToString("Drawing1.vsdx"))
    ' get a particular page
    Dim page As Page = diagram.Pages.GetPage("Page-2")
    ' set Visio page visiblity
    page.PageSheet.PageProps.UIVisibility.Value = BOOL.[False]
    
    ' initialize PDF save options
    Dim options As New XPSSaveOptions()
    ' set export option of hidden Visio pages
    options.ExportHiddenPage = False
    
    'Save the Visio diagram
    diagram.Save(dataDir & Convert.ToString("Output.xps"), options)
    

    public by sherazam  2501  1  5  0

    How to Convert Primitive Object to a Triangle Mesh with Custom Memory Layout in .NET Apps

    This Technical tip explains how .NET developers can convert primitive object to a triangle mesh with custom memory layout. Aspose.3D for .NET API allows developers to convert any primitive object to a triangle mesh with custom memory layout. The primitives include many of the most basic and most used objects like box, sphere, plane, cylinder, and t
    // Enter here the actual content of the snippet.            
    //This code example converts a Sphere to triangle mesh with custom memory layout.
    
    // [C# Code Sample]
    
    [StructLayout(LayoutKind.Sequential)]
    struct MyVertex
    {
        [Semantic(VertexFieldSemantic.Position)]
        FVector3 position;
        [Semantic(VertexFieldSemantic.Normal)]
        FVector3 normal;
    }
    public void TypedTriMesh()
    {
        Mesh sphere = (new Sphere()).ToMesh();
        //convert any mesh into typed TriMesh
        var myMesh = TriMesh<MyVertex>.FromMesh(sphere);
        //Get the vertex data in customized vertex structure.
        MyVertex[] vertex = myMesh.VerticesToTypedArray();
        //get the 32bit and 16bit indices
        int[] indices32bit;
        ushort[] indices16bit;
        myMesh.IndicesToArray(out indices32bit);
        myMesh.IndicesToArray(out indices16bit);
        using (MemoryStream ms = new MemoryStream())
        {
            //or we can write the vertex directly into stream like:
            myMesh.WriteVerticesTo(ms);
            //the indice data can be directly write to stream, we support 32-bit and 16-bit indice.
            myMesh.Write16bIndicesTo(ms);
            myMesh.Write32bIndicesTo(ms);
        }
        Console.WriteLine("Indices = {0}, Actual vertices = {1}, vertices before merging = {2}", myMesh.IndicesCount, myMesh.VerticesCount, myMesh.UnmergedVerticesCount);
        Console.WriteLine("Total bytes of vertices in memory {0}bytes", myMesh.VerticesSizeInBytes);
    
    }
    
    //[VB.NET Code Sample]
    
    <StructLayout(LayoutKind.Sequential)> Structure MyVertex
        <Semantic(VertexFieldSemantic.Position)>
        Private position As FVector3
        <Semantic(VertexFieldSemantic.Normal)>
        Private normal As FVector3
    End Structure
    Public Sub TypedTriMesh()
        Dim sphere As Mesh = (New Sphere()).ToMesh()
        'convert any mesh into typed TriMesh
        Dim myMesh = TriMesh(Of MyVertex).FromMesh(sphere)
        'Get the vertex data in customized vertex structure.
        Dim vertex As MyVertex() = myMesh.VerticesToTypedArray()
        'get the 32bit and 16bit indices
        Dim indices32bit As Integer()
        Dim indices16bit As UShort()
        myMesh.IndicesToArray(indices32bit)
        myMesh.IndicesToArray(indices16bit)
        Using ms As New MemoryStream()
            'or we can write the vertex directly into stream like:
            myMesh.WriteVerticesTo(ms)
            'the indice data can be directly write to stream, we support 32-bit and 16-bit indice.
            myMesh.Write16bIndicesTo(ms)
            myMesh.Write32bIndicesTo(ms)
        End Using
        Console.WriteLine("Indices = {0}, Actual vertices = {1}, vertices before merging = {2}", myMesh.IndicesCount, myMesh.VerticesCount, myMesh.UnmergedVerticesCount)
        Console.WriteLine("Total bytes of vertices in memory {0}bytes", myMesh.VerticesSizeInBytes)
        End Sub
    
    //This code example converts a Box to triangle mesh with custom memory layout.
    
    // [C# Code Sample]
    
    // get mesh of the Box
    Mesh box = (new Box()).ToMesh();
    //create a customized vertex layout
    VertexDeclaration vd = new VertexDeclaration();
    VertexField position = vd.AddField(VertexFieldDataType.FVector4, VertexFieldSemantic.Position);
    vd.AddField(VertexFieldDataType.FVector3, VertexFieldSemantic.Normal);
    // get a triangle mesh
    TriMesh triMesh = TriMesh.FromMesh(box);
    
    //[VB.NET Code Sample]
    
    ' get mesh of the Box
    Dim box As Mesh = (New Box()).ToMesh()
    'create a customized vertex layout
    Dim vd As New VertexDeclaration()
    Dim position As VertexField = vd.AddField(VertexFieldDataType.FVector4, VertexFieldSemantic.Position)
    vd.AddField(VertexFieldDataType.FVector3, VertexFieldSemantic.Normal)
    ' get a triangle mesh
    Dim triMesh As TriMesh = TriMesh.FromMesh(box)
    
    

    public by sherazam  2323  0  6  0

    How to Add Animation Property to 3D Scene Document inside .NET Application

    // Enter here the actual content of the snippet.            
    // [C# Code Sample]
    
    // For complete examples and data files, please go to https://github.com/aspose3d/Aspose_3D_NET
    // Initialize scene object
    Scene scene = new Scene();
    
    // Call Common class create mesh using polygon builder method to set mesh instance 
    Mesh mesh = Common.CreateMeshUsingPolygonBuilder();             
    
    // Each cube node has their own translation
    Node cube1 = scene.RootNode.CreateChildNode("cube1", mesh);
    
    // Find translation property on node's transform object
    Property translation = cube1.Transform.FindProperty("Translation");
                
    // Create a curve mapping based on translation property
    CurveMapping mapping = new CurveMapping(scene, translation);
                
    // Create curve on channel X and Z
    Curve curveX = mapping.CreateCurve("X");
    Curve curveZ = mapping.CreateCurve("Z");
                
    // Move node's translation to (10, 0, 10) at 0 sec using bezier interpolation
    curveX.CreateKeyFrame(0, 10.0f, Interpolation.Bezier);
    curveZ.CreateKeyFrame(0, 10.0f, Interpolation.Bezier);
                
    // Move node's translation to (20, 0, -10) at 3 sec
    curveX.CreateKeyFrame(3, 20.0f, Interpolation.Bezier);
    curveZ.CreateKeyFrame(3, -10.0f, Interpolation.Bezier);
                
    // Move node's translation to (30, 0, 0) at 5 sec
    curveX.CreateKeyFrame(5, 30.0f, Interpolation.Linear);
    curveZ.CreateKeyFrame(5, 0.0f, Interpolation.Bezier);            
    
    // The path to the documents directory.
    string MyDir = RunExamples.GetDataDir();
    MyDir = MyDir + RunExamples.GetOutputFilePath("PropertyToDocument.fbx");            
    
    // Save 3D scene in the supported file formats
    scene.Save(MyDir, FileFormat.FBX7400ASCII);
    
    //[VB.NET Code Sample]
    
    ' For complete examples and data files, please go to https://github.com/aspose3d/Aspose_3D_NET
    ' Initialize scene object
    Dim scene As New Scene()
    
    ' Call Common class create mesh using polygon builder method to set mesh instance 
    Dim mesh As Mesh = Common.CreateMeshUsingPolygonBuilder()
    
    ' Each cube node has their own translation
    Dim cube1 As Node = scene.RootNode.CreateChildNode("cube1", mesh)
    
    ' Find translation property on node's transform object
    Dim translation As [Property] = cube1.Transform.FindProperty("Translation")
    
    ' Create a curve mapping based on translation property
    Dim mapping As New CurveMapping(scene, translation)
    
    ' Create curve on channel X and Z
    Dim curveX As Curve = mapping.CreateCurve("X")
    Dim curveZ As Curve = mapping.CreateCurve("Z")
    
    ' Move node's translation to (10, 0, 10) at 0 sec using bezier interpolation
    curveX.CreateKeyFrame(0, 10.0F, Interpolation.Bezier)
    curveZ.CreateKeyFrame(0, 10.0F, Interpolation.Bezier)
    
    ' Move node's translation to (20, 0, -10) at 3 sec
    curveX.CreateKeyFrame(3, 20.0F, Interpolation.Bezier)
    curveZ.CreateKeyFrame(3, -10.0F, Interpolation.Bezier)
    
    ' Move node's translation to (30, 0, 0) at 5 sec
    curveX.CreateKeyFrame(5, 30.0F, Interpolation.Linear)
    curveZ.CreateKeyFrame(5, 0.0F, Interpolation.Bezier)
    
    ' The path to the documents directory.
    Dim MyDir As String = RunExamples.GetDataDir()
    MyDir = MyDir & RunExamples.GetOutputFilePath("PropertyToDocument.fbx")
              
    ' Save 3D scene in the supported file formats
    scene.Save(MyDir, FileFormat.FBX7400ASCII)
    

    public by Geometry  938  0  5  0

    Create: Allocate new image in unmanaged memory.

    Allocate new image in unmanaged memory. Image width. Image height. Image pixel format. Return image allocated in unmanaged memory. Allocate new image with specified attributes in unmanaged memory. The method supports only Format8bppIndexed, Format16bppGrayScale, Format24bppRgb, Format32bppRgb, Format32bppArgb, Format32bppP
    /// <summary>
    /// Allocate new image in unmanaged memory.
    /// </summary>
    /// 
    /// <param name="width">Image width.</param>
    /// <param name="height">Image height.</param>
    /// <param name="pixelFormat">Image pixel format.</param>
    /// 
    /// <returns>Return image allocated in unmanaged memory.</returns>
    /// 
    /// <remarks><para>Allocate new image with specified attributes in unmanaged memory.</para>
    /// 
    /// <para><note>The method supports only
    /// <see cref="System.Drawing.Imaging.PixelFormat">Format8bppIndexed</see>,
    /// <see cref="System.Drawing.Imaging.PixelFormat">Format16bppGrayScale</see>,
    /// <see cref="System.Drawing.Imaging.PixelFormat">Format24bppRgb</see>,
    /// <see cref="System.Drawing.Imaging.PixelFormat">Format32bppRgb</see>,
    /// <see cref="System.Drawing.Imaging.PixelFormat">Format32bppArgb</see>,
    /// <see cref="System.Drawing.Imaging.PixelFormat">Format32bppPArgb</see>,
    /// <see cref="System.Drawing.Imaging.PixelFormat">Format48bppRgb</see>,
    /// <see cref="System.Drawing.Imaging.PixelFormat">Format64bppArgb</see> and
    /// <see cref="System.Drawing.Imaging.PixelFormat">Format64bppPArgb</see> pixel formats.
    /// In the case if <see cref="System.Drawing.Imaging.PixelFormat">Format8bppIndexed</see>
    /// format is specified, pallete is not not created for the image (supposed that it is
    /// 8 bpp grayscale image).
    /// </note></para>
    /// </remarks>
    /// 
    /// <exception cref="UnsupportedImageFormatException">Unsupported pixel format was specified.</exception>
    /// <exception cref="InvalidImagePropertiesException">Invalid image size was specified.</exception>
    /// 
    public static UnmanagedImage Create(int width, int height, PixelFormat pixelFormat)
    {
        int bytesPerPixel = 0;
    
        // calculate bytes per pixel
        switch (pixelFormat)
        {
            case PixelFormat.Format8bppIndexed:
                bytesPerPixel = 1;
                break;
            case PixelFormat.Format16bppGrayScale:
                bytesPerPixel = 2;
                break;
            case PixelFormat.Format24bppRgb:
                bytesPerPixel = 3;
                break;
            case PixelFormat.Format32bppRgb:
            case PixelFormat.Format32bppArgb:
            case PixelFormat.Format32bppPArgb:
                bytesPerPixel = 4;
                break;
            case PixelFormat.Format48bppRgb:
                bytesPerPixel = 6;
                break;
            case PixelFormat.Format64bppArgb:
            case PixelFormat.Format64bppPArgb:
                bytesPerPixel = 8;
                break;
            default:
                throw new UnsupportedImageFormatException("Can not create image with specified pixel format.");
        }
    
        // check image size
        if ((width <= 0) || (height <= 0))
        {
            throw new InvalidImagePropertiesException("Invalid image size specified.");
        }
    
        // calculate stride
        int stride = width * bytesPerPixel;
    
        if (stride % 4 != 0)
        {
            stride += (4 - (stride % 4));
        }
    
        // allocate memory for the image
        IntPtr imageData = System.Runtime.InteropServices.Marshal.AllocHGlobal(stride * height);
        Accord.SystemTools.SetUnmanagedMemory(imageData, 0, stride * height);
        System.GC.AddMemoryPressure(stride * height);
    
        UnmanagedImage image = new UnmanagedImage(imageData, width, height, stride, pixelFormat);
        image.mustBeDisposed = true;
    
        return image;
    }
    • Public Snippets
    • Channels Snippets