locked
Unsafe C# Code in PowerShell. RRS feed

  • Question

  • I am getting following error when running below code in Powershell. Does anyone know how i can set the unsafe mode in powershell ? 

      

    Add-Type : c:\Users\01085736\AppData\Local\Temp\3u2uqldp.0.cs(61) : Unsafe code may only appear if compiling with /unsafe
    c:\Users\01085736\AppData\Local\Temp\3u2uqldp.0.cs(60) : 
    c:\Users\01085736\AppData\Local\Temp\3u2uqldp.0.cs(61) : >>>         public unsafe bool IsBlackandWhiteImage(string imagePath)
    c:\Users\01085736\AppData\Local\Temp\3u2uqldp.0.cs(62) :         {
    At \\usinffil02\user\01085736\My Documents\PROJECT\IsColorUnsafe.ps1:158 char:1
    + Add-Type -TypeDefinition $cSharp -ReferencedAssemblies $assemblies
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidData: (c:\Users\010857...ng with /unsafe:CompilerError) [Add-Type], Exception
        + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddTypeCommand

    Add-Type : Cannot add type. Compilation errors occurred.
    At \\usinffil02\user\01085736\My Documents\PROJECT\IsColorUnsafe.ps1:158 char:1
    + Add-Type -TypeDefinition $cSharp -ReferencedAssemblies $assemblies
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidData: (:) [Add-Type], InvalidOperationException
        + FullyQualifiedErrorId : COMPILER_ERRORS,Microsoft.PowerShell.Commands.AddTypeCommand

    Unable to find type [isColor.CheckGrayScale]. Make sure that the assembly that contains this type is loaded.
    At \\usinffil02\user\01085736\My Documents\PROJECT\IsColorUnsafe.ps1:159 char:1
    + [isColor.CheckGrayScale]::Main()
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (isColor.CheckGrayScale:TypeName) [], RuntimeException
        + FullyQualifiedErrorId : TypeNotFound

    $path = "C:\Windows\Microsoft.NET\Framework\v4.0.30319"
    $assemblies = @(
        "$path\System.Windows.Forms.dll",
        "$path\System.Drawing.dll",
        "System.Core"
    )

    $cSharp = @"
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Text;

    namespace  isColor



        public partial class CheckGrayScale


     

            public void Main()
            {
                string imageColor = "";

                int isBlackAndWhite;
                string colorImaageDir = @"C:\Users\vinay\Documents\Images\IsColor";
                string blackAndWhiteImageDir = @"CC:\Users\vinay\Documents\Images\IsBlackAndWhite";
                // TODO: Add your code here
                var imageName = "abcd.jpg";
                var imagePath = @"C:\Users\vinay\Documents\Images\" + imageName;
                //string imagePath = Dts.Variables["User::FileFullQName"].Value.ToString();
                var response = IsBlackandWhiteImage(imagePath);
                //var  imageColor = new List<string>();

                //ImageMagickObject.MagickImage img = new ImageMagickObject.MagickImage();
                //object[] args = new object[] { "-format", "%r", imagePath };
                //object result = img.Identify(ref args);


                if (response)
                {
                    imageColor = "Black & White Image";
                    isBlackAndWhite = 1;
                    // System.IO.File.Move(imagePath, blackAndWhiteImageDir);
                }
                else
                {
                    imageColor = "Color Image ";
                    isBlackAndWhite = 0;
                    //System.IO.File.Move(imagePath, colorImaageDir);
                }
                //MessageBox.Show(imageColor + imagePath);

                //Dts.Variables["User::IsBlackAndWhite"].Value = isBlackAndWhite;
                //  Dts.Variables["User::IsBlackAndWhite"].Value = ;

                //ImageMagickNET.MagickNet.InitializeMagick();
                //var image2 = new ImageMagickNET.Image(imagePath);
                //image2.Resize(new ImageMagickNET.Geometry("10%"));
                //image2.Write("Photo1.jpg");


                ///Dts.TaskResult = (int)ScriptResults.Success;
            }


            public unsafe bool IsBlackandWhiteImage(string imagePath)
            {



                Bitmap image = new Bitmap(imagePath);

                var tolerance = 6;

                string CamModel = "";
                bool res = true;
                try
                {
                    PropertyItem[] props =
                    image.PropertyItems;
                    const int IDCamModel = 272;
                    PropertyItem Make = image.GetPropertyItem(IDCamModel);
                    Encoding ascii = Encoding.ASCII;
                    CamModel = ascii.GetString(
                       Make.Value, 0, Make.Len - 1);
                }
                catch
                { }



                if (CamModel != "")
                {
                    image.Dispose();
                    res = false;
                    return res;
                }

                using (Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb))
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.DrawImage(image, 0, 0);
                    }

                    BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);

                    int* pt = (int*)data.Scan0;
                    int sz = data.Height * data.Width; //length of complete array
                    int stride = data.Stride; //bitmap stride ("scanline")
                    int cnt = stride / 4 + 1; //step for diagonal line (1 time "width_by_stride" + 1)

                    for (int i = 0; i < sz; i += cnt)
                    {

                        Color color = Color.FromArgb(pt[i]);
                        int colorRGBTotal = color.R + color.G + color.B;


                        if ((Math.Abs((colorRGBTotal / 3) - color.R) >= tolerance)
                            && (Math.Abs((colorRGBTotal / 3) - color.G) >= tolerance)
                            && (Math.Abs((colorRGBTotal / 3) - color.B) >= tolerance)
                            )
                        {

                            //string imageRGB = color.A + "|" + color.R + "|" + color.G + "|" + color.B + "|" + test +"|"+ imagePath;
                            //List<string> newLines = new List<string>();
                            //newLines.Add(imageRGB);
                            // File.AppendAllLines("C:\\test.txt", newLines);

                            res = false;
                            break;
                        }


                    }

                    bmp.UnlockBits(data);
                    bmp.Dispose();
                    image.Dispose();

                    return res;


                }


            }


        }
    }
    "@

    Add-Type -TypeDefinition $cSharp -ReferencedAssemblies $assemblies 
    [isColor.CheckGrayScale]::Main()  

    Monday, August 14, 2017 5:26 PM

Answers

  • Jrv,

    My requirement is to loop through file and all within the c# code. Is it possible to use the main Method  ? what would be the best place to plug it ? i tried right after    public static unsafe class CheckGrayScale but  i am getting message  OverloadDefinitions static void Main() and it does nothing.

    $cSharp = @'
    using System;
    using System.IO;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Text;
    
    namespace isColor
    {
    
    
        public static unsafe class CheckGrayScale
        {
    
            public static void Main()
            {
                string imageColor = "";
    
                int isBlackAndWhite;
                string colorImageDir = @"C:\Images\IsColor";
                string blackAndWhiteImageDir = @"C:\Images\IsBlackAndWhite";
                // TODO: Add your code here
                var imageName = "test123.jpg";
                var imagePath = @"C:\Images\" + imageName;
                //string imagePath = Dts.Variables["User::FileFullQName"].Value.ToString();
                var response = IsBlackandWhiteImage(imagePath);
                //var  imageColor = new List<string>();
    
                //ImageMagickObject.MagickImage img = new ImageMagickObject.MagickImage();
                //object[] args = new object[] { "-format", "%r", imagePath };
                //object result = img.Identify(ref args);
                FileInfo fileinfo = new FileInfo(Path.Combine(imagePath));
    
                if (response)
                {
                    imageColor = "Black & White Image";
                    isBlackAndWhite = 1;
                    fileinfo.MoveTo(Path.Combine(blackAndWhiteImageDir, imageName));
                }
                else
                {
                    imageColor = "Color Image ";
                    isBlackAndWhite = 0;
                    fileinfo.MoveTo(Path.Combine(colorImageDir, imageName));
                }
    
            }
    
        
    
    
    
            public static bool IsBlackandWhiteImage(string imagePath)
            {
    
                Bitmap image = new Bitmap(imagePath);
                var tolerance = 6;
                string CamModel = "";
                bool res = true;
    
                try
                {
                    PropertyItem[] props = image.PropertyItems;
                    const int IDCamModel = 272;
                    PropertyItem Make = image.GetPropertyItem(IDCamModel);
                    Encoding ascii = Encoding.ASCII;
                    CamModel = ascii.GetString(Make.Value, 0, Make.Len - 1);
                }
                catch
                {
                }
    
                if (CamModel != "")
                {
                    image.Dispose();
                    res = false;
                    return res;
                }
    
                using (Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb))
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.DrawImage(image, 0, 0);
                    }
    
                    BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);
    
                    int* pt = (int*)data.Scan0;
                    int sz = data.Height * data.Width; //length of complete array
                    int stride = data.Stride; //bitmap stride ("scanline")
                    int cnt = stride / 4 + 1; //step for diagonal line (1 time "width_by_stride" + 1)
    
                    for (int i = 0; i < sz; i += cnt)
                    {
    
                        Color color = Color.FromArgb(pt[i]);
                        int colorRGBTotal = color.R + color.G + color.B;
    
                        if ((Math.Abs((colorRGBTotal / 3) - color.R) >= tolerance)
                            && (Math.Abs((colorRGBTotal / 3) - color.G) >= tolerance)
                            && (Math.Abs((colorRGBTotal / 3) - color.B) >= tolerance)
                            )
                        {
    
                            res = false;
                            break;
                        }
                    }
    
                    bmp.UnlockBits(data);
                    bmp.Dispose();
                    image.Dispose();
    
                    return res;
                }
            }
        }
    }
    '@
    $cp = New-Object System.CodeDom.Compiler.CompilerParameters
    $cp.ReferencedAssemblies.AddRange(('System.Windows.Forms.dll','System.Drawing.dll'))
    $cp.CompilerOptions = '/unsafe'
    Add-Type -TypeDefinition $cSharp -CompilerParameters $cp
    [isColor.CheckGrayScale]::Main


    • Marked as answer by DC_010 Tuesday, August 15, 2017 7:31 PM
    Tuesday, August 15, 2017 1:09 AM

All replies

  • Add-Type file.cs -CompilerParameters 'UNSAFE'

    \_(ツ)_/

    Monday, August 14, 2017 5:39 PM
  • I got error message that it can't be converted.

    PS C:\Users\01085736>\My Documents\PROJECT\IsColorUnsafe.ps1
    Add-Type : Cannot bind parameter 'CompilerParameters'. Cannot convert the "unsafe" value of type "System.String" to type "System.CodeDom.Compiler.CompilerParameters".
    At \My Documents\PROJECT\IsColorUnsafe.ps1:158 char:89
    + ... ilerParameters 'unsafe'
    +                    ~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:) [Add-Type], ParameterBindingException
        + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.AddTypeCommand

    Unable to find type [isColor.CheckGrayScale]. Make sure that the assembly that contains this type is loaded.
    At \My Documents\PROJECT\IsColorUnsafe.ps1:159 char:1
    + [isColor.CheckGrayScale]::Main()
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (isColor.CheckGrayScale:TypeName) [], RuntimeException
        + FullyQualifiedErrorId : TypeNotFound

     
    • Edited by DC_010 Monday, August 14, 2017 5:51 PM
    Monday, August 14, 2017 5:46 PM
  • Here is how to use parameters with a compile:

    $path = "C:\Windows\Microsoft.NET\Framework\v4.0.30319"
    $assemblies = @(
    	"$path\System.Windows.Forms.dll",
    	"$path\System.Drawing.dll"
    )
    $cp = [System.CodeDom.Compiler.CompilerParameters]::new($assemblies)
    $cp.CompilerOptions = '/unsafe'
    Add-Type -TypeDefinition $cSharp -CompilerParameters $cp


    \_(ツ)_/

    Monday, August 14, 2017 5:57 PM
  • Beware - you cannot use partial classes in PowerShell.  They require an initializer and other support.


    \_(ツ)_/

    Monday, August 14, 2017 6:15 PM
  • i tried but similar error. 

    Method invocation failed because [System.CodeDom.Compiler.CompilerParameters] does not contain a method named 'new'.
    AtMy Documents\PROJECT\IsColorUnsafe.ps1:159 char:1
    + $cp = [System.CodeDom.Compiler.CompilerParameters]::new($assemblies)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : MethodNotFound
     
    The property 'CompilerOptions' cannot be found on this object. Verify that the property exists and can be set.
    At \\usinffil02\user\01085736\My Documents\PROJECT\IsColorUnsafe.ps1:160 char:1
    + $cp.CompilerOptions = '/unsafe'
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : PropertyNotFound
     
    Add-Type : \AppData\Local\Temp\h4xie4hq.0.cs(61) : Unsafe code may only appear if compiling with /unsafe
    \AppData\Local\Temp\h4xie4hq.0.cs(60) : 
    \AppData\Local\Temp\h4xie4hq.0.cs(61) : >>>         public unsafe bool IsBlackandWhiteImage(string imagePath)
    c:\Users\01085736\AppData\Local\Temp\h4xie4hq.0.cs(62) :         {
    At \\usinffil02\user\01085736\My Documents\PROJECT\IsColorUnsafe.ps1:161 char:1
    + Add-Type  -TypeDefinition  $cSharp -CompilerParameters $cp -ReferencedAssemblies ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidData: (c:\Users\010857...ng with /unsafe:CompilerError) [Add-Type], Exception
        + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddTypeCommand
     
    Add-Type : Cannot add type. Compilation errors occurred.
    At\My Documents\PROJECT\IsColorUnsafe.ps1:161 char:1
    + Add-Type  -TypeDefinition  $cSharp -CompilerParameters $cp -ReferencedAssemblies ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidData: (:) [Add-Type], InvalidOperationException
        + FullyQualifiedErrorId : COMPILER_ERRORS,Microsoft.PowerShell.Commands.AddTypeCommand
     
    Unable to find type [isColor.CheckGrayScale]. Make sure that the assembly that contains this type is loaded.
    At \\usinffil02\user\01085736\My Documents\PROJECT\IsColorUnsafe.ps1:162 char:1
    + [isColor.CheckGrayScale]::Main()
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (isColor.CheckGrayScale:TypeName) [], RuntimeException
        + FullyQualifiedErrorId : TypeNotFound
     

    Monday, August 14, 2017 6:15 PM
  • Jrv, 

    thank you for the assistance but  can you help with above code how would i go about altering it so it would function PowerShell. 
    • Edited by DC_010 Monday, August 14, 2017 6:25 PM
    Monday, August 14, 2017 6:25 PM
  • This is an easier method to compile against the latest version of Net:

    $cp = [System.CodeDom.Compiler.CompilerParameters]::new()
    $cp.ReferencedAssemblies.AddRange(('System.Windows.Forms.dll', 'System.Drawing.dll'))
    $cp.CompilerOptions = '/unsafe'
    Add-Type -TypeDefinition $cSharp -CompilerParameters $cp


    \_(ツ)_/

    Monday, August 14, 2017 6:25 PM
  • You are using an old version of PowerShell.  You should upgrade to the latest version

    $cp =New-Object System.CodeDom.Compiler.CompilerParameters


    \_(ツ)_/

    Monday, August 14, 2017 6:30 PM
  • I have the latest i believe 

    PS C:\Users\> $PSVersionTable

    Name                           Value                                                                                                                                                          
    ----                           -----                                                                                                                                                          
    PSVersion                      4.0                                                                                                                                                            
    WSManStackVersion              3.0                                                                                                                                                            
    SerializationVersion           1.1.0.1                                                                                                                                                        
    CLRVersion                     4.0.30319.42000                                                                                                                                                
    BuildVersion                   6.3.9600.16406                                                                                                                                                 
    PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}                                                                                                                                           
    PSRemotingProtocolVersion      2.2                                                                                                                                                            

    Monday, August 14, 2017 6:32 PM
  • I think am somewhere now.  I am getting below. code compile in VS bu it's failing in powershell .

    Method invocation failed because [System.CodeDom.Compiler.CompilerParameters] does not contain a method named 'new'.
    At \\usinffil02\user\\My Documents\PROJECT\IsColorUnsafe.ps1:159 char:1
    + $cp = [System.CodeDom.Compiler.CompilerParameters]::new()
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : MethodNotFound
     
    Add-Type : Cannot add type. The type name 'isColor.CheckGrayScale' already exists.
    At \\usinffil02\user\\My Documents\PROJECT\IsColorUnsafe.ps1:162 char:1
    + Add-Type -TypeDefinition $cSharp -CompilerParameters $cp
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (isColor.CheckGrayScale:String) [Add-Type], Exception
        + FullyQualifiedErrorId : TYPE_ALREADY_EXISTS,Microsoft.PowerShell.Commands.AddTypeCommand
     
    Method invocation failed because [isColor.CheckGrayScale] does not contain a method named 'Main'.
    At \\usinffil02\user\\My Documents\PROJECT\IsColorUnsafe.ps1:163 char:1
    + [isColor.CheckGrayScale]::Main()
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : MethodNotFound

    ---------------------------- code start-------------------------

    $path = "C:\Windows\Microsoft.NET\Framework\v4.0.30319"
    $assemblies = @(
        "$path\System.Windows.Forms.dll",
        "$path\System.Drawing.dll",
        "$path\System.Data.dll",
        "$path\System.Core.dll"
    )

    $cSharp = @"
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Text;

    namespace  isColor



        public  partial class CheckGrayScale


     

            public void Main()
            {
                string imageColor = "";

                int isBlackAndWhite;
                string colorImaageDir = @"C:\Users\vinay\Documents\Images\IsColor";
                string blackAndWhiteImageDir = @"CC:\Users\vinay\Documents\Images\IsBlackAndWhite";
                // TODO: Add your code here
                var imageName = "abcd.jpg";
                var imagePath = @"C:\Users\vinay\Documents\Images\" + imageName;
                //string imagePath = Dts.Variables["User::FileFullQName"].Value.ToString();
                var response = IsBlackandWhiteImage(imagePath);
                //var  imageColor = new List<string>();

                //ImageMagickObject.MagickImage img = new ImageMagickObject.MagickImage();
                //object[] args = new object[] { "-format", "%r", imagePath };
                //object result = img.Identify(ref args);


                if (response)
                {
                    imageColor = "Black & White Image";
                    isBlackAndWhite = 1;
                    // System.IO.File.Move(imagePath, blackAndWhiteImageDir);
                }
                else
                {
                    imageColor = "Color Image ";
                    isBlackAndWhite = 0;
                    //System.IO.File.Move(imagePath, colorImaageDir);
                }
                //MessageBox.Show(imageColor + imagePath);

                //Dts.Variables["User::IsBlackAndWhite"].Value = isBlackAndWhite;
                //  Dts.Variables["User::IsBlackAndWhite"].Value = ;

                //ImageMagickNET.MagickNet.InitializeMagick();
                //var image2 = new ImageMagickNET.Image(imagePath);
                //image2.Resize(new ImageMagickNET.Geometry("10%"));
                //image2.Write("Photo1.jpg");


                ///Dts.TaskResult = (int)ScriptResults.Success;
            }


            public unsafe bool IsBlackandWhiteImage(string imagePath)
            {



                Bitmap image = new Bitmap(imagePath);

                var tolerance = 6;

                string CamModel = "";
                bool res = true;
                try
                {
                    PropertyItem[] props =
                    image.PropertyItems;
                    const int IDCamModel = 272;
                    PropertyItem Make = image.GetPropertyItem(IDCamModel);
                    Encoding ascii = Encoding.ASCII;
                    CamModel = ascii.GetString(
                       Make.Value, 0, Make.Len - 1);
                }
                catch
                { }



                if (CamModel != "")
                {
                    image.Dispose();
                    res = false;
                    return res;
                }

                using (Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb))
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.DrawImage(image, 0, 0);
                    }

                    BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);

                    int* pt = (int*)data.Scan0;
                    int sz = data.Height * data.Width; //length of complete array
                    int stride = data.Stride; //bitmap stride ("scanline")
                    int cnt = stride / 4 + 1; //step for diagonal line (1 time "width_by_stride" + 1)

                    for (int i = 0; i < sz; i += cnt)
                    {

                        Color color = Color.FromArgb(pt[i]);
                        int colorRGBTotal = color.R + color.G + color.B;


                        if ((Math.Abs((colorRGBTotal / 3) - color.R) >= tolerance)
                            && (Math.Abs((colorRGBTotal / 3) - color.G) >= tolerance)
                            && (Math.Abs((colorRGBTotal / 3) - color.B) >= tolerance)
                            )
                        {

                            //string imageRGB = color.A + "|" + color.R + "|" + color.G + "|" + color.B + "|" + test +"|"+ imagePath;
                            //List<string> newLines = new List<string>();
                            //newLines.Add(imageRGB);
                            // File.AppendAllLines("C:\\test.txt", newLines);

                            res = false;
                            break;
                        }


                    }

                    bmp.UnlockBits(data);
                    bmp.Dispose();
                    image.Dispose();

                    return res;


                }


            }


        }
    }
    "@
    $cp =New-Object System.CodeDom.Compiler.CompilerParameters
    $cp = [System.CodeDom.Compiler.CompilerParameters]::new()
    $cp.ReferencedAssemblies.AddRange(('System.Windows.Forms.dll', 'System.Drawing.dll'))
    $cp.CompilerOptions = '/unsafe'
    Add-Type -TypeDefinition $cSharp -CompilerParameters $cp
    [isColor.CheckGrayScale]::Main()  

    ----------------------------code end--------------------------

    Monday, August 14, 2017 6:38 PM
  • The latest is 5.1

    You can't use both New-Object and new().  Use only one.


    \_(ツ)_/

    Monday, August 14, 2017 6:51 PM
  • i am installing but do you happen to know what is wrong with my C# script ? it compiles fine in VS but in PowerShell it's failing. I am a new bee i assume you figured.

    Monday, August 14, 2017 7:08 PM
  • It works fine for me:

    $cSharp = @'
     using System;
     using System.Drawing;
     using System.Drawing.Imaging;
     using System.Text;
    
     namespace  isColor
     { 
    
    
         public partial class CheckGrayScale
     { 
    
      
    
             public void Main()
             {
                 string imageColor = "";
    
                 int isBlackAndWhite;
                 string colorImaageDir = @"C:\Users\vinay\Documents\Images\IsColor";
                 string blackAndWhiteImageDir = @"CC:\Users\vinay\Documents\Images\IsBlackAndWhite";
                 // TODO: Add your code here
                 var imageName = "abcd.jpg";
                 var imagePath = @"C:\Users\vinay\Documents\Images\" + imageName;
                 //string imagePath = Dts.Variables["User::FileFullQName"].Value.ToString();
                 var response = IsBlackandWhiteImage(imagePath);
                 //var  imageColor = new List<string>();
    
                 //ImageMagickObject.MagickImage img = new ImageMagickObject.MagickImage();
                 //object[] args = new object[] { "-format", "%r", imagePath };
                 //object result = img.Identify(ref args);
    
    
                 if (response)
                 {
                     imageColor = "Black & White Image";
                     isBlackAndWhite = 1;
                     // System.IO.File.Move(imagePath, blackAndWhiteImageDir);
                 }
                 else
                 {
                     imageColor = "Color Image ";
                     isBlackAndWhite = 0;
                     //System.IO.File.Move(imagePath, colorImaageDir);
                 }
                 //MessageBox.Show(imageColor + imagePath);
    
                 //Dts.Variables["User::IsBlackAndWhite"].Value = isBlackAndWhite;
                 //  Dts.Variables["User::IsBlackAndWhite"].Value = ;
    
                 //ImageMagickNET.MagickNet.InitializeMagick();
                 //var image2 = new ImageMagickNET.Image(imagePath);
                 //image2.Resize(new ImageMagickNET.Geometry("10%"));
                 //image2.Write("Photo1.jpg");
    
    
                 ///Dts.TaskResult = (int)ScriptResults.Success;
             }
    
    
             public unsafe bool IsBlackandWhiteImage(string imagePath)
             {
    
    
    
                 Bitmap image = new Bitmap(imagePath);
    
                 var tolerance = 6;
    
                 string CamModel = "";
                 bool res = true;
                 try
                 {
                     PropertyItem[] props =
                     image.PropertyItems;
                     const int IDCamModel = 272;
                     PropertyItem Make = image.GetPropertyItem(IDCamModel);
                     Encoding ascii = Encoding.ASCII;
                     CamModel = ascii.GetString(
                        Make.Value, 0, Make.Len - 1);
                 }
                 catch
                 { }
    
    
    
                 if (CamModel != "")
                 {
                     image.Dispose();
                     res = false;
                     return res;
                 }
    
                 using (Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb))
                 {
                     using (Graphics g = Graphics.FromImage(bmp))
                     {
                         g.DrawImage(image, 0, 0);
                     }
    
                     BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);
    
                     int* pt = (int*)data.Scan0;
                     int sz = data.Height * data.Width; //length of complete array
                     int stride = data.Stride; //bitmap stride ("scanline")
                     int cnt = stride / 4 + 1; //step for diagonal line (1 time "width_by_stride" + 1)
    
                     for (int i = 0; i < sz; i += cnt)
                     {
    
                         Color color = Color.FromArgb(pt[i]);
                         int colorRGBTotal = color.R + color.G + color.B;
    
    
                         if ((Math.Abs((colorRGBTotal / 3) - color.R) >= tolerance)
                             && (Math.Abs((colorRGBTotal / 3) - color.G) >= tolerance)
                             && (Math.Abs((colorRGBTotal / 3) - color.B) >= tolerance)
                             )
                         {
    
                             //string imageRGB = color.A + "|" + color.R + "|" + color.G + "|" + color.B + "|" + test +"|"+ imagePath;
                             //List<string> newLines = new List<string>();
                             //newLines.Add(imageRGB);
                             // File.AppendAllLines("C:\\test.txt", newLines);
    
                             res = false;
                             break;
                         }
    
    
                     }
    
                     bmp.UnlockBits(data);
                     bmp.Dispose();
                     image.Dispose();
    
                     return res;
    
    
                 }
    
    
             }
    
    
         }
     }
    '@
    $cp = New-Object System.CodeDom.Compiler.CompilerParameters
    $cp.ReferencedAssemblies.AddRange(('System.Windows.Forms.dll', 'System.Drawing.dll'))
    $cp.CompilerOptions = '/unsafe'
    Add-Type -TypeDefinition $cSharp -CompilerParameters $cp
    [isColor.CheckGrayScale]

    #produces this output
    IsPublic IsSerial Name                                     BaseType
    -------- -------- ---- --------
    True     False    CheckGrayScale                           System.Object


    \_(ツ)_/

    Monday, August 14, 2017 7:13 PM
  • I think this is what you are trying to do:

    $cSharp = @'
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Text;
    
    namespace isColor{ 
    
    	public static unsafe class CheckGrayScale{ 
    
    		 public static bool IsBlackandWhiteImage(string imagePath){
    
    		     Bitmap image = new Bitmap(imagePath);
    		     var tolerance = 6;
    		     string CamModel = "";
    		     bool res = true;
    
    		     try{
    		         PropertyItem[] props = image.PropertyItems;
    		         const int IDCamModel = 272;
    		         PropertyItem Make = image.GetPropertyItem(IDCamModel);
    		         Encoding ascii = Encoding.ASCII;
    		         CamModel = ascii.GetString(Make.Value, 0, Make.Len - 1);
    		     }
    		     catch{
    		     }
    
    		    if(CamModel != ""){
    		         image.Dispose();
    		         res = false;
    		         return res;
    		     }
    
    		     using (Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb)){
    		         using (Graphics g = Graphics.FromImage(bmp)){
    		             g.DrawImage(image, 0, 0);
    		         }
    
    		         BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);
    
    		         int* pt = (int*)data.Scan0;
    		         int sz = data.Height * data.Width; //length of complete array
    		         int stride = data.Stride; //bitmap stride ("scanline")
    		         int cnt = stride / 4 + 1; //step for diagonal line (1 time "width_by_stride" + 1)
    
    		         for (int i = 0; i < sz; i += cnt){
    
    		             Color color = Color.FromArgb(pt[i]);
    		             int colorRGBTotal = color.R + color.G + color.B;
    
    		             if ((Math.Abs((colorRGBTotal / 3) - color.R) >= tolerance)
    		                 && (Math.Abs((colorRGBTotal / 3) - color.G) >= tolerance)
    		                 && (Math.Abs((colorRGBTotal / 3) - color.B) >= tolerance)
    		                 ){
    
    		                 res = false;
    		                 break;
    		             }
    		         }
    
    		         bmp.UnlockBits(data);
    		         bmp.Dispose();
    		         image.Dispose();
    
    		         return res;
    	    	}
    	 	}
    	}
    }
    '@
    $cp = New-Object System.CodeDom.Compiler.CompilerParameters
    $cp.ReferencedAssemblies.AddRange(('System.Windows.Forms.dll','System.Drawing.dll'))
    $cp.CompilerOptions = '/unsafe'
    Add-Type -TypeDefinition $cSharp -CompilerParameters $cp
    [isColor.CheckGrayScale]::IsBlackandWhiteImage('D:\eecons\crypto\eMedSenderCrypto\eMedSender1.ico')
    

    It works as expected  and runs as a static class.


    \_(ツ)_/


    • Edited by jrv Monday, August 14, 2017 8:57 PM
    Monday, August 14, 2017 8:55 PM
  • jrv, 

    Why i can't use main method. i want to try to move the files in Main()

      public static void Main()
            {
                string imageColor = "";

                int isBlackAndWhite;
                string colorImageDir = @"C:\Images\IsColor";
                string blackAndWhiteImageDir = @"C:\Images\IsBlackAndWhite";
                // TODO: Add your code here
                var imageName = "test123.jpg";
                var imagePath = @"C:\Images\" + imageName;
                //string imagePath = Dts.Variables["User::FileFullQName"].Value.ToString();
                var response = IsBlackandWhiteImage(imagePath);
                //var  imageColor = new List<string>();

                //ImageMagickObject.MagickImage img = new ImageMagickObject.MagickImage();
                //object[] args = new object[] { "-format", "%r", imagePath };
                //object result = img.Identify(ref args);
                FileInfo fileinfo = new FileInfo(Path.Combine(imagePath));

                if (response)
                {
                    imageColor = "Black & White Image";
                    isBlackAndWhite = 1;
                    fileinfo.MoveTo(Path.Combine(blackAndWhiteImageDir, imageName));
                }
                else
                {
                    imageColor = "Color Image ";
                    isBlackAndWhite = 0;
                    fileinfo.MoveTo(Path.Combine(colorImageDir, imageName));
                }

            }

        

    Monday, August 14, 2017 11:40 PM
  • Use PowerShell to move the files.  All you need is to test then for B&W then move them.  It doesn't have to be done in C#.


    \_(ツ)_/

    Monday, August 14, 2017 11:54 PM
  • Jrv,

    My requirement is to loop through file and all within the c# code. Is it possible to use the main Method  ? what would be the best place to plug it ? i tried right after    public static unsafe class CheckGrayScale but  i am getting message  OverloadDefinitions static void Main() and it does nothing.

    $cSharp = @'
    using System;
    using System.IO;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Text;
    
    namespace isColor
    {
    
    
        public static unsafe class CheckGrayScale
        {
    
            public static void Main()
            {
                string imageColor = "";
    
                int isBlackAndWhite;
                string colorImageDir = @"C:\Images\IsColor";
                string blackAndWhiteImageDir = @"C:\Images\IsBlackAndWhite";
                // TODO: Add your code here
                var imageName = "test123.jpg";
                var imagePath = @"C:\Images\" + imageName;
                //string imagePath = Dts.Variables["User::FileFullQName"].Value.ToString();
                var response = IsBlackandWhiteImage(imagePath);
                //var  imageColor = new List<string>();
    
                //ImageMagickObject.MagickImage img = new ImageMagickObject.MagickImage();
                //object[] args = new object[] { "-format", "%r", imagePath };
                //object result = img.Identify(ref args);
                FileInfo fileinfo = new FileInfo(Path.Combine(imagePath));
    
                if (response)
                {
                    imageColor = "Black & White Image";
                    isBlackAndWhite = 1;
                    fileinfo.MoveTo(Path.Combine(blackAndWhiteImageDir, imageName));
                }
                else
                {
                    imageColor = "Color Image ";
                    isBlackAndWhite = 0;
                    fileinfo.MoveTo(Path.Combine(colorImageDir, imageName));
                }
    
            }
    
        
    
    
    
            public static bool IsBlackandWhiteImage(string imagePath)
            {
    
                Bitmap image = new Bitmap(imagePath);
                var tolerance = 6;
                string CamModel = "";
                bool res = true;
    
                try
                {
                    PropertyItem[] props = image.PropertyItems;
                    const int IDCamModel = 272;
                    PropertyItem Make = image.GetPropertyItem(IDCamModel);
                    Encoding ascii = Encoding.ASCII;
                    CamModel = ascii.GetString(Make.Value, 0, Make.Len - 1);
                }
                catch
                {
                }
    
                if (CamModel != "")
                {
                    image.Dispose();
                    res = false;
                    return res;
                }
    
                using (Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb))
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.DrawImage(image, 0, 0);
                    }
    
                    BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);
    
                    int* pt = (int*)data.Scan0;
                    int sz = data.Height * data.Width; //length of complete array
                    int stride = data.Stride; //bitmap stride ("scanline")
                    int cnt = stride / 4 + 1; //step for diagonal line (1 time "width_by_stride" + 1)
    
                    for (int i = 0; i < sz; i += cnt)
                    {
    
                        Color color = Color.FromArgb(pt[i]);
                        int colorRGBTotal = color.R + color.G + color.B;
    
                        if ((Math.Abs((colorRGBTotal / 3) - color.R) >= tolerance)
                            && (Math.Abs((colorRGBTotal / 3) - color.G) >= tolerance)
                            && (Math.Abs((colorRGBTotal / 3) - color.B) >= tolerance)
                            )
                        {
    
                            res = false;
                            break;
                        }
                    }
    
                    bmp.UnlockBits(data);
                    bmp.Dispose();
                    image.Dispose();
    
                    return res;
                }
            }
        }
    }
    '@
    $cp = New-Object System.CodeDom.Compiler.CompilerParameters
    $cp.ReferencedAssemblies.AddRange(('System.Windows.Forms.dll','System.Drawing.dll'))
    $cp.CompilerOptions = '/unsafe'
    Add-Type -TypeDefinition $cSharp -CompilerParameters $cp
    [isColor.CheckGrayScale]::Main


    • Marked as answer by DC_010 Tuesday, August 15, 2017 7:31 PM
    Tuesday, August 15, 2017 1:09 AM
  • Sorry but I cannot help your lack of programming and program design issues.  This is not a C# forum.  If you are trying to create a C# application that solves your problem you will have to post in a C# forum.

    I have shown you how to do this in PowerShell.  C# forms partial classes cannot be used as types in PowerShell and PowerShell is not a system that is useful for creating Forms code.  You will have to learn C# development and learn how to use Visual studio to create you application.

    Post your issues for building C# applications in the C# developers forum.  They will help you to learn code development.  This is a PowerShell scripting forum. Helping you with C# compiles is outside of the scope of this forum.


    \_(ツ)_/

    Tuesday, August 15, 2017 1:31 AM
  • Thank you I'll look in to what i should do.  Thank you for all your assistance else i would have never made it.

    Tuesday, August 15, 2017 7:32 PM