System.Math.Abs(int)

Here are the examples of the csharp api System.Math.Abs(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1889 Examples 7

19 Source : ImageUtils.cs
with MIT License
from azist

public static unsafe Color[] ExtractMainColors(Image srcImg,
                                                   int resizeWidth = 64, int resizeHeight = 64,
                                                   int dwnFactor1 = 128, int dwnFactor2 = 24,
                                                   float interiorPct = 0.9F)
    {
      var interiorWidth  = interiorPct * resizeWidth;
      var interiorHeight = interiorPct * resizeHeight;
      var mainHist = new Dictionary<Color, int>();
      var backHist = new Dictionary<Color, int>();

      // STEP 1: resize image
      using (var rszImg = srcImg.ResizeTo(resizeWidth, resizeHeight))
      using (var maskImg = Image.Of(resizeWidth, resizeHeight, rszImg.XResolution, rszImg.YResolution, rszImg.PixelFormat))
      {
        // STEP 2: extract downgraded (very few colors) - color histogram (main and background)
        // IMPORTANT: these colors will be used below not as itself but only AS A MASK
        for (int x=0; x<resizeWidth; x++)
        for (int y=0; y<resizeHeight; y++)
        {
          var p = rszImg.GetPixel(x, y);

          var a = p.A - p.A%dwnFactor1;
          var r = p.R - p.R%dwnFactor1;
          var g = p.G - p.G%dwnFactor1;
          var b = p.B - p.B%dwnFactor1;
          var color = Color.FromArgb(a, r, g, b);

          // histogram for a main color
          if (!mainHist.ContainsKey(color)) mainHist[color] = 1;
          else mainHist[color] += 1;

          // histogram for a background color
          if (Math.Abs(2 * x - resizeWidth) >= interiorWidth ||
              Math.Abs(2 * y - resizeHeight) >= interiorHeight)
          {
            if (!backHist.ContainsKey(color)) backHist[color] = 1;
            else backHist[color] += 1;
          }

          maskImg.SetPixel(x, y, color);
        }

        // take background area color and the first three colors (i.e. main image areas) except background
        var backArea = backHist.FirstMax(h => h.Value).Key;
        var areas = mainHist.Where(h => h.Key != backArea).OrderByDescending(h => h.Value).Take(3).ToList();
        var firstArea  = (areas.Count > 0) ? areas[0].Key : backArea;
        var secondArea = (areas.Count > 1) ? areas[1].Key : firstArea;
        var thirdArea  = (areas.Count > 2) ? areas[2].Key : secondArea;

        // get histogram for background area each of three main areas
        if (ts_FirstHist==null)  ts_FirstHist=new Dictionary<Color, int>();  else ts_FirstHist.Clear();
        if (ts_SecondHist==null) ts_SecondHist=new Dictionary<Color, int>(); else ts_SecondHist.Clear();
        if (ts_ThirdHist==null)  ts_ThirdHist=new Dictionary<Color, int>();  else ts_ThirdHist.Clear();
        if (ts_BckHist==null)    ts_BckHist=new Dictionary<Color, int>();    else ts_BckHist.Clear();

        // STEP 3: fill color (1,2,3+background) histograms
        for (int x=0; x<resizeWidth; x++)
        for (int y=0; y<resizeHeight; y++)
        {
          // fetch histogram by a mask
          var maskP = maskImg.GetPixel(x, y);
          Dictionary<Color, int> h;
          if (maskP == firstArea)       h = ts_FirstHist;
          else if (maskP == secondArea) h = ts_SecondHist;
          else if (maskP == thirdArea)  h = ts_ThirdHist;
          else if (maskP == backArea)   h = ts_BckHist;
          else continue;

          var p = rszImg.GetPixel(x, y);
          var a = p.A - p.A%dwnFactor2;
          var r = p.R - p.R%dwnFactor2;
          var g = p.G - p.G%dwnFactor2;
          var b = p.B - p.B%dwnFactor2;
          var color = Color.FromArgb(a, r, g, b);

          if (!h.ContainsKey(color)) h[color] = 1;
          else h[color] += 1;
        }

        // STEP 4: extract color for each histogram
        var firstHist  = ts_FirstHist;
        var secondHist = (ts_SecondHist.Count > 0) ? ts_SecondHist : firstHist;
        var thirdHist  = (ts_ThirdHist.Count > 0) ? ts_ThirdHist : secondHist;
        var bckHist    = (ts_BckHist.Count > 0) ? ts_BckHist : thirdHist;
        var topColors = new[]
        {
          colorFromHist(firstHist),
          colorFromHist(secondHist),
          colorFromHist(thirdHist),
          colorFromHist(bckHist)
        };

        return topColors;
      }
    }

19 Source : ImageUtils.cs
with MIT License
from azist

private static float colorsAbsDist(Color c1, Color c2)
    {
      var d = Math.Abs(c1.R - c2.R) + Math.Abs(c1.G - c2.G) + Math.Abs(c1.B - c2.B);
      return d / 256.0F;
    }

19 Source : JsonWriter.cs
with MIT License
from azist

public static void EncodeDateTime(TextWriter wri, DateTime data, JsonWritingOptions opt = null, TimeSpan? utcOffset = null)
        {
            if (opt==null) opt = JsonWritingOptions.Compact;

            if (!opt.ISODates)
            {
                wri.Write("new Date({0})".Args( data.ToMillisecondsSinceUnixEpochStart() ));
                return;
            }

            wri.Write('"');
            var year = data.Year;
            if (year>999) wri.Write(year);
            else if (year>99) { wri.Write('0'); wri.Write(year); }
            else if (year>9) { wri.Write("00"); wri.Write(year); }
            else if (year>0) { wri.Write("000"); wri.Write(year); }

            wri.Write('-');

            var month = data.Month;
            if (month>9) wri.Write(month);
            else { wri.Write('0'); wri.Write(month); }

            wri.Write('-');

            var day = data.Day;
            if (day>9) wri.Write(day);
            else { wri.Write('0'); wri.Write(day); }

            wri.Write('T');

            var hour = data.Hour;
            if (hour>9) wri.Write(hour);
            else { wri.Write('0'); wri.Write(hour); }

            wri.Write(':');

            var minute = data.Minute;
            if (minute>9) wri.Write(minute);
            else { wri.Write('0'); wri.Write(minute); }

            wri.Write(':');

            var second = data.Second;
            if (second>9) wri.Write(second);
            else { wri.Write('0'); wri.Write(second); }

            var ms = data.Millisecond;
            if (ms>0)
            {
              wri.Write('.');

              if (ms>99) wri.Write(ms);
              else if (ms>9) { wri.Write('0'); wri.Write(ms); }
              else { wri.Write("00"); wri.Write(ms); }
            }

            if (data.Kind==DateTimeKind.Utc)
              wri.Write('Z');
            else
            {
              var offset = utcOffset==null ? TimeZoneInfo.Local.GetUtcOffset(data) : utcOffset.Value;

              wri.Write( offset.Ticks<0 ? '-' : '+' );

              hour = Math.Abs(offset.Hours);
              if (hour>9) wri.Write(hour);
              else { wri.Write('0'); wri.Write(hour); }

              wri.Write(':');

              minute = Math.Abs(offset.Minutes);
              if (minute>9) wri.Write(minute);
              else { wri.Write('0'); wri.Write(minute); }
            }


            wri.Write('"');
        }

19 Source : TemplateCompiler.cs
with MIT License
from azist

public string GenerateUniqueName()
         {
           while(true)
           {
             var name = string.Format("id_{0}_template_{1}", m_Rnd.Next(100000), Math.Abs(this.GetType().FullName.GetHashCode() % 1000));
             if (!m_UniqueNames.Contains(name))
             {
               m_UniqueNames.Add(name);
               return name;
             }
           }
         }

19 Source : TextCSTemplateCompiler.cs
with MIT License
from azist

internal FSM Build()
              {
                if (Result!=null) return this;
                Result = new StringBuilder();

                var cnode = ConfigNode[CONFIG_COMPILER_SECTION];

                ClreplacedName = cnode.AttrByName(CONFIG_CLreplaced_NAME_ATTR).Valuereplacedtring(InferredClreplacedName);
                if (string.IsNullOrWhiteSpace(ClreplacedName)) ClreplacedName = Compiler.BaseTypeName;
                if (string.IsNullOrWhiteSpace(ClreplacedName)) ClreplacedName = Compiler.GenerateUniqueName();

                ClreplacedDeclaration = cnode.AttrByName(CONFIG_CLreplaced_DECLARATION_ATTR).Valuereplacedtring(ClreplacedName);
                if (string.IsNullOrWhiteSpace(ClreplacedDeclaration)) ClreplacedDeclaration = ClreplacedName;

                ClreplacedConstraint = cnode.AttrByName(CONFIG_CLreplaced_CONSTRAINT_ATTR).Value;


                ClreplacedID = Math.Abs(ClreplacedName.GetHashCode() % 100);

                Namespace = cnode.AttrByName(CONFIG_NAMESPACE_ATTR).Value;
                if (string.IsNullOrWhiteSpace(Namespace)) Namespace = Compiler.Namespace;
                if (string.IsNullOrWhiteSpace(Namespace)) Namespace = Compiler.GenerateUniqueName();


                Unit.CompiledTemplateTypeName = "{0}.{1}".Args( Namespace, ClreplacedName);


                BaseClreplacedName = cnode.AttrByName(CONFIG_BASE_CLreplaced_NAME_ATTR).Valuereplacedtring(Compiler.BaseTypeName);
                if (string.IsNullOrWhiteSpace(BaseClreplacedName)) BaseClreplacedName = DEFAULT_BASE_TEMPLATE_CLreplaced_NAME;

                Abstract = cnode.AttrByName(CONFIG_ABSTRACT_ATTR).ValueAsBool(false);

                BaseRender = cnode.AttrByName(CONFIG_BASE_RENDER_ATTR).ValueAsBool(true);

                Summary = cnode.AttrByName(CONFIG_SUMMARY_ATTR).Valuereplacedtring("Auto-generated from template");

                Areas.Add(RENDER_AREA, Code);
                Areas.Add(CLreplaced_AREA, new StringBuilder());


                Idx = 0;
                while(Idx<Source.Length)
                {
                    var s = this[Idx, 2];

                    if (s==AREA_ESCAPE || s==STATEMENT_ESCAPE || s==EXPRESSION_ESCAPE)
                    {
                     Idx++;
                    }else
                    if (s==STATEMENT)
                    {
                      flushLiteral();
                      Idx+=STATEMENT.Length;
                      var statement = readSpan();
                      Code.Append("      ");
                      Code.AppendLine(statement);
                    }else
                    if (s==EXPRESSION)
                    {
                      flushLiteral();
                      Idx+=EXPRESSION.Length;
                      var expression = readSpan();

                      if (expression.EndsWith(";"))
                       expression = expression.Remove(expression.Length-1);

                      if (expression.Length==0)
                       throw new TemplateParseException(string.Format(StringConsts.TEMPLATE_CS_COMPILER_EMPTY_EXPRESSION_ERROR, LineNo));

                      if (expression.StartsWith(VERBATIM))
                      {
                        expression = expression.Substring(1);
                        Code.AppendFormat("        Target.Write( {0} );\n", expression);
                      }
                      else
                        Code.AppendFormat("        Target.Write(Target.Encode( {0} ));\n", expression);
                    }else
                    if (s==AREA)
                    {
                      flushLiteral();
                      Idx+=AREA.Length;
                      var area = readSpan();
                      if (!Areas.ContainsKey(area))
                      {
                        Code = new StringBuilder();
                        Areas.Add(area, Code);
                      }
                       else
                      {
                        Code = Areas[area];
                      }
                    }

                    if (Idx<Source.Length)//20141010 DKH fixed tail span [] bug
                    {
                     Literal.Append(getch());
                     Idx++;
                    }
                }//while

                flushLiteral();


                Result.AppendFormat("//WARNING: This code was auto generated by template compiler, do not modify by hand!\n");
                Result.AppendFormat("//Generated on {0} by {1} at {2}\n", Ambient.UTCNow.ToLocalTime(), Compiler.GetType().FullName, System.Environment.MachineName);
                Result.AppendLine();
                foreach(var us in Usings)
                  Result.AppendFormat("using {0}; \n", us);
                Result.AppendLine();
                Result.AppendFormat("namespace {0} \n", Namespace);
                Result.AppendLine  ("{");
                Result.AppendLine();
                Result.AppendLine  (" ///<summary>");
                Result.AppendLine  (" /// "+Summary);
                Result.AppendLine  (" ///</summary>");
                if (Attributes.Count>0)
                  foreach(var attr in Attributes)
                    Result.AppendFormat(" [{0}] \n", attr);
                Result.AppendFormat(" public {0} clreplaced {1} : {2} {3}\n", Abstract ? "abstract":string.Empty, ClreplacedDeclaration, BaseClreplacedName, ClreplacedConstraint);
                Result.AppendLine  (" {");
                Result.AppendLine(Areas[CLreplaced_AREA].ToString());

                Result.AppendLine("     protected override void DoRender()");
                Result.AppendLine("     {");

                if (BaseRender)
                 Result.AppendLine("       base.DoRender();");

                if (Areas.ContainsKey(RENDER_AREA))
                 Result.AppendLine(Areas[RENDER_AREA].ToString());

                Result.AppendLine("     }");

                foreach(var ark in Areas.Keys.Where(k=> k!=CLreplaced_AREA && k!=RENDER_AREA))
                {
                    var over = ark.StartsWith(OVERRIDE);
                    if (over)
                      Result.AppendLine("    protected override void " + ark.Remove(0, OVERRIDE.Length));
                    else
                    {
                      var virt = ark.StartsWith(VIRTUAL);
                      if (virt)
                        Result.AppendLine("    protected virtual void " + ark.Remove(0, VIRTUAL.Length));
                      else
                        Result.AppendLine("    protected void " + ark);
                    }
                    Result.AppendLine("    {");
                    Result.AppendLine(Areas[ark].ToString());
                    Result.AppendLine("    }");
                }

                Result.AppendLine();
                Result.AppendLine();
                Result.AppendLine("     #region Literal blocks content");
                foreach(var block in LiteralBlocks)
                {
                  Result.AppendFormat("        private const string {0} = @\"{1}\"; \n", block.Key, block.Value.Replace("\"","\"\""));
                }
                Result.AppendLine("     #endregion");
                Result.AppendLine();
                Result.AppendLine(" }//clreplaced");

                Result.AppendLine("}//namespace");

                return this;
              }

19 Source : NaturalTextGenerator.cs
with MIT License
from azist

public static string GenerateAddressLine()
    {
      var streetNumber = rndi(1, 10000);

      var rnd = rndi();

      string street;

      if (rnd % 3==0) street = GenerateFirstName();
      else
      if (rnd % 2==0) street = GenerateLastName();
      else
       street = GenerateCityName();

      if (rnd > 0)
       street +=  STREET_SUFFIXES[(0x7fFFFFFF & rndi()) % STREET_SUFFIXES.Length];

      var rnd2 = rndi();

      if (rnd2 % 7==0) street += " apt #"+Math.Abs(rnd2 % 18).ToString()+(char)('A'+(rnd2 & 0x8));
      else
      if (rnd2 % 5==0) street += " apt. "+Math.Abs(rnd2 % 18).ToString()+(char)('a'+(rnd2 & 0x8));
      else
      if (rnd2 % 4==0) street += " suite "+Math.Abs(rnd2 % 180).ToString();
      else
      if (rnd2 % 3==0) street += " room "+Math.Abs(rnd2 % 180).ToString();

      return "{0} {1}".Args(streetNumber, street);
    }

19 Source : NaturalTextGenerator.cs
with MIT License
from azist

public static string GenerateEMail()
    {
       var rnd = rndi();
       string domain;

       var user = GenerateFirstName();
       if (rnd%5==0) user += "."+GenerateLastName();
       if (rnd%7==0) user += (1900+Math.Abs(rnd%115)).ToString();

       if (rnd<-1500000000)
        domain = DOMAIN_NAMES[(0x7fFFFFFF & rndi()) % DOMAIN_NAMES.Length];
       else
       {
         if (rnd%3==0 && user.Length<11)
           domain = GenerateWord()+"."+GenerateCityName()+TLD_NAMES[(0x7fFFFFFF & rndi()) % TLD_NAMES.Length];
         else
           domain = GenerateWord(8)+TLD_NAMES[(0x7fFFFFFF & rndi()) % TLD_NAMES.Length];
       }

       var rnd2 = rndi();

       if (user.Length<5 && rnd2%17!=0) user += Math.Abs(rnd%99).ToString();

       if (rnd2<1700000000) user = user.ToLowerInvariant();

       return (user+"@"+domain.ToLowerInvariant()).Replace('\'','.').Replace(' ', '.');
    }

19 Source : ImageUtils.cs
with MIT License
from azist

public static unsafe Color[] ExtractMainColors(Bitmap srcBmp,
                                                   int dwnFactor1=128, int dwnFactor2=24,
                                                   float interiorPct=0.9F)
    {
      var height   = srcBmp.Height;
      var width    = srcBmp.Width;
      var mainHist = new Dictionary<Color, int>();
      var backHist = new Dictionary<Color, int>();

      using (var dwnBmp = new Bitmap(width, height))
      {
        BitmapData srcData = null;
        BitmapData dwnData = null;

        try
        {
          // extract downgraded (very few colors) color histogramm
          srcData = srcBmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, srcBmp.PixelFormat);
          int srcBytesPerPixel  = Bitmap.GetPixelFormatSize(srcBmp.PixelFormat) / 8;
          int srcHeightInPixels = srcData.Height;
          int srcWidthInBytes   = srcData.Width * srcBytesPerPixel;
          byte* srcFirstPixel   = (byte*)srcData.Scan0;

          dwnData = dwnBmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, dwnBmp.PixelFormat);
          int dwnBytesPerPixel  = Bitmap.GetPixelFormatSize(dwnBmp.PixelFormat) / 8;
          int dwnHeightInPixels = dwnData.Height;
          int dwnWidthInBytes   = dwnData.Width * dwnBytesPerPixel;
          byte* dwnFirstPixel   = (byte*)dwnData.Scan0;

          for (int y=0; y<height; y++)
          {
            byte* srcLine = srcFirstPixel + (y*srcData.Stride);
            byte* dwnLine = dwnFirstPixel + (y*dwnData.Stride);
            for (int x=0; x<srcWidthInBytes; x += srcBytesPerPixel)
            {
              var b = dwnFactor1*(srcLine[x]/dwnFactor1);
              var g = dwnFactor1*(srcLine[x+1]/dwnFactor1);
              var r = dwnFactor1*(srcLine[x+2]/dwnFactor1);
              var color = Color.FromArgb(r, g, b);

              // histogramm for main color
              if (!mainHist.ContainsKey(color)) mainHist[color] = 1;
              else mainHist[color] += 1;

              // histogramm for background color
              if (Math.Abs(2*x-srcWidthInBytes)>=interiorPct*srcWidthInBytes || Math.Abs(2*y-height)>=interiorPct*height)
              {
                if (!backHist.ContainsKey(color)) backHist[color] = 1;
                else backHist[color] += 1;
              }

              dwnLine[x]   = (byte)b;
              dwnLine[x+1] = (byte)g;
              dwnLine[x+2] = (byte)r;
            }
          }

          // take background area color and the first three colors (i.e. main image areas) except background
          var backArea = backHist.OrderByDescending(h => h.Value).First().Key;
          var areas = mainHist.Where(h => h.Key != backArea).OrderByDescending(h => h.Value).Take(3).ToList();
          var firstArea  = (areas.Count > 0) ? areas[0].Key : backArea;
          var secondArea = (areas.Count > 1) ? areas[1].Key : firstArea;
          var thirdArea  = (areas.Count > 2) ? areas[2].Key : secondArea;

          // get histogramm for background area each of three main areas
          if (ts_FirstHist==null)  ts_FirstHist=new Dictionary<Color, int>();  else ts_FirstHist.Clear();
          if (ts_SecondHist==null) ts_SecondHist=new Dictionary<Color, int>(); else ts_SecondHist.Clear();
          if (ts_ThirdHist==null)  ts_ThirdHist=new Dictionary<Color, int>();  else ts_ThirdHist.Clear();
          if (ts_BckHist==null)    ts_BckHist=new Dictionary<Color, int>();    else ts_BckHist.Clear();

          for (int y=0; y<height; y++)
          {
            byte* srcLine = srcFirstPixel + (y*srcData.Stride);
            byte* dwnLine = dwnFirstPixel + (y*dwnData.Stride);
            for (int x=0; x<srcWidthInBytes; x += srcBytesPerPixel)
            {
              var b = dwnLine[x];
              var g = dwnLine[x+1];
              var r = dwnLine[x+2];
              var color = Color.FromArgb(r, g, b);
              Dictionary<Color, int> h;
              if      (color==firstArea)  h = ts_FirstHist;
              else if (color==secondArea) h = ts_SecondHist;
              else if (color==thirdArea)  h = ts_ThirdHist;
              else if (color==backArea)   h = ts_BckHist;
              else continue;

              b = (byte)(dwnFactor2*(srcLine[x]/dwnFactor2));
              g = (byte)(dwnFactor2*(srcLine[x+1]/dwnFactor2));
              r = (byte)(dwnFactor2*(srcLine[x+2]/dwnFactor2));
              color = Color.FromArgb(r, g, b);
              if (!h.ContainsKey(color)) h[color] = 1;
              else h[color] += 1;
            }
          }
        }
        finally
        {
          if (srcData != null) srcBmp.UnlockBits(srcData);
          if (dwnBmp != null)  dwnBmp.UnlockBits(dwnData);
        }

        // extract color for each histogram
        var firstHist  = ts_FirstHist;
        var secondHist = (ts_SecondHist.Count>0) ? ts_SecondHist : firstHist;
        var thirdHist  = (ts_ThirdHist.Count>0) ? ts_ThirdHist : secondHist;
        var bckHist    = (ts_BckHist.Count>0) ? ts_BckHist : thirdHist;
        var topColors = new[]
        {
          colorFromHist(firstHist),
          colorFromHist(secondHist),
          colorFromHist(thirdHist),
          colorFromHist(bckHist)
        };

        return topColors;
      }
    }

19 Source : ImageUtils.cs
with MIT License
from azist

private static float imagesAbsDist(Color c1, Color c2)
    {
      var d = Math.Abs(c1.R-c2.R) + Math.Abs(c1.G-c2.G) + Math.Abs(c1.B-c2.B);
      return d / 256.0F;
    }

19 Source : SerializerForm2.cs
with MIT License
from azist

private void btnABsSpeed_Click(object sender, EventArgs e)
          {
             System.Threading.Thread.SpinWait(100000000);
             const int CNT = 100000000;
             var sw = Stopwatch.StartNew();

             long sum = 0;
             for(var i=0; i<CNT; i++)
               sum += (Math.Abs(i) % 3);

             var t1 = sw.ElapsedMilliseconds;
             sw.Restart();

             long sum2 = 0;
             for(var i=0; i<CNT; i++)
               sum2 += ((i & 0x7fffffff) % 3);

             var t2 = sw.ElapsedMilliseconds;
             sw.Restart();

             long sum3 = 0;
             for(var i=0; i<CNT; i++)
               sum3 += ((i < 0? -i : i) % 3);
             var t3 = sw.ElapsedMilliseconds;

             var msg =
@"
Did {0}:
--------------------------------------
Math.Abs() {1:n0} ms at @ {2:n0} ops/sec
Bit &&     {3:n0} ms at @ {4:n0} ops/sec
IF         {5:n0} ms at @ {6:n0} ops/sec".Args(CNT,
                  t1, CNT / (t1 / 1000d),
                  t2, CNT / (t2 / 1000d),
                  t3, CNT / (t3 / 1000d)  );

            MessageBox.Show( msg );

          }

19 Source : Effect.cs
with MIT License
from b-editor

public static void Diffusion(this Image<BGRA32> image, byte value)
        {
            if (image is null) throw new ArgumentNullException(nameof(image));
            image.ThrowIfDisposed();
            value = Math.Clamp(value, (byte)0, (byte)30);

            fixed (BGRA32* data = image.Data)
            {
                var raw = (IntPtr)data;
                var rand = new Random();

                Parallel.For(0, image.Height, y =>
                {
                    Parallel.For(0, image.Width, x =>
                    {
                        var data = (BGRA32*)raw;

                        // 取得する座標
                        var dy = Math.Abs(y + rand.Next(-value, value));
                        var dx = Math.Abs(x + rand.Next(-value, value));
                        int sPos;
                        var dPos = (y * image.Width) + x;

                        // 範囲外はデフォルトの値を使用する
                        if ((dy >= image.Height - 1) || (dx >= image.Width - 1))
                        {
                            sPos = dPos;
                        }
                        else
                        {
                            var sRow = dy * image.Width;
                            sPos = sRow + dx;
                        }

                        data[dPos].R = data[sPos].R;
                        data[dPos].G = data[sPos].G;
                        data[dPos].B = data[sPos].B;
                    });
                });
            }
        }

19 Source : Effect.cs
with MIT License
from b-editor

public static Image<BGRA32> FlatShadow(this Image<BGRA32> image, Color color, float angle, float length)
        {
            using var alphamap = image.AlphaMap();
            using var alphaMat = alphamap.ToMat();

            // 輪郭検出
            alphaMat.FindContours(out var points, out var h, RetrievalModes.List, ContourApproximationModes.ApproxSimple);

            var dgree = angle;
            var radian = dgree * (MathF.PI / 180);
            var x1 = MathF.Cos(radian);
            var y1 = MathF.Sin(radian);
            var x2 = (int)(length * MathF.Cos(radian));
            var y2 = (int)(length * MathF.Sin(radian));
            var x2Abs = Math.Abs(x2);
            var y2Abs = Math.Abs(y2);

            using var bmp = new SKBitmap(new SKImageInfo(image.Width + x2Abs, image.Height + y2Abs, SKColorType.Bgra8888));
            using var canvas = new SKCanvas(bmp);
            using var paint = new SKPaint
            {
                Color = new SKColor(color.R, color.G, color.B, color.A),
                IsAntialias = true,
                Style = SKPaintStyle.Fill,
            };

            foreach (var p in points)
            {
                canvas.Translate((x2Abs - x2) / 2, (y2Abs - y2) / 2);

                using var path = new SKPath();

                path.MoveTo(p[0].X, p[0].Y);

                for (var i = 0; i < p.Length; i++)
                {
                    var item = p[i];
                    path.LineTo(item.X, item.Y);
                }

                for (var i = 0; i < length; i++)
                {
                    canvas.Translate(x1, y1);
                    canvas.DrawPath(path, paint);
                }

                canvas.ResetMatrix();
            }

            using var srcBmp = image.ToSKBitmap();
            canvas.DrawBitmap(srcBmp, (x2Abs - x2) / 2, (y2Abs - y2) / 2);

            return bmp.ToImage32();
        }

19 Source : ImageGenerator.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static void Create(byte[] payload, string image, string outputfile)
        {
            try
            {
                Bitmap img = new Bitmap(image);

                int width = img.Size.Width;
                int height = img.Size.Height;

                //Lock the bitmap in memory so it can be changed programmatically.
                Rectangle rect = new Rectangle(0, 0, width, height);
                BitmapData bmpData = img.LockBits(rect, ImageLockMode.ReadWrite, img.PixelFormat);
                IntPtr ptr = bmpData.Scan0;

                // Copy the RGB values to an array for easy modification
                int bytes = Math.Abs(bmpData.Stride) * img.Height;
                byte[] rgbValues = new byte[bytes];
                Marshal.Copy(ptr, rgbValues, 0, bytes);

                //Check that the payload fits in the image 
                if (bytes / 2 < payload.Length)
                {
                    Console.Write("Image not large enough to contain payload!");
                    img.UnlockBits(bmpData);
                    img.Dispose();
                    return;
                }

                //Generate a random string to use to fill other pixel info in the picture.
                string randstr = RandomString(128);
                byte[] randb = Encoding.ASCII.GetBytes(randstr);

                //loop through the RGB array and copy the payload into it
                for (int counter = 0; counter < (rgbValues.Length) / 3; counter++)
                {
                    int paybyte1;
                    int paybyte2;
                    int paybyte3;
                    if (counter < payload.Length)
                    {
                        paybyte1 = (int)Math.Floor((decimal)(payload[counter] / 16));
                        paybyte2 = (payload[counter] & 0x0f);
                        paybyte3 = (randb[(counter + 2) % 109] & 0x0f);
                    }
                    else
                    {
                        paybyte1 = (randb[counter % 113] & 0x0f);
                        paybyte2 = (randb[(counter + 1) % 67] & 0x0f);
                        paybyte3 = (randb[(counter + 2) % 109] & 0x0f);
                    }
                    rgbValues[(counter * 3)] = (byte)((rgbValues[(counter * 3)] & 0xf0) | paybyte1);
                    rgbValues[(counter * 3 + 1)] = (byte)((rgbValues[(counter * 3 + 1)] & 0xf0) | paybyte2);
                    rgbValues[(counter * 3 + 2)] = (byte)((rgbValues[(counter * 3 + 2)] & 0xf0) | paybyte3);
                }

                //Copy the array of RGB values back to the bitmap
                Marshal.Copy(rgbValues, 0, ptr, bytes);
                img.UnlockBits(bmpData);

                //Write the image to a file
                img.Save(outputfile, ImageFormat.Png);
                img.Dispose();

                //Console.WriteLine("[*] Image file created {0}", outputfile);

            }
            catch (Exception e)
            {
                Console.WriteLine("[x] error: " + e.Message);
                Console.WriteLine("[x] file : " + image);
                Console.WriteLine("[x] error: " + e.StackTrace);
            }
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

static void Main(string[] args)
        {
            string replacedemblypath = "";
            string image = "";
            string outputfile = "";
            bool showHelp = false;
            
            var p = new OptionSet() {
                { "a|replacedembly=", "replacedembly to hide.\n", v => replacedemblypath = v },
                { "i|image=", "Image src.", v => image = v },
                { "o|output=", "Output file", v => outputfile = v },
                { "h|help",  "Show this message and exit.", v => showHelp = v != null },
            };

            try
            {
                try
                {
                    p.Parse(args);
                }
                catch (OptionException e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine("Try '--help' for more information.");
                    return;
                }

                if (showHelp)
                {
                    ShowHelp(p);
                    return;
                }

                //Payload to work
                byte[] payload = File.ReadAllBytes(replacedemblypath);

                Bitmap img = new Bitmap(image);

                int width = img.Size.Width;
                int height = img.Size.Height;

                //Lock the bitmap in memory so it can be changed programmatically.
                Rectangle rect = new Rectangle(0, 0, width, height);
                BitmapData bmpData = img.LockBits(rect, ImageLockMode.ReadWrite, img.PixelFormat);
                IntPtr ptr = bmpData.Scan0;

                // Copy the RGB values to an array for easy modification
                int bytes = Math.Abs(bmpData.Stride) * img.Height;
                byte[] rgbValues = new byte[bytes];
                Marshal.Copy(ptr, rgbValues, 0, bytes);

                //Check that the payload fits in the image 
                if(bytes/2 < payload.Length) {
                    Console.Write("Image not large enough to contain payload!");
                    img.UnlockBits(bmpData);
                    img.Dispose();
                    return;
                }

                //Generate a random string to use to fill other pixel info in the picture.
                string randstr = RandomString(128);
                byte[] randb = Encoding.ASCII.GetBytes(randstr);

                //loop through the RGB array and copy the payload into it
                for (int counter = 0; counter < (rgbValues.Length) / 3; counter++) {
                    int paybyte1;
                    int paybyte2;
                    int paybyte3;
                    if (counter < payload.Length){
                        paybyte1 = (int)Math.Floor((decimal)(payload[counter] / 16));
                        paybyte2 = (payload[counter] & 0x0f);
                        paybyte3 = (randb[(counter + 2) % 109] & 0x0f);
                    } else {
                        paybyte1 = (randb[counter % 113] & 0x0f);
                        paybyte2 = (randb[(counter + 1)% 67] & 0x0f);
                        paybyte3 = (randb[(counter + 2)% 109] & 0x0f);
                    }
                    rgbValues[(counter * 3)] = (byte)((rgbValues[(counter * 3)] & 0xf0) | paybyte1);
                    rgbValues[(counter * 3 + 1)] = (byte)((rgbValues[(counter * 3 + 1)] & 0xf0) | paybyte2);
                    rgbValues[(counter * 3 + 2)] = (byte)((rgbValues[(counter * 3 + 2)] & 0xf0) | paybyte3);
                }

                //Copy the array of RGB values back to the bitmap
                Marshal.Copy(rgbValues, 0, ptr, bytes);
                img.UnlockBits(bmpData);

                //Write the image to a file
                img.Save(outputfile, ImageFormat.Png);
                img.Dispose();

                Executereplacedembly(outputfile, payload.Length);

            }
            catch (Exception e)
            {
                Console.WriteLine("[x] error: " + e.Message);
                Console.WriteLine("[x] error: " + e.StackTrace);
            }
        }

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int Nearest
		(
			this IEnumerable<int> self,
			int target
		)
		{
			var min = self.Min( c => Math.Abs( c - target ) );
			return self.FirstOrDefault( c => Math.Abs( c - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int Nearest<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var min = self.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( self.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static TSource FindNearest<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var min = self.Min( c => Math.Abs( selector( c ) - target ) );
			return self.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestMoreThan
		(
			this IEnumerable<int> self,
			int target
		)
		{
			var list = self.Where( c => target < c ).ToArray();
			var min = list.Min( c => Math.Abs( c - target ) );
			return list.FirstOrDefault( c => Math.Abs( c - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestMoreThan<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target < selector( c ) ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static TSource FindNearestMoreThan<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target < selector( c ) ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestOrLess
		(
			this IEnumerable<int> self,
			int target
		)
		{
			var list = self.Where( c => c <= target );
			var min = list.Min( c => Math.Abs( c - target ) );
			return list.FirstOrDefault( c => Math.Abs( c - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestOrLess<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => selector( c ) <= target );
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static TSource FindNearestOrLess<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => selector( c ) <= target );
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestOrMore
		(
			this IEnumerable<int> self,
			int target
		)
		{
			var list = self.Where( c => target <= c );
			var min = list.Min( c => Math.Abs( c - target ) );
			return list.FirstOrDefault( c => Math.Abs( c - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestOrMore<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target <= selector( c ) );
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static TSource FindNearestOrMore<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target <= selector( c ) );
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestMoreLess
		(
			this IEnumerable<int> self,
			int target
		)
		{
			var list = self.Where( c => c < target ).ToArray();
			var min = list.Min( c => Math.Abs( c - target ) );
			return list.FirstOrDefault( c => Math.Abs( c - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestMoreLess<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => selector( c ) < target ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static TSource FindNearestMoreLess<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => selector( c ) < target ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static int NearestOrMore<TSource>
		(
			this IList<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target <= selector( c ) ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( list.First( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static TSource FindNearestOrMore<TSource>
		(
			this IList<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target <= selector( c ) ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return list.First( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static int NearestOrMoreOrDefault<TSource>
		(
			this IList<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target <= selector( c ) ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( list.Find( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static TSource FindNearestOrMoreOrDefault<TSource>
		(
			this IList<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target <= selector( c ) ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return list.Find( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static int NearestMoreLess
		(
			this IList<int> self,
			int target
		)
		{
			var list = self.Where( c => c < target ).ToArray();
			var min = list.Min( c => Math.Abs( c - target ) );
			return list.First( c => Math.Abs( c - target ) == min );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static TSource FindNearestMoreLess<TSource>
		(
			this IList<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => selector( c ) < target ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return list.First( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static int NearestMoreLessOrDefault<TSource>
		(
			this IList<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => selector( c ) < target ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( list.Find( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static TSource FindNearestMoreLessOrDefault<TSource>
		(
			this IList<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => selector( c ) < target ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return list.Find( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static int Nearest
		(
			this IList<int> self,
			int target
		)
		{
			var min = self.Min( c => Math.Abs( c - target ) );
			return self.First( c => Math.Abs( c - target ) == min );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static int Nearest<TSource>
		(
			this IList<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var min = self.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( self.First( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static TSource FindNearest<TSource>
		(
			this IList<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var min = self.Min( c => Math.Abs( selector( c ) - target ) );
			return self.First( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static int NearestOrDefault(
			this IList<int> self,
			int target
		)
		{
			var min = self.Min( c => Math.Abs( c - target ) );
			return self.Find( c => Math.Abs( c - target ) == min );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static int NearestOrDefault<TSource>
		(
			this IList<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var min = self.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( self.Find( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static TSource FindNearestOrDefault<TSource>
		(
			this IList<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var min = self.Min( c => Math.Abs( selector( c ) - target ) );
			return self.Find( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static int NearestMoreThan
		(
			this IList<int> self,
			int target
		)
		{
			var list = self.Where( c => target < c ).ToArray();
			var min = list.Min( c => Math.Abs( c - target ) );
			return list.First( c => Math.Abs( c - target ) == min );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static int NearestMoreThan<TSource>
		(
			this IList<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target < selector( c ) ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( list.First( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static TSource FindNearestMoreThan<TSource>
		(
			this IList<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target < selector( c ) ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return list.First( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static int NearestMoreThanOrDefault
		(
			this IList<int> self,
			int target
		)
		{
			var list = self.Where( c => target < c ).ToArray();
			var min = list.Min( c => Math.Abs( c - target ) );
			return list.Find( c => Math.Abs( c - target ) == min );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static int NearestMoreThanOrDefault<TSource>
		(
			this IList<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target < selector( c ) ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( list.Find( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static TSource FindNearestMoreThanOrDefault<TSource>
		(
			this IList<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target < selector( c ) ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return list.Find( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IListExt.cs
with MIT License
from baba-s

public static int NearestOrLess
		(
			this IList<int> self,
			int target
		)
		{
			var list = self.Where( c => c <= target ).ToArray();
			var min = list.Min( c => Math.Abs( c - target ) );
			return list.First( c => Math.Abs( c - target ) == min );
		}

See More Examples