SetPixel() public method

public SetPixel ( int x, int y, Color color ) : void
x int
y int
color Color
return void
Ejemplo n.º 1
2
        public static void Remove(int colour, ref Bitmap bp)
        {
            Color c;
              switch (colour)
              {
            case BLUE:
              for (int i = 1; i < bp.Width; i++)
            for (int j = 1; j < bp.Height; j++)
            {
              c = bp.GetPixel(i, j);
              bp.SetPixel(i, j, Color.FromArgb(c.R, c.G, 0));
            }
              break;

            case RED:
              for (int i = 1; i < bp.Width; i++)
            for (int j = 1; j < bp.Height; j++)
            {
              c = bp.GetPixel(i, j);
              bp.SetPixel(i, j, Color.FromArgb(0, c.G, c.B));
            }
              break;

            case GREEN:
              for (int i = 1; i < bp.Width; i++)
            for (int j = 1; j < bp.Height; j++)
            {
              c = bp.GetPixel(i, j);
              bp.SetPixel(i, j, Color.FromArgb(c.R, 0, c.B));
            }
              break;
              }
        }
Ejemplo n.º 2
0
		private void MakeImage( short[] colors )
		{
			Image = new System.Drawing.Bitmap( 34, 14 );

			if ( colors == null )
			{
				this.NoHue = true;
				return;
			}

			// Draw border
			for ( int x = 0; x < 34; x++ )
			{
				Image.SetPixel( x, 0, Color.Black );
				Image.SetPixel( x, 13, Color.Black );
			}
			for ( int y = 1; y < 14; y++ )
			{
				Image.SetPixel( 0, y, Color.Black );
				Image.SetPixel( 33, y, Color.Black );
			}

			for ( int i = 0; i < 32; i++ )
			{
				for ( int y = 1; y < 13; y++ )
					Image.SetPixel( i + 1, y, TheBox.Mul.Hue.ToColor( colors[i] ) );
			}
		}
        private void generateHazardImage()
        {
            Bitmap bitmap = new Bitmap(slopeWidth, slopeHeight);

            int slopeX = 0;
            int slopeY = 0;

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    System.Drawing.Color tempColor = getHazardColorValue(hazardModel[x, y]);

                    bitmap.SetPixel(slopeX, slopeY, tempColor);
                    for (int a = 0; a < sectorSize; a++)
                    {
                        for (int b = 0; b < sectorSize; b++)
                        {
                            bitmap.SetPixel(slopeX + a, slopeY + b, tempColor);
                        }
                    }

                    slopeY += sectorSize;
                }
                slopeY = 0;
                slopeX += sectorSize;
            }

            hazardBitmap = bitmap;
        }
Ejemplo n.º 4
0
 public static Bitmap encode(Bitmap img, int offSet)
 {
     Bitmap newImage = new Bitmap(img.Width * offSet, img.Height * offSet);
     List<List<Color>> pixelMap = new List<List<Color>>();
     for (int y = 0; y < img.Height; y++)
     {
         List<Color> row = new List<Color>();
         for (int x = 0; x < img.Width; x++)
         {
             row.Add(img.GetPixel(x, y));
         }
         pixelMap.Add(row);
     }
     Random r = new Random();
     for (int y = 0; y < newImage.Height; y++)
     {
         for (int x = 0; x < newImage.Width; x++)
         {
             if (x % offSet == 0 && y % offSet == 0)
             {
                 newImage.SetPixel(x, y, pixelMap[y / offSet][x / offSet]);
             }
             else
             {
                 newImage.SetPixel(x, y, img.GetPixel(r.Next(0, img.Width - 1), r.Next(0, img.Height - 1)));
             }
         }
     }
     return newImage;
 }
Ejemplo n.º 5
0
        /// <summary>
        ///     カーソルを作成する
        /// </summary>
        /// <param name="bitmap">カーソル画像</param>
        /// <param name="xHotSpot">ホットスポットのX座標</param>
        /// <param name="yHotSpot">ホットスポットのY座標</param>
        /// <returns>作成したカーソル</returns>
        public static Cursor CreateCursor(Bitmap bitmap, int xHotSpot, int yHotSpot)
        {
            Bitmap andMask = new Bitmap(bitmap.Width, bitmap.Height);
            Bitmap xorMask = new Bitmap(bitmap.Width, bitmap.Height);
            Color transparent = bitmap.GetPixel(bitmap.Width - 1, bitmap.Height - 1);
            for (int x = 0; x < bitmap.Width; x++)
            {
                for (int y = 0; y < bitmap.Height; y++)
                {
                    Color pixel = bitmap.GetPixel(x, y);
                    if (pixel == transparent)
                    {
                        andMask.SetPixel(x, y, Color.White);
                        xorMask.SetPixel(x, y, Color.Transparent);
                    }
                    else
                    {
                        andMask.SetPixel(x, y, Color.Black);
                        xorMask.SetPixel(x, y, pixel);
                    }
                }
            }

            IntPtr hIcon = bitmap.GetHicon();
            IconInfo info = new IconInfo();
            NativeMethods.GetIconInfo(hIcon, ref info);
            info.xHotspot = xHotSpot;
            info.yHotspot = yHotSpot;
            info.hbmMask = andMask.GetHbitmap();
            info.hbmColor = xorMask.GetHbitmap();
            info.fIcon = false;
            hIcon = NativeMethods.CreateIconIndirect(ref info);
            return new Cursor(hIcon);
        }
Ejemplo n.º 6
0
        public Bitmap ChangeColor(Bitmap scrBitmap, Bitmap result, Color oldColor, Color newColor, Color notToChange)
        {
            //You can change your new color here. Red,Green,LawnGreen any..
            // Build a colour map of old to new colour
            ColorMap[] colorMap = BuildArrayOfOldAndNewColours(scrBitmap, oldColor, newColor, notToChange);

            Color actulaColor;
            //make an empty bitmap the same size as scrBitmap
            Bitmap newBitmap = new Bitmap(scrBitmap.Width, scrBitmap.Height);
            for (int i = 0; i < scrBitmap.Width; i++)
            {
                for (int j = 0; j < scrBitmap.Height; j++)
                {
                    //get the pixel from the scrBitmap image
                    actulaColor = scrBitmap.GetPixel(i, j);
                    var map = (from x in colorMap where x.OldColor.A == actulaColor.A && x.OldColor.R == actulaColor.R && x.OldColor.G == actulaColor.G && x.OldColor.B == actulaColor.B select x).FirstOrDefault();
                    // > 150 because.. Images edges can be of low pixel colr. if we set all pixel color to new then there will be no smoothness left.
                    if (actulaColor.A == 0 && actulaColor.R == 0 && actulaColor.G == 0 && actulaColor.B == 0) continue;
                    if (actulaColor.R != notToChange.R || notToChange.G != notToChange.G && actulaColor.B != notToChange.B)
                        newBitmap.SetPixel(i, j, map.NewColor);
                    else
                        newBitmap.SetPixel(i, j, actulaColor);
                }
            }
            return newBitmap;
        }
Ejemplo n.º 7
0
        public void TestBitmapToByteArray()
        {
            Bitmap bm = new Bitmap(2, 2, PixelFormat.Format24bppRgb);
            bm.SetPixel(0, 0, Color.FromArgb(1, 2, 3));
            bm.SetPixel(1, 0, Color.FromArgb(4, 5, 6));
            bm.SetPixel(0, 1, Color.FromArgb(7, 8, 9));
            bm.SetPixel(1, 1, Color.FromArgb(10, 11, 12));
            int stride;
            byte[] pxl = ExecuteBitmapToByteArray(bm, out stride);
            Assert.AreEqual(16, pxl.Length);
            Assert.AreEqual(8, stride);

            // line 1
            Assert.AreEqual(3, pxl[0]);
            Assert.AreEqual(2, pxl[1]);
            Assert.AreEqual(1, pxl[2]);
            Assert.AreEqual(6, pxl[3]);
            Assert.AreEqual(5, pxl[4]);
            Assert.AreEqual(4, pxl[5]);

            // line 2
            Assert.AreEqual(9, pxl[8]);
            Assert.AreEqual(8, pxl[9]);
            Assert.AreEqual(7, pxl[10]);
            Assert.AreEqual(12, pxl[11]);
            Assert.AreEqual(11, pxl[12]);
            Assert.AreEqual(10, pxl[13]);
        }
Ejemplo n.º 8
0
        //-------------------------------------------------------------------------------------------
        public static Bitmap GenerateCode(string data, int size)
        {
            QRCodeWriter writer = new QRCodeWriter();
               com.google.zxing.common.ByteMatrix matrix;

               matrix = writer.encode(data, BarcodeFormat.QR_CODE, size, size, null);

               Bitmap img = new Bitmap(size, size);
               Color Color = Color.FromArgb(0, 0, 0);

               for (int y = 0; y < matrix.Height; ++y)
               {
                    for (int x = 0; x < matrix.Width; ++x)
                    {
                         Color pixelColor = img.GetPixel(x, y);

                         //Find the colour of the dot
                         if (matrix.get_Renamed(x, y) == -1)
                         {
                              img.SetPixel(x, y, Color.White);
                         }
                         else
                         {
                              img.SetPixel(x, y, Color.Black);
                         }
                    }
               }
               return img;
        }
Ejemplo n.º 9
0
        private static Bitmap GenerateHistogram(Bitmap image)
        {
            Bitmap histogram = new Bitmap(256, 100);

            int[] colorcounts = new int[256];

            // This is ungodly slow but it's just for diagnostics.
            for (int y = 0; y < image.Height; y++)
            {
                for (int x = 0; x < image.Width; x++)
                {
                    Color c = image.GetPixel(x, y);
                    colorcounts[c.R]++;
                    colorcounts[c.G]++;
                    colorcounts[c.B]++;
                }
            }

            int maxval = 0;
            for (int i = 0; i < 256; i++) if (colorcounts[i] > maxval) maxval = colorcounts[i];
            for (int i = 1; i < 255; i++)
            {
                //Console.WriteLine(i + ": " + histogram[i] + "," + (((float)histogram[i] / (float)maxval) * 100F));
                colorcounts[i] = (int)Math.Round(((double)colorcounts[i] / (double)maxval) * 100D);
            }
            for (int x = 0; x < 256; x++)
            {
                for (int y = 0; y < 100; y++)
                {
                    if (colorcounts[x] >= (100 - y)) histogram.SetPixel(x, y, Color.Black);
                    else histogram.SetPixel(x, y, Color.White);
                }
            }
            return histogram;
        }
Ejemplo n.º 10
0
        public static Bitmap GetThumbnail(Bitmap bmpImage, Size size)
        {
            double width = bmpImage.Width;
             double height = bmpImage.Height;

             Double xFactor = new Double();
             Double yFactor = new Double();
             xFactor = (double)size.Width / width;
             yFactor = (double)size.Height / height;

             Double scaleFactor = Math.Min(xFactor, yFactor);

             Size scaledSize = new Size();
             scaledSize.Width = Convert.ToInt32(width * scaleFactor);
             scaledSize.Height = Convert.ToInt32(height * scaleFactor);

             Bitmap scaledOriginal = (Bitmap) bmpImage.GetThumbnailImage(scaledSize.Width, scaledSize.Height, new Image.GetThumbnailImageAbort(target), IntPtr.Zero);
             Bitmap thumnailBmp = new Bitmap(size.Width, size.Height);

             for (int y = 0; y < thumnailBmp.Height; y++)
             {
            for (int x = 0; x < thumnailBmp.Width; x++)
            {
               if ((x < scaledOriginal.Width) && (y < scaledOriginal.Height))
               {
                  thumnailBmp.SetPixel(x, y, scaledOriginal.GetPixel(x, y));
               }
               else
               {
                  thumnailBmp.SetPixel(x, y, Color.Transparent);
               }
            }
             }
             return thumnailBmp;
        }
Ejemplo n.º 11
0
 private void binarize(Bitmap bittt, ref int[,] massss, ToolStripProgressBar progress)
 {
     massss = new int[bittt.Width, bittt.Height];
     progress.Minimum = 0;
     progress.Maximum = bittt.Height;
     for (int i = 0; i < bittt.Height; i++)
     {
         for (int j = 0; j < bittt.Width; j++)
         {
             if (bittt.GetPixel(j, i).R > 200 || bittt.GetPixel(j, i).B > 200 || bittt.GetPixel(j, i).G > 200)
             {
                 bittt.SetPixel(j, i, Color.White);
                 massss[j, i] = 0;
             }
             else
             {
                 bittt.SetPixel(j, i, Color.Black);
                 massss[j, i] = 1;
             }
             /*      if (j == (int)(bittt.Height / 6))
                    {
                        bittt.SetPixel(j, i, Color.Teal);
                    }*/
         }
         if (progress.Value < bittt.Height)
         {
             progress.Value++;
         }
     }
     progress.Value = 0;
 }
Ejemplo n.º 12
0
        private static void Print(int id, int length, Matrix matrix)
        {
            if (id % 10 != 0) return;

            var bitmap = new Bitmap(length*2, length);

            for (int i = 0; i < length; i++)
            {
                for (int j = 0; j < length; j++)
                {
                    bitmap.SetPixel(i, j, matrix.Eat[i, j] != 0 ? Color.Green : Color.White);
                }
            }

            for (int i = 0; i < length; i++)
            {
                for (int j = 0; j < length; j++)
                {
                    var x = i + length;
                    var y = j;

                    bitmap.SetPixel(x, y, matrix.Cells[i, j] == null ? Color.White : Color.Red);

                    // bitmap.SetPixel(x, y, matrix.Cells[i, j] == null ? (eat[i, j] ? Color.White : Color.Green) : Color.Red);
                }
            }

            bitmap.Save($@"C:\temp\creatures\bitmaps\{id}.bmp", ImageFormat.Bmp);
        }
Ejemplo n.º 13
0
        public static void CreateBitmap(TemporalNetwork net, string output_path, bool square = true, int border_width=5)
        {
            int columns = 1;
            if(square)
                columns = ((int)Math.Sqrt(net.AggregateNetwork.VertexCount * net.Length)) / net.VertexCount + 1;
            int width = (border_width + net.AggregateNetwork.VertexCount) * columns;
            int height = (int) Math.Ceiling( (double) net.Length / (double) columns);
            Bitmap bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            Console.WriteLine("Exporting to png, output dimensions: {0} x {1}", width, height);

            Color[] colorWheel = new Color[] {Color.Red, Color.Green, Color.LightBlue, Color.Orange, Color.Blue, Color.Brown, Color.DarkViolet};
            Random r = new Random();

            Dictionary<string, int> vertex_map = new Dictionary<string, int>();
            int i = 0, line = 0;
            foreach (var v in net.AggregateNetwork.Vertices)
                vertex_map[v] = i++;

            foreach(int t in net.Keys)
            {
                int y = line % height;
                int x = (line / height) * (net.AggregateNetwork.VertexCount + border_width);
                int c = r.Next(colorWheel.Length);
                foreach (var edge in net[t])
                {
                    bmp.SetPixel(x + vertex_map[edge.Item1], y, colorWheel[c%colorWheel.Length]);
                    bmp.SetPixel(x + vertex_map[edge.Item2], y, colorWheel[c % colorWheel.Length]);
                    c++;
                }
                for (int j = 0; j < border_width; j++)
                    bmp.SetPixel(x+net.AggregateNetwork.VertexCount+j, y, Color.White);
                line++;
            }
            bmp.Save(output_path, System.Drawing.Imaging.ImageFormat.Png);
        }
Ejemplo n.º 14
0
        public bool[,] OperateOverArrayWithSize(int[, ] array, int x, int y)
        {
            var bitmap = new Bitmap(x, y);
               // var bmp = BitmapOverArrayWithSize(array, x, y);
            bool[,] binary = new bool[x, y];

            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < y; j++)
                {
                    bool value = CheckAtPosition(array, i, j, x, y);
                    if (value)
                    {
                        binary[i, j] = true;
                        bitmap.SetPixel(i, j, Color.White);
                    }
                    else
                    {
                        bitmap.SetPixel(i, j, Color.Black);
                    }
                }
            }
            bitmap.Save("edgeImage.bmp");
            return binary;
        }
        /* Convert the image into binary image*/
        public Bitmap Img2BW(Bitmap imgSrc, double threshold)
        {
            int width = imgSrc.Width;
            int height = imgSrc.Height;
            int px; double br;
            Color pixel;
            Bitmap imgOut = new Bitmap(imgSrc);
            allPoints = new Point[5000000];

            for (int row = 0; row < height - 1; row++)
            {
                for (int col = 0; col < width - 1; col++)
                {
                    pixel = imgSrc.GetPixel(col, row);
                    px = pixel.ToArgb();
                    br = pixel.GetBrightness();
                    if (pixel.GetBrightness() < threshold)
                    {
                        imgOut.SetPixel(col, row, cblack);
                        vertices.Add(new Vertex(col, row));
                        allPoints[countPoints].X = col;
                        allPoints[countPoints].Y = row;
                        countPoints++;
                    }
                    else
                        imgOut.SetPixel(col, row, cwhite);
                }
            }
            
            return imgOut;
        }
Ejemplo n.º 16
0
        public override System.Drawing.Bitmap GetDrawnBitmap(FractalAssociationParametrs FAP, object Extra = null)
        {
            int width = FAP.Width, height = FAP.Height;
            Bitmap bmp = new Bitmap(width, height);
            double[][] dm = ((RadianMatrix)FAP.GetUniqueParameter(typeof(RadianMatrix))).Matrix;
            Color cl = Color.Black; ;
            ulong[][] iter_matrix=FAP.Get2DOriginalIterationsMatrix();
            ulong iter;
            int deg;
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    iter = (ulong)(iter_matrix[x][y]*0.8);
                    cl =Color.FromArgb((255 - iter / 1.85) >= 0 ? (int)(255 - iter / 1.85) : 0,
                                                         (255 - iter / 1.4) >= 0 ? (int)(255 - iter / 1.4) : 0,
                                                         (255 - iter / 1.8) >= 0 ? (int)(255 - iter / 1.8) : 0);

                    bmp.SetPixel(x, y,cl);
                    if (iter < 85) {
                        deg = (int)((dm[x][y] / Math.PI) * 180);
                        if (deg < 0) deg = 360 + deg;
                        if (deg < 181) cl = Color.FromArgb(255 - 255 * deg / 180,255- 255 * deg / 180, 255 -255 * deg / 180);
                        else
                        {
                            deg -= 180;
                            cl = Color.FromArgb(255 * deg / 180, 255 * deg / 180,  255 * deg / 180);
                        }

                    bmp.SetPixel(x, y,cl);}

                }
            }
            return bmp;
        }
        public void GenerateBackgroundTest()
        {
            Bitmap backgroundTemplate = new Bitmap(30, 20);
            backgroundTemplate.SetPixel(0, 0, Color.Red);
            backgroundTemplate.SetPixel(19, 9, Color.Blue);
            const int width = 50;
            const int height = 50;
            Bitmap actual = StereoPictureBuilder_Accessor.GenerateBackground(backgroundTemplate, width, height);

            Bitmap expected = new Bitmap(width, height);
            expected.SetPixel(0, 0, Color.Red);
            expected.SetPixel(30, 0, Color.Red);
            expected.SetPixel(0, 20, Color.Red);
            expected.SetPixel(30, 20, Color.Red);
            expected.SetPixel(19, 9, Color.Blue);
            expected.SetPixel(49, 9, Color.Blue);
            expected.SetPixel(19, 29, Color.Blue);
            expected.SetPixel(49, 29, Color.Blue);
            expected.SetPixel(19, 49, Color.Blue);
            expected.SetPixel(49, 49, Color.Blue);

            //Assert.AreEqual(expected, actual);
            Assert.AreEqual(expected.Width, actual.Width);
            Assert.AreEqual(expected.Height, actual.Height);
            Assert.AreEqual(expected.GetPixel(0, 0), actual.GetPixel(0, 0));
            Assert.AreEqual(expected.GetPixel(49, 49), actual.GetPixel(49, 49));
        }
Ejemplo n.º 18
0
        public Stroke(Bitmap bitmap,Color color,float a,float b,float c,float soft,bool flat,bool square)
        {
            //Create shape
            shape=(Bitmap)bitmap.Clone();
            for(int i=0;i<shape.Width;i++)
            {
                for(int j=0;j<shape.Height;j++)
                {
                    float x=(float)(i-shape.Width/2);
                    float y=(float)(j-shape.Height/2);
                    float len2=x*x+y*y;
                    float r=Math.Min(shape.Width/2,shape.Height/2);
                    float r2=r*r;
                    if(square||len2<=r2)
                    {
                        Color col=shape.GetPixel(i,j);
                        float ii=(((float)(col.R+col.G+col.B))/3f)/255f;
                        int aa=(int)(((a*ii*ii+b*ii+c)*(((float)color.A)/255f)*255f));
                        if(aa<0)
                            aa=0;
                        if(aa>255)
                            aa=255;
                        float sa=1f;
                        if(soft>0f)
                        {
                            sa=1f-(len2/r2)*soft;
                            if(sa<0f)
                                sa=0f;
                            if(sa>1f)
                                sa=1f;
                        }
                        if(flat)
                            shape.SetPixel(i,j,Color.FromArgb((int)(((float)aa)*sa),color));
                        else
                        {
                            Color cc=shape.GetPixel(i,j);
                            int rr=(int)((((float)cc.R)/255f)*(((float)color.R)/255f)*255f);
                            if(rr<0)
                                rr=0;
                            if(rr>255)
                                rr=255;
                            int gg=(int)((((float)cc.G)/255f)*(((float)color.G)/255f)*255f);
                            if(gg<0)
                                gg=0;
                            if(gg>255)
                                gg=255;
                            int bb=(int)((((float)cc.B)/255f)*(((float)color.B)/255f)*255f);
                            if(bb<0)
                                bb=0;
                            if(bb>255)
                                bb=255;
                            shape.SetPixel(i,j,Color.FromArgb((int)(((float)aa)*sa),rr,gg,bb));
                        }

                    }
                    else
                        shape.SetPixel(i,j,Color.FromArgb(0,0,0,0));
                }
            }
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Converts byte buffer to Image with given bitmap type
 /// </summary>
 /// <param name="data"></param>
 /// <param name="w"></param>
 /// <param name="h"></param>
 /// <param name="type"></param>
 /// <returns></returns>
 public static Image ConvertBytesToImage(byte[] data, int w, int h, ImageType type = ImageType.RGB) {
     var bitmap = new Bitmap(w,h);
     var channels = GetChannelCount(type);
     var bluefirst = type == ImageType.BGR || type == ImageType.BGRA;
     var size = w * h * channels;
     if (data.Length < size) {
         throw new Exception("invalid buffer size");
     }
     var i = -1;
     for (var r = 0; r < h; r++) {
         for (var c = 0; c < w; c++) {
             if (channels == 1) {
                 int gray = data[++i];
                 bitmap.SetPixel(c, r, Color.FromArgb(gray, gray, gray));
             }
             else {
                 var buf = new[] {data[++i], data[++i], data[++i], channels == 4 ? data[++i] : (byte)0};
                 var basecolor = Color.FromArgb(bluefirst?buf[2]:buf[0],buf[1],bluefirst?buf[0]:buf[2]);
                 if (channels == 4) {
                     bitmap.SetPixel(c, r, Color.FromArgb(buf[3], basecolor));
                 }
                 else {
                     bitmap.SetPixel(c,r,basecolor);
                 }
             }
         }
     }
     return bitmap;
 }
Ejemplo n.º 20
0
 static Bitmap GetMandelbrotImage(PictureBox pictureBox, double maxr, double minr, double maxi, double mini)
 {
     currentMaxR = maxr;
     currentMaxI = maxi;
     currentMinR = minr;
     currentMinI = mini;
     var img = new Bitmap(pictureBox.Width, pictureBox.Height);
     double xjump = (maxr - minr)/Convert.ToDouble(img.Width);
     double yjump = (maxi - mini)/Convert.ToDouble(img.Height);
     int loopmax = 1000; // the 'resolution'.. lower means faster..
     for (int x = 0; x < img.Width; x++)
     {
         double cx = (xjump*x) - Math.Abs(minr);
         for (int y = 0; y < img.Height; y++)
         {
             double zx = 0;
             double zy = 0;
             var cy = (yjump*y) - Math.Abs(mini);
             var loopgo = 0;
             while (zx*zx + zy*zy <= 4 && loopgo < loopmax)
             {
                 loopgo++;
                 var tempzx = zx;
                 zx = (zx*zx) - (zy*zy) + cx;
                 zy = (2*tempzx*zy) + cy;
             }
             if (loopgo != loopmax)
                 img.SetPixel(x, y, Color.FromArgb(loopgo % 128 * 2, loopgo % 32 * 7, loopgo % 16 * 14));
             else
                 img.SetPixel(x, y, Color.Black);
         }
     }
     return img;
 }
Ejemplo n.º 21
0
        public double GetBitmapsSimilarityRatio(Bitmap first, Bitmap second)
        {
            int DiferentPixels = 0;
            Bitmap container = new Bitmap(first.Width, first.Height);
            for (int i = 0; i < first.Width; i++)
            {
                for (int j = 0; j < first.Height; j++)
                {
                    int r1 = second.GetPixel(i, j).R;
                    int g1 = second.GetPixel(i, j).G;
                    int b1 = second.GetPixel(i, j).B;

                    int r2 = first.GetPixel(i, j).R;
                    int g2 = first.GetPixel(i, j).G;
                    int b2 = first.GetPixel(i, j).B;

                    if (r1 != r2 && g1 != g2 && b1 != b2)
                    {
                        DiferentPixels++;
                        container.SetPixel(i, j, Color.Red);
                    }
                    else
                        container.SetPixel(i, j, first.GetPixel(i, j));
                }
            }
            int TotalPixels = first.Width * first.Height;
            float dierence = (float)((float)DiferentPixels / (float)TotalPixels);
            float percentage = dierence * 100;

            return percentage;
        }
Ejemplo n.º 22
0
 public Bitmap GetBitmap()
 {
     Bitmap output;
     using (BinaryReader reader = new BinaryReader(File.Open(filepath, FileMode.Open)))
     {
         int width = reader.ReadInt32();
         int height = reader.ReadInt32();
         output = new Bitmap(width * 8, height);
         for (int y = height - 1; y >= 0; y--)
         {
             for (int x = 0; x < width; x++)
             {
                 byte input = reader.ReadByte();
                 for (int i = 0; i < 8; i++)
                 {
                     //we unpack the bits
                     if ((input & (byte)Math.Pow(2, i)) != 0) //read 1 bit
                     {
                         output.SetPixel((x * 8) + i, y, Color.Black);
                     }
                     else //read 0 bit
                     {
                         output.SetPixel((x * 8) + i, y, Color.White);
                     }
                 }
             }
         }
     }
     return output;
 }
Ejemplo n.º 23
0
        public static Bitmap CreateBitmapFromMap(ITerrainChannel map)
        {
            Bitmap gradientmapLd = new Bitmap("defaultstripe.png");

            int pallete = gradientmapLd.Height;

            Bitmap bmp = new Bitmap(map.Width, map.Height);
            Color[] colours = new Color[pallete];

            for (int i = 0; i < pallete; i++)
            {
                colours[i] = gradientmapLd.GetPixel(0, i);
            }

            for (int y = 0; y < map.Height; y++)
            {
                for (int x = 0; x < map.Width; x++)
                {
                    // 512 is the largest possible height before colours clamp
                    int colorindex = (int)(Math.Max(Math.Min(1.0, map[x, y] / 512.0), 0.0) * (pallete - 1));

                    // Handle error conditions
                    if (colorindex > pallete - 1 || colorindex < 0)
                        bmp.SetPixel(x, map.Height - y - 1, Color.Red);
                    else
                        bmp.SetPixel(x, map.Height - y - 1, colours[colorindex]);
                }
            }
            return bmp;
        }
        public static int Compare(Bitmap processedImage, Bitmap originalImage, out Bitmap diffImage)
        {
            var width = processedImage.Width;
            var height = processedImage.Height;
            diffImage = new Bitmap(width, height);

            var diffCount = 0;
            var eqColor = Color.White;
            var neColor = Color.Red;
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    if (processedImage.GetPixel(x, y).Equals(originalImage.GetPixel(x, y)))
                        diffImage.SetPixel(x, y, eqColor);
                    else
                    {
                        diffImage.SetPixel(x, y, neColor);
                        diffCount++;
                    }
                }
            }

            return diffCount;
        }
Ejemplo n.º 25
0
        private void Form1_Load(object sender, EventArgs e)
        {
            //read source image
            Bitmap simg = new Bitmap("D:\\Image\\audrey.jpg");

            //get source image dimension
            int width = simg.Width;
            int height = simg.Height;

            //load source image in picturebox1
            pictureBox1.Image = Image.FromFile("D:\\Image\\audrey.jpg");

            //mirror image
            Bitmap mimg = new Bitmap(width * 2, height);

            for (int y = 0; y < height; y++)
            {
                for (int lx = 0, rx = width * 2 - 1; lx < width; lx++, rx--)
                {
                    //get source pixel value
                    Color p = simg.GetPixel(lx, y);

                    //set mirror pixel value
                    mimg.SetPixel(lx, y, p);
                    mimg.SetPixel(rx, y, p);
                }
            }

            //load mirror image in picturebox2
            pictureBox2.Image = mimg;

            //save (write) mirror image
            mimg.Save("D:\\Image\\MirrorImage.png");
        }
Ejemplo n.º 26
0
 private void button1_Click(object sender, EventArgs e)
 {
     // Flatten the image to just black and white based on a threshold value
     Bitmap bmap = new Bitmap(im);
     Color col;
     // Keep track of the ratio of black to white
     int whiteCount = 0;
     int blackCount = 0;
     for (int i = 0; i < bmap.Width; i++)
     {
         for (int j = 0; j < bmap.Height; j++)
         {
             col = bmap.GetPixel(i, j);
             if (col.GetBrightness() * 256 > trackThresh.Value)
             {
                 bmap.SetPixel(i, j, Color.White);
                 whiteCount++;
             }
             else
             {
                 bmap.SetPixel(i, j, Color.Black);
                 blackCount++;
             }
         }
     }
     double percentWhite = whiteCount * 1.0 / (whiteCount + blackCount);
     label_imageratio.Text = ("W/B ratio: " + percentWhite.ToString()).Remove(16);
     im_bw = bmap;
     pictureBox1.Image = im_bw;
     button_load_text.Enabled = true;
 }
Ejemplo n.º 27
0
        public static void MyClassInitialize(TestContext testContext)
        {
            Greyscale conv = new Greyscale();
            testBitmap = new Bitmap(testPixel, testPixel);
            for (int height = 0; height < testBitmap.Height; height++)
            {
                for (int width = 0; width < testBitmap.Width; width++)
                {
                    testBitmap.SetPixel(width, height, Color.White);
                    width++;
                    testBitmap.SetPixel(width, height, Color.Black);
                    width++;
                    testBitmap.SetPixel(width, height, Color.Red);
                    width++;
                    testBitmap.SetPixel(width, height, Color.Green);
                    width++;
                    testBitmap.SetPixel(width, height, Color.Blue);
                }
            }

            //create greyscale
            double[] newColorValues = new double[3];
            for (int i = 0; i < newColorValues.GetLength(0); i++)
            {
                newColorValues[i] = 1;
            }
            fullGrey = new Memento("Blur", newColorValues);

            //get greyscaled Bitmap
            original = conv.getMemento();
            conv.setMemento(fullGrey);
            processedBitmap = conv.process(testBitmap);
            conv.setMemento(original);
        }
Ejemplo n.º 28
0
        public static Bitmap byteArrayToBitmap(byte[] byteArray, int height, int width)
        {
            // create our bitmap image that we will be maping the contents of the byte
            // array into
            Bitmap image = new Bitmap(width, height);

            // we need to expand out the byte array to a single byte representing each bit
            // in each of the bytes.  This will allow the next loop to be less than confusing.
            for (int heightIndex = 0; heightIndex < height / BITS_IN_A_BYTE; heightIndex++)
            {
                for (int widthIndex = 0; widthIndex < width; widthIndex++)
                {
                    for (int maskOffset = 0; maskOffset < BITS_IN_A_BYTE; maskOffset++)
                    {
                        int value = byteArray[(heightIndex * width) + widthIndex];
                        int maskResult = value & (1 << maskOffset);

                        // calculate the x,y location in the image we need to update
                        int x = width - widthIndex - 1;

                        int y = (heightIndex * (BITS_IN_A_BYTE)) + maskOffset;

                        if (maskResult != 0)
                            image.SetPixel(x, y, Color.Aqua);
                        else
                            image.SetPixel(x, y, Color.Black);
                    }
                }
            }

            // reaturn our created image
            return image;
        }
Ejemplo n.º 29
0
        public static Bitmap ToImage(this Glyph glyph, int width)
        {
            var bitmap = new Bitmap(width, width, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            var cellSize = width/glyph.Size;
            var glyphSize = glyph.Size;

            for (var i = 0; i < width; i++)
            {
                var yCell = i/cellSize;

                for (var j = 0; j < width; j++)
                {
                    var xCell = j/cellSize;

                    if ((yCell >= glyphSize) || (xCell >= glyphSize))
                    {
                        // set pixel to transparent if it outside of the glyph
                        bitmap.SetPixel(j, i, Color.Transparent);
                    }
                    else
                    {
                        // set pixel to black or white depending on glyph value
                        bitmap.SetPixel(j, i, (glyph.Data[yCell, xCell] == 0) ? Color.Black : Color.White);
                    }
                }
            }

            return bitmap;
        }
Ejemplo n.º 30
0
        public static byte[] Compare(/*Bitmap _first, Bitmap _second*/)
        {
            Bitmap first = new Bitmap(@"C:\Users\netstalkerrr\Documents\Visual Studio 2013\Projects\testAppImage\img\1.png");
            Bitmap second = new Bitmap(@"C:\Users\netstalkerrr\Documents\Visual Studio 2013\Projects\testAppImage\img\2.png");
            Bitmap difference = new Bitmap(first.Width, first.Height);
            for (int i = 0; i < first.Width; i++)
            {
                for (int j = 0; j < first.Height; j++)
                {
                    int r1 = second.GetPixel(i, j).R;
                    int g1 = second.GetPixel(i, j).G;
                    int b1 = second.GetPixel(i, j).B;
                    int r2 = first.GetPixel(i, j).R;
                    int g2 = first.GetPixel(i, j).G;
                    int b2 = first.GetPixel(i, j).B;

                    if (r1 != r2 && g1 != g2 && b1 != b2)
                    {
                        difference.SetPixel(i, j, Color.Red);
                    }
                    else
                        difference.SetPixel(i, j, first.GetPixel(i, j));
                }
            }
            var bitmapBytes = BitmapToBytes(difference);

            return bitmapBytes;
        }
Ejemplo n.º 31
0
    public void SaveBytesToImg()
    {
        print(Application.streamingAssetsPath + @"\tes2.bmp");
        print(Application.dataPath + "/tes2.bmp");
        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(size, size);

        for (int i = 0; i < tiles.Count; i++)
        {
            System.Drawing.Color c = System.Drawing.Color.FromArgb(tiles[i].GetColor32().r, tiles[i].GetColor32().g, tiles[i].GetColor32().b);
            bmp.SetPixel((int)tiles[i].transform.position.x, (int)tiles[i].transform.position.y, c);
        }
        bmp.Save(Application.dataPath + "/Resources/Levels/test.png", System.Drawing.Imaging.ImageFormat.Png);
    }
Ejemplo n.º 32
0
    void Start()
    {
        // get maintexture from source renderer
        var sourceTexture = (Texture2D)sourceRenderer.material.mainTexture;

        // create system bitmap
        System.Drawing.Bitmap accordImage = new System.Drawing.Bitmap(sourceTexture.width, sourceTexture.height);

        // copy our texture pixels to that system bitmap
        for (int x = 0; x < accordImage.Width; x++)
        {
            for (int y = 0; y < accordImage.Height; y++)
            {
                var c  = (Color32)sourceTexture.GetPixel(x, y);
                var nc = System.Drawing.Color.FromArgb(c.r, c.g, c.b, c.a);
                accordImage.SetPixel(x, y, nc);
            }
        }


        // These 2 lines are the only Accord.NET code used here, create filter and then apply it to bitmap
        IFilter gaussianFilter     = new GaussianBlur(2.0, 20);
        var     resultsAccordImage = gaussianFilter.Apply(accordImage);


        // copy result pixels into our color32 array from system.drawing.bitmap
        var colors = new Color32[resultsAccordImage.Width * resultsAccordImage.Height];

        for (int x = 0; x < resultsAccordImage.Width; x++)
        {
            for (int y = 0; y < resultsAccordImage.Height; y++)
            {
                var c = resultsAccordImage.GetPixel(x, y);
                colors[y * resultsAccordImage.Width + x] = new Color32(c.A, c.R, c.G, c.B); // colors are flipped in System.Drawing.Color
            }
        }

        // create new results texture from that color32 array
        var targetTexture = new Texture2D(sourceTexture.width, sourceTexture.height, sourceTexture.format, false);

        targetTexture.SetPixels32(colors);
        targetTexture.Apply(false);

        // assign it to another object
        targetRenderer.material.mainTexture = targetTexture;
    }
Ejemplo n.º 33
0
        /// <summary>
        /// 获取QR内容
        /// </summary>
        /// <param name="model">编码模式</param>
        /// <param name="scale">比例:二维码图片大小</param>
        /// <param name="version">版本:决定图片复杂度及内容多少</param>
        /// <param name="correction">纠错</param>
        /// <param name="imageFormat"></param>
        /// <returns></returns>
        public byte[] GetQRContent(Leigh.Wen.QRCode.Libs.QRCodeEncoder.ENCODE_MODE model, int scale, int version, Leigh.Wen.QRCode.Libs.QRCodeEncoder.ERROR_CORRECTION correction, ImageFormat imageFormat)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                try
                {
                    QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();

                    qrCodeEncoder.QRCodeEncodeMode = model;

                    qrCodeEncoder.QRCodeScale = scale;

                    qrCodeEncoder.QRCodeVersion = version;

                    qrCodeEncoder.QRCodeErrorCorrect = correction;

                    qrCodeEncoder.QRCodeBackgroundColor = _backColor;

                    qrCodeEncoder.QRCodeForegroundColor = _foreColor;

                    System.Drawing.Bitmap bmp = qrCodeEncoder.Encode(_message);

                    if (bmp != null && bmp.Width > 0)
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(_iconFilePath))
                            {
                                Bitmap iconBitMap = new Bitmap(_iconFilePath);
                                if (iconBitMap != null && iconBitMap.Width > 0)
                                {
                                    int left = (bmp.Width - iconBitMap.Width) / 2;
                                    int top  = (bmp.Height - iconBitMap.Height) / 2;
                                    for (int i = 0; i < bmp.Width; i++)
                                    {
                                        for (int j = 0; j < bmp.Height; j++)
                                        {
                                            if (i >= left && i < left + iconBitMap.Width)
                                            {
                                                if (j >= top && j < top + iconBitMap.Height)
                                                {
                                                    var color = iconBitMap.GetPixel(i - left, j - top);

                                                    if (color.A != Color.Transparent.A)
                                                    {
                                                        bmp.SetPixel(i, j, iconBitMap.GetPixel(i - left, j - top));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch { }
                    }
                    bmp.Save(ms, imageFormat);
                }
                catch { }
                _QRContent = ms.ToArray();
                return(_QRContent);
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Paint the density image in the layer.
        /// </summary>
        /// <param name="gfrx">The graphics context painting in.</param>
        /// <param name="gl">The layer painting in.</param>
        /// <param name="plotObject">The data to plot.</param>
        public void Paint(Graphics gfrx, IPlotArea gl, object plotObject) // plots the curve with the choosen style
        {
            if (!(plotObject is XYZMeshedColumnPlotData))
            {
                return; // we cannot plot any other than a TwoDimMeshDataAssociation now
            }
            XYZMeshedColumnPlotData myPlotAssociation = (XYZMeshedColumnPlotData)plotObject;

            Altaxo.Data.INumericColumn xColumn = myPlotAssociation.XColumn as Altaxo.Data.INumericColumn;
            Altaxo.Data.INumericColumn yColumn = myPlotAssociation.YColumn as Altaxo.Data.INumericColumn;

            if (null == xColumn || null == yColumn)
            {
                return; // this plotitem is only for x and y double columns
            }
            //double layerWidth = gl.Size.Width;
            //double layerHeight = gl.Size.Height;

            int cols = myPlotAssociation.ColumnCount;
            int rows = myPlotAssociation.RowCount;


            if (cols <= 0 || rows <= 0)
            {
                return; // we cannot show a picture if one length is zero
            }
            // there is a need for rebuilding the bitmap only if the data are invalid for some reason
            if (!m_bCachedDataValid)
            {
                System.Diagnostics.Trace.WriteLine("DensityImagePlotStyle.Paint, calculate image data...");

                // look if the image has the right dimensions
                if (null == m_Image || m_Image.Width != cols || m_Image.Height != rows)
                {
                    if (null != m_Image)
                    {
                        m_Image.Dispose();
                    }

                    // please notice: the horizontal direction of the image is related to the row index!!! (this will turn the image in relation to the table)
                    // and the vertical direction of the image is related to the column index
                    m_Image = new System.Drawing.Bitmap(rows, cols, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                }

                // now we can fill the image with our data

                NumericalBoundaries pb = m_ScalingStyle == ScalingStyle.Logarithmic ? (NumericalBoundaries) new PositiveFiniteNumericalBoundaries() :  (NumericalBoundaries) new FiniteNumericalBoundaries();
                myPlotAssociation.SetVBoundsFromTemplate(pb); // ensure that the right v-boundary type is set
                myPlotAssociation.MergeVBoundsInto(pb);

                double vmin       = double.IsNaN(this.m_RangeFrom) ? pb.LowerBound : Math.Max(pb.LowerBound, this.m_RangeFrom);
                double vmax       = double.IsNaN(this.m_RangeTo) ? pb.UpperBound : Math.Min(pb.UpperBound, this.m_RangeTo);
                double lowerBound = vmin;
                double upperBound = vmax;

                if (this.m_ScalingStyle == ScalingStyle.Logarithmic)
                {
                    // Ensure that min and max >0
                    vmin = lowerBound = Math.Max(lowerBound, double.Epsilon);
                    vmax = upperBound = Math.Max(lowerBound, upperBound); // lowerBound is ok, to ensure that upperBound>=lowerBound

                    vmin = Math.Log(vmin);
                    vmax = vmax > 0 ? Math.Log(vmax) : vmin;
                }

                // double vmid = (vmin+vmax)*0.5;
                double vscal = vmax <= vmin ? 1 : 255.0 / (vmax - vmin);

                int r, g, b;

                for (int i = 0; i < cols; i++)
                {
                    Altaxo.Data.INumericColumn col = myPlotAssociation.DataColumns[i] as Altaxo.Data.INumericColumn;
                    if (null == col)
                    {
                        continue;
                    }

                    for (int j = 0; j < rows; j++)
                    {
                        double val = col[j];
                        if (double.IsNaN(val))
                        {
                            m_Image.SetPixel(j, cols - i - 1, m_ColorInvalid); // invalid pixels are transparent
                        }
                        else if (val < lowerBound)
                        {
                            m_Image.SetPixel(j, cols - i - 1, m_ColorBelow); // below the lower bound
                        }
                        else if (val > upperBound)
                        {
                            m_Image.SetPixel(j, cols - i - 1, m_ColorAbove); // above the upper bound
                        }
                        else // a valid value
                        {
                            double relval;
                            // calculate a relative value between 0 and 255 from the borders and the scaling style
                            if (this.m_ScalingStyle == ScalingStyle.Logarithmic)
                            {
                                relval = (Math.Log(val) - vmin) * vscal;
                            }
                            else // ScalingStyle is linear
                            {
                                relval = (val - vmin) * vscal;
                            }


                            r = ((int)(Math.Abs(relval))) % 256;
                            g = ((int)(Math.Abs(relval + relval))) % 256;
                            b = ((int)(Math.Abs(255 - relval))) % 256;
                            m_Image.SetPixel(j, cols - i - 1, System.Drawing.Color.FromArgb(r, g, b));
                        }
                    } // for all pixel of a column
                }     // for all columns


                m_bCachedDataValid = true; // now the bitmap is valid
            }


            double x_rel_left  = gl.XAxis.PhysicalVariantToNormal(xColumn[0]);
            double x_rel_right = gl.XAxis.PhysicalVariantToNormal(xColumn[rows - 1]);

            double y_rel_bottom = gl.YAxis.PhysicalVariantToNormal(yColumn[0]);
            double y_rel_top    = gl.YAxis.PhysicalVariantToNormal(yColumn[cols - 1]);

            double xleft, xright, ytop, ybottom;

            if (gl.CoordinateSystem.LogicalToLayerCoordinates(new Logical3D(x_rel_left, y_rel_top), out xleft, out ytop) &&
                gl.CoordinateSystem.LogicalToLayerCoordinates(new Logical3D(x_rel_right, y_rel_bottom), out xright, out ybottom))
            {
                GraphicsState savedGraphicsState = gfrx.Save();

                if (this.m_ClipToLayer)
                {
                    gfrx.Clip = gl.CoordinateSystem.GetRegion();
                }

                gfrx.DrawImage(m_Image, (float)xleft, (float)ytop, (float)(xright - xleft), (float)(ybottom - ytop));

                gfrx.Restore(savedGraphicsState);
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// 根据GenerateYZM方法生成的随机数,生成验证码图片
        /// </summary>
        /// <returns></returns>
        public Stream CreateYZM()
        {
            if (string.IsNullOrEmpty(_rancode))
            {
                return(null);
            }
            Matrix m       = new Matrix();       //定义几何变换
            Bitmap charbmp = new Bitmap(90, 30); //图片前景色,即生成背景透明的随机字符串图片

            //定义字体
            Font[] fonts =
            {
                                                       new Font(new FontFamily("Times New Roman"), 17, FontStyle.Regular),
                                                       new Font(new FontFamily("Georgia"),         17, FontStyle.Regular),
                                                       new Font(new FontFamily("Arial"),           17, FontStyle.Regular),
                                                       new Font(new FontFamily("Comic Sans MS"),   17, FontStyle.Regular)
                                                    
            };


            //定义图片背景色
            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((_rancode.Length * 22.5)), 30);

            //开始描绘
            Graphics g = Graphics.FromImage(image);

            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;

            //定义背景色为白色
            g.Clear(Color.White);
            try
            {
                Random random = new Random();        //生成随机生成器
                g.Clear(Color.White);                //清空图片背景色
                for (int i = 0; i < 2; i++)
                {
                                                         //画图片的背景噪音线,i表示画多少条噪音线
                    {
                        int x1 = random.Next(image.Width);
                        int x2 = random.Next(image.Width);
                        int y1 = random.Next(image.Height);
                        int y2 = random.Next(image.Height);

                        g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
                    }
                }



                //开始描绘前景图
                Graphics charg = Graphics.FromImage(charbmp);

                SolidBrush drawBrush = new SolidBrush(Color.FromArgb(random.Next(101), random.Next(101), random.Next(101)));
                float      charx     = -18;

                //把随机字符串,逐个写入前景图
                for (int i = 0; i < _rancode.Length; i++)
                {
                    m.Reset();
                    m.RotateAt(random.Next(31) - 25, new PointF(random.Next(4) + 7, random.Next(4) + 7));

                    charg.Clear(Color.Transparent);//定义前景图为透明
                    charg.Transform = m;
                    //定义前景色为黑色
                    drawBrush.Color = Color.Black;

                    charx = charx + 20 + random.Next(3);
                    PointF drawPoint = new PointF(charx, 0.1F);
                    charg.DrawString(_rancode[i].ToString(), fonts[random.Next(fonts.Length)], drawBrush, new PointF(0, 0));//通过特定的几何变换,旋转或变形随机字符,写入前景图

                    charg.ResetTransform();

                    g.DrawImage(charbmp, drawPoint);
                }


                //画图片的前景噪音点
                for (int i = 0; i < 25; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

                //保存
                Stream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Bmp);
                return(stream);
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
        /// <summary>
        /// To plot the bitmap png file for the Hamming Distance of two learnings
        /// </summary>
        /// <param name="twoDimArray">The Hamming Distance array</param>
        /// <param name="width">Width of the array</param>
        /// <param name="height">Height of the array</param>
        /// <param name="filePath">Path where the generated file to be placed</param>
        /// <param name="text">Test to be written on the top left side of the generated file</param>
        public static void DrawBitmapHamming(int[,] twoDimArray, int width, int height, String filePath, string text = null)
        {
            int w = twoDimArray.GetLength(0);
            int h = twoDimArray.GetLength(1);

            var scale = width / w;

            if (scale * w < width)
            {
                scale++;
            }

            System.Drawing.Bitmap myBitmap = new System.Drawing.Bitmap(w * scale, h * scale);
            ColorConverter        convert  = new ColorConverter();
            int k = 0;

            for (int Xcount = 0; Xcount < w; Xcount++)
            {
                for (int Ycount = 0; Ycount < h; Ycount++)
                {
                    for (int padX = 0; padX < scale; padX++)
                    {
                        for (int padY = 0; padY < scale; padY++)
                        {
                            if (twoDimArray[Xcount, Ycount] == 100)
                            {
                                //myBitmap.SetPixel(Xcount, Ycount, System.Drawing.Color.Yellow); // HERE IS YOUR LOGIC
                                myBitmap.SetPixel(Xcount * scale + padX, Ycount * scale + padY, Color.White); // HERE IS YOUR LOGIC
                                k++;
                            }
                            else if (twoDimArray[Xcount, Ycount] >= 90)
                            {
                                myBitmap.SetPixel(Xcount * scale + padX, Ycount * scale + padY, (Color)convert.ConvertFromString("#e6e6e6")); // HERE IS YOUR LOGIC
                                k++;
                            }
                            else if (twoDimArray[Xcount, Ycount] >= 80)
                            {
                                myBitmap.SetPixel(Xcount * scale + padX, Ycount * scale + padY, (Color)convert.ConvertFromString("#d9d9d9")); // HERE IS YOUR LOGIC
                                k++;
                            }
                            else if (twoDimArray[Xcount, Ycount] >= 70)
                            {
                                myBitmap.SetPixel(Xcount * scale + padX, Ycount * scale + padY, (Color)convert.ConvertFromString("#cccccc")); // HERE IS YOUR LOGIC
                                k++;
                            }
                            else if (twoDimArray[Xcount, Ycount] >= 60)
                            {
                                myBitmap.SetPixel(Xcount * scale + padX, Ycount * scale + padY, (Color)convert.ConvertFromString("#bfbfbf")); // HERE IS YOUR LOGIC
                                k++;
                            }
                            else if (twoDimArray[Xcount, Ycount] >= 50)
                            {
                                myBitmap.SetPixel(Xcount * scale + padX, Ycount * scale + padY, (Color)convert.ConvertFromString("#a6a6a6")); // HERE IS YOUR LOGIC
                                k++;
                            }
                            else if (twoDimArray[Xcount, Ycount] >= 40)
                            {
                                myBitmap.SetPixel(Xcount * scale + padX, Ycount * scale + padY, (Color)convert.ConvertFromString("#8c8c8c")); // HERE IS YOUR LOGIC
                                k++;
                            }
                            else if (twoDimArray[Xcount, Ycount] >= 30)
                            {
                                myBitmap.SetPixel(Xcount * scale + padX, Ycount * scale + padY, (Color)convert.ConvertFromString("#737373")); // HERE IS YOUR LOGIC
                                k++;
                            }
                            else if (twoDimArray[Xcount, Ycount] >= 20)
                            {
                                myBitmap.SetPixel(Xcount * scale + padX, Ycount * scale + padY, (Color)convert.ConvertFromString("#595959")); // HERE IS YOUR LOGIC
                                k++;
                            }
                            else if (twoDimArray[Xcount, Ycount] >= 10)
                            {
                                myBitmap.SetPixel(Xcount * scale + padX, Ycount * scale + padY, (Color)convert.ConvertFromString("#333333")); // HERE IS YOUR LOGIC
                                k++;
                            }
                            else
                            {
                                //myBitmap.SetPixel(Xcount, Ycount, System.Drawing.Color.Black); // HERE IS YOUR LOGIC
                                myBitmap.SetPixel(Xcount * scale + padX, Ycount * scale + padY, (Color)convert.ConvertFromString("#000000")); // HERE IS YOUR LOGIC
                                k++;
                            }
                        }
                    }
                }
            }

            Graphics g          = Graphics.FromImage(myBitmap);
            var      fontFamily = new FontFamily(System.Drawing.Text.GenericFontFamilies.SansSerif);

            g.DrawString(text, new Font(fontFamily, 32), SystemBrushes.Control, new PointF(0, 0));

            myBitmap.Save(filePath, ImageFormat.Png);
        }
Ejemplo n.º 37
0
        public byte[] CreateCheckCodeByteArray()
        {
            string checkCode = this._checkCode;

            if (string.IsNullOrWhiteSpace(checkCode))
            {
                switch (_codetype)
                {
                case CodeType.字母:
                    checkCode = GenerateAlphas();
                    break;

                case CodeType.数字:
                    checkCode = GenerateNumbers();
                    break;

                case CodeType.字母数字:
                    checkCode = GenerateCharacters();
                    break;

                default:
                    checkCode = GenerateAlphas();
                    break;
                }
                this._checkCode = checkCode;
            }



            if (checkCode == null || checkCode.Trim() == String.Empty)
            {
                return(null);
            }
            Bitmap   image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * _jianju)), (int)_height);
            Graphics g     = Graphics.FromImage(image);

            try
            {
                Random random = new Random();
                g.Clear(Color.White);
                // 画图片的背景噪音线
                for (int i = 0; i < 18; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.FromArgb(random.Next()), 1), x1, y1, x2, y2);
                }
                Font font = new System.Drawing.Font("Times New Roman", 14, System.Drawing.FontStyle.Bold);
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                if (_codetype != CodeType.Alphas)
                {
                    for (int i = 0; i < checkCode.Length; i++)
                    {
                        g.DrawString(checkCode.Substring(i, 1), font, brush, 2 + i * _jianju, 1);
                    }
                }
                else
                {
                    g.DrawString(checkCode, font, brush, 2, 2);
                }

                // 画图片的前景噪音点

                for (int i = 0; i < 150; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                // 画图片的波形滤镜效果

                if (_codetype != CodeType.Alphas)
                {
                    image = TwistImage(image, true, 3, 1);
                }
                // 画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                using (MemoryStream ms = new System.IO.MemoryStream())
                {
                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                    return(ms.ToArray());
                }
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
Ejemplo n.º 38
0
        public static byte[] CreateCodeImage(
            int pInt_length    = 4,
            CodeType pStr_Type = CodeType.Numeral,
            string checkCode   = null)
        {
            if (string.IsNullOrEmpty(checkCode))
            {
                checkCode = GetRandomData(pStr_Type, pInt_length);
            }
            int Int_fontSize = 15;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap(checkCode.Length * Int_fontSize + 5, (int)(Int_fontSize * 1.6));
            Graphics g = Graphics.FromImage(image);

            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的背景噪音线25
                for (int i = 0; i < 4; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.FromArgb(150, 150, 150), 1), x1, y1, x2, y2);
                }

                int Int_Count_X = 0, Int_Count_Y = 0;
                for (int Int_Count_I = 0; Int_Count_I < checkCode.Length; Int_Count_I++)
                {
                    Font font = new System.Drawing.Font("Arial", Int_fontSize, FontStyle.Regular);
                    //System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                    System.Drawing.SolidBrush brush = new SolidBrush(Color.FromArgb(80, 80, 80));
                    Int_Count_X = Int_Count_I * Int_fontSize;
                    Int_Count_Y = random.Next(4);
                    g.DrawString(checkCode.Substring(Int_Count_I, 1), font, brush, Int_Count_X, Int_Count_Y);
                }
                //扭曲图片
                float Twist1, Twist2;
                Twist1 = 0;
                Twist2 = 0;

                image = TwistImage(image, true, -Twist1, -Twist2);
                image = TwistImage(image, false, Twist1, Twist2); //多扭曲几次也没关系,只是消耗服务器资源多些;

                //画图片的前景噪音点
                for (int i = 0; i < 20; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

                //画图片的边框线Silver
                g.DrawRectangle(new Pen(Color.Black), 0, 0, image.Width - 1, image.Height - 1);

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                return(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
Ejemplo n.º 39
0
        public Stream CreateCheckCodeImage(ref string checkCode)
        {
            switch (_codetype)
            {
            case CodeType.Alphas:
                checkCode = GenerateAlphas();
                break;

            case CodeType.Numbers:
                checkCode = GenerateNumbers();
                break;

            case CodeType.Characters:
                checkCode = GenerateCharacters();
                break;

            default:
                checkCode = GenerateAlphas();
                break;
            }
            this._checkCode = checkCode;
            MemoryStream ms = null;

            if (checkCode == null || checkCode.Trim() == String.Empty)
            {
                return(null);
            }
            Bitmap   image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * _jianju)), (int)_height);
            Graphics g     = Graphics.FromImage(image);

            try
            {
                Random random = new Random();
                g.Clear(System.Drawing.Color.FromArgb(255, 234, 153, 222));
                // 画图片的背景噪音线
                for (int i = 0; i < 22; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new System.Drawing.Pen(System.Drawing.Color.FromArgb(random.Next()), 1), x1, y1, x2, y2);
                }
                Font font = new System.Drawing.Font("Times New Roman", 12, System.Drawing.FontStyle.Regular);
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true);
                if (_codetype != CodeType.Words)
                {
                    for (int i = 0; i < checkCode.Length; i++)
                    {
                        g.DrawString(checkCode.Substring(i, 1), font, brush, 2 + i * _jianju, 1);
                    }
                }
                else
                {
                    g.DrawString(checkCode, font, brush, 2, 2);
                }
                // 画图片的前景噪音点
                for (int i = 0; i < 30; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next()));
                }
                // 画图片的波形滤镜效果
                if (_codetype != CodeType.Words)
                {
                    image = TwistImage(image, true, 3, 1);
                }
                // 画图片的边框线

                //g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            }

            finally
            {
                g.Dispose();
                image.Dispose();
            }
            return(ms);
        }
Ejemplo n.º 40
0
        protected byte[] CreateCheckCodeImage(string[] checkCode)
        {
            if (checkCode == null || checkCode.Length <= 0)
            {
                return(null);
            }

            System.Drawing.Bitmap   image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 32.5)), 30);
            System.Drawing.Graphics g     = Graphics.FromImage(image);


            Random random = new Random();

            //清空图片背景色
            g.Clear(Color.White);

            //画图片的背景噪音线
            for (int i = 0; i < 20; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);

                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }

            //定义颜色
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
            //定义字体
            string[] f = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };

            for (int k = 0; k <= checkCode.Length - 1; k++)
            {
                int cindex = random.Next(7);
                int findex = random.Next(5);

                Font drawFont = new Font(f[findex], 18, (System.Drawing.FontStyle.Bold));



                SolidBrush drawBrush = new SolidBrush(c[cindex]);

                float x      = 5.0F;
                float y      = 0.0F;
                float width  = 20.0F;
                float height = 25.0F;
                int   sjx    = random.Next(10);
                int   sjy    = random.Next(image.Height - (int)height);

                RectangleF drawRect = new RectangleF(x + sjx + (k * 25), y + sjy, width, height);

                StringFormat drawFormat = new StringFormat();
                drawFormat.Alignment = StringAlignment.Center;

                g.DrawString(checkCode[k], drawFont, drawBrush, drawRect, drawFormat);
            }

            //画图片的前景噪音点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);

                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            //画图片的边框线
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, ImageFormat.Jpeg);
            return(ms.ToArray());
        }
Ejemplo n.º 41
0
        /// <summary>
        /// 功能:返回验证码图片
        /// </summary>
        /// <returns></returns>
        public ActionResult ValidateImg()
        {
            Color color1 = new Color();
            //---------产生随机6位字符串
            Random ran = new Random();

            char[] c  = new char[62];
            char[] ou = new char[6];
            int    n  = 0;

            for (int i = 65; i < 91; i++)
            {
                c[n] = (char)i;
                n++;
            }
            for (int j = 97; j < 123; j++)
            {
                c[n] = (char)j;
                n++;
            }
            for (int k = 48; k < 58; k++)
            {
                c[n] = (char)k;
                n++;
            }
            foreach (char ch in c)
            {
                Console.WriteLine(ch);
            }
            string outcode = "";

            for (int h = 0; h < 6; h++)
            {
                ou[h]    = c[ran.Next(62)];
                outcode += ou[h].ToString();
            }
            //
            Session["ValidateImgCode"] = outcode;

            //1.创建一个新的图片,大小为(输入的字符串的长度*12),22
            System.Drawing.Bitmap bmap = new System.Drawing.Bitmap(outcode.Length * 18, 25);

            //2.定义画图面板,基于创建的新图片来创建
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmap);

            //3.由于默认的画图面板背景是黑色,所有使用clear方法把背景清除,同时把背景颜色设置为白色
            g.Clear(System.Drawing.Color.White);

            // 画图片的背景噪音线
            for (int i = 0; i < 25; i++)
            {
                int x1 = ran.Next(bmap.Width);
                int x2 = ran.Next(bmap.Width);
                int y1 = ran.Next(bmap.Height);
                int y2 = ran.Next(bmap.Height);
                g.DrawLine(new Pen(color1), x1, y1, x2, y2);
            }

            // 画图片的前景噪音线
            for (int i = 0; i < 100; i++)
            {
                int x = ran.Next(bmap.Width);
                int y = ran.Next(bmap.Height);
                bmap.SetPixel(x, y, Color.FromArgb(ran.Next()));
            }

            //4.使用DrawString 方法把要输出的字符串输出到画板上。输出的字符从参数(outcode)内获得。
            Font font = new Font("Arial", 14, FontStyle.Bold | FontStyle.Italic);
            LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, bmap.Width, bmap.Height), Color.Blue, Color.DarkRed, 1.2f, true);

            g.DrawString(outcode, font, brush, 0, 0);

            //5.定义一个内存流,把新创建的图片保存到内存流内,这样就不用保存到磁盘上,提高了速度。
            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            //6.把新创建的图片保存到内存流中,格式为jpeg的类型
            bmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            //7.输出这张图片,由于此页面的 ContentType="image/jpeg" 所以会输出图片到客户端。同时输出是以字节输出,所以要把内存流转换为字节序列,使用ToArray()方法。
            Response.BinaryWrite(ms.ToArray());
            return(View());
        }
    private void CreateCheckCodeImage(string checkCode)
    {
        if (checkCode == null || checkCode.Trim() == String.Empty)
        {
            return;
        }

        System.Drawing.Bitmap   image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 15.0 + 40)), 23);
        System.Drawing.Graphics g     = System.Drawing.Graphics.FromImage(image);

        try
        {
            //生成随机生成器
            Random random = new Random();

            //清空图片背景色
            g.Clear(System.Drawing.Color.White);

            //画图片的背景噪音线
            for (int i = 0; i < 25; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);

                g.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);
            }

            System.Drawing.Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true);

            int cySpace = 16;
            for (int i = 0; i < validateCodeCount; i++)
            {
                g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1);
            }

            //画图片的前景噪音点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);

                image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next()));
            }

            //画图片的边框线
            g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/Gif";
            Response.BinaryWrite(ms.ToArray());
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }
        /// <summary>
        /// draw the difference array during the learning of the spatial pooler
        /// <br>based on the value of the elements</br>
        /// <para>see --> AddArray()</para>
        /// </summary>
        /// <param name="twoDimArray"> diffArray</param>
        /// <param name="scale">length of one square pixel</param>
        /// <param name="filePath"></param>
        /// <param name="sameColor0">Value 0</param>
        /// <param name="sameColor1">Value 3</param>
        /// <param name="diffColorfrom1">Value 1</param>
        /// <param name="diffColorfrom2">Value 2</param>
        /// <param name="text">included text in the bitmap</param>
        public static void DrawdiffArray(
            int[,] twoDimArray,
            int scale,
            String filePath,
            Color sameColor0,
            Color sameColor1,
            Color diffColorfrom1,
            Color diffColorfrom2,
            string text = null)
        {
            int w = twoDimArray.GetLength(0);
            int h = twoDimArray.GetLength(1);

            System.Drawing.Bitmap myBitmap = new System.Drawing.Bitmap(w * scale, h * scale);
            int k = 0;

            for (int Xcount = 0; Xcount < w; Xcount++)
            {
                for (int Ycount = 0; Ycount < h; Ycount++)
                {
                    for (int padX = 0; padX < scale; padX++)
                    {
                        for (int padY = 0; padY < scale; padY++)
                        {
                            // If '1' in the first array.
                            if (twoDimArray[Xcount, Ycount] == 1)
                            {
                                //Coloring the pixel in case its value is 1
                                myBitmap.SetPixel(Xcount * scale + padX, Ycount * scale + padY, diffColorfrom1);
                                k++;
                            }
                            // If '1' in second array
                            else if (twoDimArray[Xcount, Ycount] == 2)
                            {
                                //Coloring the pixel in case its value is 2
                                myBitmap.SetPixel(Xcount * scale + padX, Ycount * scale + padY, diffColorfrom2);
                                k++;
                            }
                            // If same value in both arrays = overlap.
                            else if (twoDimArray[Xcount, Ycount] == 3)
                            {
                                //Coloring the pixel in case its value is 3
                                myBitmap.SetPixel(Xcount * scale + padX, Ycount * scale + padY, sameColor1);
                                k++;
                            }
                            else
                            {
                                //Coloring the pixel in case its value is 0
                                myBitmap.SetPixel(Xcount * scale + padX, Ycount * scale + padY, sameColor0);
                                k++;
                            }
                        }
                    }
                }
            }
            //inserting the text
            Graphics g          = Graphics.FromImage(myBitmap);
            var      fontFamily = new FontFamily(System.Drawing.Text.GenericFontFamilies.SansSerif);

            g.DrawString(text, new Font(fontFamily, 32), SystemBrushes.Control, new PointF(0, 0));

            myBitmap.Save(filePath, ImageFormat.Png);
        }