Example #1
2
 public Terrain(Device device, String texture, int pitch, Renderer renderer)
 {
     HeightMap = new System.Drawing.Bitmap(@"Data/Textures/"+texture);
     WaterShader = new WaterShader(device);
     TerrainShader = new TerrainShader(device);
     _width = HeightMap.Width-1;
     _height = HeightMap.Height-1;
     _pitch = pitch;
     _terrainTextures = new ShaderResourceView[4];
     _terrainTextures[0] = new Texture(device, "Sand.png").TextureResource;
     _terrainTextures[1] = new Texture(device, "Grass.png").TextureResource;
     _terrainTextures[2] = new Texture(device, "Ground.png").TextureResource;
     _terrainTextures[3] = new Texture(device, "Rock.png").TextureResource;
     _reflectionClippingPlane = new Vector4(0.0f, 1.0f, 0.0f, 0.0f);
     _refractionClippingPlane = new Vector4(0.0f, -1.0f, 0.0f, 0.0f);
     _noClippingPlane = new Vector4(0.0f, 1.0f, 0.0f, 10000);
     _reflectionTexture = new RenderTexture(device, renderer.ScreenSize);
     _refractionTexture = new RenderTexture(device, renderer.ScreenSize);
     _renderer = renderer;
     _bitmap = new Bitmap(device,_refractionTexture.ShaderResourceView,renderer.ScreenSize, new Vector2I(100, 100), 0);
     _bitmap.Position = new Vector2I(renderer.ScreenSize.X - 100, 0);
     _bitmap2 = new Bitmap(device, _reflectionTexture.ShaderResourceView, renderer.ScreenSize, new Vector2I(100, 100), 0);
     _bitmap2.Position = new Vector2I(renderer.ScreenSize.X - 100, 120);
     _bumpMap = _renderer.TextureManager.Create("OceanWater.png");
     _skydome = new ObjModel(device, "skydome.obj", renderer.TextureManager.Create("Sky.png"));
     BuildBuffers(device);
     WaveTranslation = new Vector2(0,0);
 }
Example #2
0
 public Eagle()
 {
     name = "Eagle";
     family = "Carnivore";
     food = "Fish";
     image = new System.Drawing.Bitmap("eagle.jpg");
 }
Example #3
0
		// <summary>
		// Constructor.  Create and populate an image list
		// </summary>
		public TriStateTreeView() : base()
		{
			StateImageList = new System.Windows.Forms.ImageList();

			// populate the image list, using images from the System.Windows.Forms.CheckBoxRenderer class
			for (int i = 0; i < 3; i++)
			{
				// Create a bitmap which holds the relevent check box style
				// see http://msdn.microsoft.com/en-us/library/ms404307.aspx and http://msdn.microsoft.com/en-us/library/system.windows.forms.checkboxrenderer.aspx

				System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(16, 16);
				System.Drawing.Graphics chkGraphics = System.Drawing.Graphics.FromImage(bmp);
				switch ( i )
				{
					// 0,1 - offset the checkbox slightly so it positions in the correct place
					case 0:
						System.Windows.Forms.CheckBoxRenderer.DrawCheckBox(chkGraphics, new System.Drawing.Point(0, 1), System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal);
						break;
					case 1:
						System.Windows.Forms.CheckBoxRenderer.DrawCheckBox(chkGraphics, new System.Drawing.Point(0, 1), System.Windows.Forms.VisualStyles.CheckBoxState.CheckedNormal);
						break;
					case 2:
						System.Windows.Forms.CheckBoxRenderer.DrawCheckBox(chkGraphics, new System.Drawing.Point(0, 1), System.Windows.Forms.VisualStyles.CheckBoxState.MixedNormal);
						break;
				}

				StateImageList.Images.Add(bmp);
			}
		}
Example #4
0
        public System.Drawing.Bitmap ToBitmap()
        {
            #if WindowsCE
             var bmp = new System.Drawing.Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
             var bmpData = bmp.LockBits(
            new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height),
            System.Drawing.Imaging.ImageLockMode.WriteOnly,
            System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            #else
             var bmp = new System.Drawing.Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
             bmp.SetResolution(96, 96);
             var bmpData = bmp.LockBits(
            new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height),
            System.Drawing.Imaging.ImageLockMode.WriteOnly,
            System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            #endif
             try
             {
            //Copy the data from the byte array into BitmapData.Scan0
            System.Runtime.InteropServices.Marshal.Copy(Pixels, 0, bmpData.Scan0, Pixels.Length);
             }
             finally
             {
            //Unlock the pixels
            bmp.UnlockBits(bmpData);
             }

             return bmp;
        }
Example #5
0
 public Wolf()
 {
     name = "Wolf";
     family = "Carnivore";
     food = "Rabbits";
     image = new System.Drawing.Bitmap("wolf.jpg");
 }
Example #6
0
// ---------------------------------------------------------------------------
/*
 * you DO NOT want to use classes within the System.Drawing namespace to
 * manipulate image files in ASP.NET applications, see the warning here:
 * http://msdn.microsoft.com/en-us/library/system.drawing.aspx
*/
    public byte[] CreatePdf(long quality) {
      using (MemoryStream msDoc = new MemoryStream()) {
        Image img = null;
        using (System.Drawing.Bitmap dotnetImg = 
            new System.Drawing.Bitmap(RESOURCE)) 
        {
          // set codec to jpeg type => jpeg index codec is "1"
          System.Drawing.Imaging.ImageCodecInfo codec = 
          System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
          // set parameters for image quality
          System.Drawing.Imaging.EncoderParameters eParams = 
            new System.Drawing.Imaging.EncoderParameters(1);
          eParams.Param[0] = 
            new System.Drawing.Imaging.EncoderParameter(
              System.Drawing.Imaging.Encoder.Quality, quality
          );
          using (MemoryStream msImg = new MemoryStream()) {
            dotnetImg.Save(msImg, codec, eParams);
            msImg.Position = 0;
            img = Image.GetInstance(msImg);
            img.SetAbsolutePosition(15, 15);
            // step 1
            using (Document document = new Document()) {
              // step 2
              PdfWriter.GetInstance(document, msDoc);
              // step 3
              document.Open();
              // step 4
              document.Add(img);
            }
          }
        }
        return msDoc.ToArray();
      }
    }
Example #7
0
        public static System.Drawing.SizeF MeasureDisplayString(System.Drawing.Graphics graphics, string text, System.Drawing.Font font)
        {
            const int width = 32;

            System.Drawing.Bitmap   bitmap = new System.Drawing.Bitmap (width, 1, graphics);
            System.Drawing.SizeF    size   = graphics.MeasureString (text, font);
            System.Drawing.Graphics anagra = System.Drawing.Graphics.FromImage (bitmap);

            int measured_width = (int) size.Width;

            if (anagra != null)
            {
                anagra.Clear (System.Drawing.Color.White);
                anagra.DrawString (text+"|", font, System.Drawing.Brushes.Black, width - measured_width, -font.Height / 2);

                for (int i = width-1; i >= 0; i--)
                {
                    measured_width--;
                    if (bitmap.GetPixel (i, 0).R == 0)
                    {
                        break;
                    }
                }
            }

            return new System.Drawing.SizeF (measured_width, size.Height);
        }
Example #8
0
        /// <summary>
        /// 初始化
        /// </summary>
        public void Intitial( FontMgr.FontLoadInfo fontLoadInfo )
        {
            try
            {
                privateFontCollection = new PrivateFontCollection();

                foreach (FontMgr.FontInfo info in fontLoadInfo.UnitCodeFontInfos)
                {
                    privateFontCollection.AddFontFile( info.path );
                }

                fontFamilys = privateFontCollection.Families;

                if (fontFamilys.Length != fontLoadInfo.UnitCodeFontInfos.Count)
                    throw new Exception( "导入的各个字体必须属于不同类别" );

                for (int i = 0; i < fontFamilys.Length; i++)
                {
                    fonts.Add( fontLoadInfo.UnitCodeFontInfos[i].name, new System.Drawing.Font( fontFamilys[i], fontLoadInfo.DefualtEmSize ) );
                }

                System.Drawing.Bitmap tempBitMap = new System.Drawing.Bitmap( 1, 1 );
                mesureGraphics = System.Drawing.Graphics.FromImage( tempBitMap );
            }
            catch (Exception)
            {
                throw new Exception( "读取字体文件出错" );
            }

        }
            public string CropImage(int x, int y, int w, int h, string imagePath)
            {
                var pathImage = Server.MapPath(imagePath);
                Image img = Image.FromFile(pathImage);
                Bitmap newBitmap = null;
                using (System.Drawing.Bitmap _bitmap = new System.Drawing.Bitmap(w, h))
                {
                    _bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
                    using (Graphics _graphic = Graphics.FromImage(_bitmap))
                    {
                        _graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        _graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        _graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                        _graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

                        _graphic.DrawImage(img, 0, 0, w, h);
                        _graphic.DrawImage(img, new Rectangle(0, 0, w, h), x, y, w, h, GraphicsUnit.Pixel);
                    }
                    var objImg = _bitmap.Clone();
                    newBitmap = (Bitmap)objImg;

                }
                var fileName = Path.GetFileNameWithoutExtension(imagePath) + "_Cropped" + Path.GetExtension(imagePath);
                newBitmap.Save(Server.MapPath("/Uploads/Temp/") + fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                return fileName;
            }
        public static void Run()
        {
            // ExStart:ExtractAllImagesFromPage
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_Shapes();

            // Call a Diagram class constructor to load a VSD diagram
            Diagram diagram = new Diagram(dataDir + "ExtractAllImagesFromPage.vsd");

            // Enter page index i.e. 0 for first one
            foreach (Shape shape in diagram.Pages[0].Shapes)
            {
                // Filter shapes by type Foreign
                if (shape.Type == Aspose.Diagram.TypeValue.Foreign)
                {
                    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(shape.ForeignData.Value))
                    {
                        // Load memory stream into bitmap object
                        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(stream);

                        // Save bmp here
                        bitmap.Save(dataDir + "ExtractAllImages" + shape.ID + "_out.bmp");
                    }
                }
            }
            // ExEnd:ExtractAllImagesFromPage
        }
 /// <summary>
 /// Converts a <see cref="System.Drawing.Image"/> into a WPF <see cref="BitmapSource"/>.
 /// </summary>
 /// <param name="image">The image image.</param>
 /// <returns>A BitmapSource</returns>
 public static BitmapSource ToBitmapSource(this System.Drawing.Image image)
 {
     using (var bitmap = new System.Drawing.Bitmap(image))
     {
         return bitmap.ToBitmapSource();
     }
 }
        public BatchClassificationDialog(ref Klu klu, ref TrainingDataSet dataSet, ProcessOptions processOptions)
        {
            InitializeComponent();

            _BackgroundWorker = new BackgroundWorker();
            _BackgroundWorker.WorkerReportsProgress = true;
            _BackgroundWorker.WorkerSupportsCancellation = true;
            _BackgroundWorker.DoWork += new DoWorkEventHandler(DoWork);
            _BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompleted);
            _BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(ProgressChanged);        

            BrowseButton.IsEnabled = true;
            CancelButton.IsEnabled = false;
            ClassifyButton.IsEnabled = false;

            _DataSet = dataSet;
            _SelectedFiles = new ArrayList();
            _ProcessOptions = processOptions;
            // We want the images to be as less distorded as possible, so we disable all the overlays.

            _ProcessOptions.DrawAnthropometricPoints = 0;
            _ProcessOptions.DrawDetectionTime = 0;
            _ProcessOptions.DrawFaceRectangle = 0;
            _ProcessOptions.DrawSearchRectangles = 0;
            _ProcessOptions.DrawFeaturePoints = 0;
            
            _KLU = klu;
            _FFP = new FaceFeaturePoints();
            _TempBitmap = new System.Drawing.Bitmap(10, 10);

            ExpressionsComboBox.ItemsSource = _DataSet.Expression;
            ClassifyButton.Content = "Classify";
        }
Example #13
0
        public string IsBig(string originalImagePath, int intWidth)
        {
            bool isExist = WXSSK.Common.DirectoryAndFile.FileExists(originalImagePath);
            System.Drawing.Image imgOriginal = System.Drawing.Image.FromFile(Server.MapPath(originalImagePath));

            //获取原图片的的宽度与高度
            int originalWidth = imgOriginal.Width;
            int originalHeight = imgOriginal.Height;

            //如果原图片宽度大于原图片的高度
            if (originalWidth > intWidth)
            {
                originalWidth = intWidth;  //宽度等于缩略图片尺寸
                originalHeight = originalHeight * (intWidth / originalWidth);  //高度做相应比例缩小
            }

            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(originalWidth, originalHeight);
            System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);

            //设置缩略图片质量
            graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
            graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            graphics.DrawImage(imgOriginal, 0, 0, originalWidth, originalHeight);

            //System.Drawing.Graphics temp = graphics;
            // 保存缩略图片
            imgOriginal.Dispose();
            WXSSK.Common.DirectoryAndFile.DeleteFile(originalImagePath);
            bitmap.Save(Server.MapPath(originalImagePath), System.Drawing.Imaging.ImageFormat.Jpeg);
            return originalImagePath;
        }
        private static void ScaleByFixedHeight(String fileName, int newHeight, String outputFile)
        {
            System.Drawing.Bitmap resizedImage = null;

            try
            {
                using (System.Drawing.Image originalImage = System.Drawing.Image.FromFile(fileName))
                {
                    double resizeRatio = (double)newHeight / originalImage.Size.Height;
                    int newWidth = (int)(originalImage.Size.Width * resizeRatio);

                    System.Drawing.Size newSize = new System.Drawing.Size(newWidth, newHeight);

                    resizedImage = new System.Drawing.Bitmap(originalImage, newSize);
                }

                // Save resized picture.
                CheckAndCreatePath(outputFile);
                resizedImage.Save(outputFile, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            finally
            {
                if (resizedImage != null)
                {
                    resizedImage.Dispose();
                }
            }
        }
Example #15
0
        public static void CreateThumbnail(string source, string dest)
        {
            try
            {
                System.Drawing.Image src_image = System.Drawing.Image.FromFile(source);

                int smallDim = 100;
                int SMALLWIDTH, SMALLHEIGHT;
                if (src_image.Width > src_image.Height)
                {
                    SMALLWIDTH = smallDim;
                    SMALLHEIGHT = (int)((((decimal)SMALLWIDTH) * src_image.Height) / src_image.Width);
                }
                else
                {
                    SMALLHEIGHT = smallDim;
                    SMALLWIDTH = (int)((((decimal)SMALLHEIGHT) * src_image.Width) / src_image.Height);
                }
                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(SMALLWIDTH, SMALLHEIGHT, src_image.PixelFormat);
                System.Drawing.Graphics new_g = System.Drawing.Graphics.FromImage(bitmap);

                new_g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                new_g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                new_g.DrawImage(src_image, 0, 0, bitmap.Width, bitmap.Height);
                bitmap.Save(dest, System.Drawing.Imaging.ImageFormat.Jpeg);

                return;
            }
            catch
            {
                return;
            }
        }
 public ActionDefinition(ActionLibrary parent, string name, int id)
 {
     Library = parent;
     GameMakerVersion = 520;
     Name = name;
     ActionID = id;
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     Properties.Resources.DefaultAction.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
     OriginalImage = ms.ToArray();
     ms.Close();
     Image = new System.Drawing.Bitmap(24, 24, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
     System.Drawing.Graphics.FromImage(Image).DrawImage(Properties.Resources.DefaultAction, new System.Drawing.Rectangle(0, 0, 24, 24), new System.Drawing.Rectangle(0, 0, 24, 24), System.Drawing.GraphicsUnit.Pixel);
     (Image as System.Drawing.Bitmap).MakeTransparent(Properties.Resources.DefaultAction.GetPixel(0, Properties.Resources.DefaultAction.Height - 1));
     Hidden = false;
     Advanced = false;
     RegisteredOnly = false;
     Description = string.Empty;
     ListText = string.Empty;
     HintText = string.Empty;
     Kind = ActionKind.Normal;
     InterfaceKind = ActionInferfaceKind.Normal;
     IsQuestion = false;
     ShowApplyTo = true;
     ShowRelative = true;
     ArgumentCount = 0;
     Arguments = new ActionArgument[8];
     for (int i = 0; i < 8; i++) Arguments[i] = new ActionArgument();
     ExecutionType = ActionExecutionType.None;
     FunctionName = string.Empty;
     Code = string.Empty;
 }
        public static void Run()
        {
            // ExStart:RenderWorksheetToGraphicContext
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            // Create workbook object from source file
            Workbook workbook = new Workbook(dataDir + "SampleBook.xlsx");

            // Access first worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            // Create empty Bitmap
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1100, 600);

            // Create Graphics Context
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
            g.Clear(System.Drawing.Color.Blue);

            // Set one page per sheet to true in image or print options
            Aspose.Cells.Rendering.ImageOrPrintOptions opts = new Aspose.Cells.Rendering.ImageOrPrintOptions();
            opts.OnePagePerSheet = true;

            // Render worksheet to graphics context
            Aspose.Cells.Rendering.SheetRender sr = new Aspose.Cells.Rendering.SheetRender(worksheet, opts);
            sr.ToImage(0, g, 0, 0);

            // Save the graphics context image in Png format
            bmp.Save(dataDir + "OutputImage_out.png", System.Drawing.Imaging.ImageFormat.Png);
            //ExEnd:RenderWorksheetToGraphicContext
        }
Example #18
0
 public Kiwi()
 {
     name = "Kiwi";
     family = "Carnivore";
     food = "Worms";
     image = new System.Drawing.Bitmap("kiwi.jpg");
 }
Example #19
0
		internal static System.Drawing.Bitmap GetResourceBitmap(string filename)
		{
			System.IO.StreamReader reader = Common.GetResourceReader(filename);
			System.Drawing.Bitmap toReturn = new System.Drawing.Bitmap(reader.BaseStream);
			reader.Close();
			return toReturn;
		}
Example #20
0
    public static Cursor CreateCursor(UIElement element, int xHotSpot, 
        int yHotSpot)
    {
      element.Measure(new Size(double.PositiveInfinity, 
        double.PositiveInfinity));
      element.Arrange(new Rect(0, 0, element.DesiredSize.Width, 
        element.DesiredSize.Height));

      RenderTargetBitmap rtb = 
        new RenderTargetBitmap((int)element.DesiredSize.Width, 
          (int)element.DesiredSize.Height, 96, 96, PixelFormats.Pbgra32);
      rtb.Render(element);

      PngBitmapEncoder encoder = new PngBitmapEncoder();
      encoder.Frames.Add(BitmapFrame.Create(rtb));

      MemoryStream ms = new MemoryStream();
      encoder.Save(ms);

      System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms);

      ms.Close();
      ms.Dispose();     

      Cursor cur = InternalCreateCursor(bmp, xHotSpot, yHotSpot);

      bmp.Dispose();

      return cur;
    }
Example #21
0
        public TextureData(string src)
        {
            try
            {
                System.Drawing.Bitmap texture = new System.Drawing.Bitmap(src);

                width = texture.Width;
                height = texture.Height;

                Clear();

                for (int x = 0; x < width; x++)
                    for (int y = 0; y < height; y++)
                    {
                        Color xnaColor = new Color();
                        System.Drawing.Color formsColor = texture.GetPixel(x, y);

                        xnaColor.R = formsColor.R;
                        xnaColor.G = formsColor.G;
                        xnaColor.B = formsColor.B;
                        xnaColor.A = formsColor.A;

                        data[y * width + x] = xnaColor.PackedValue;
                    }
            }
            catch(Exception e)
            {
                Console.WriteLine("Failed to load file: " + e.Message);
                Clear();
            }
        }
Example #22
0
 public RoyalAlbatross()
 {
     name = "Royal Albatross";
     family = "Carnivore";
     food = "Squid";
     image = new System.Drawing.Bitmap("royal_albatross.jpg");
 }
Example #23
0
 public static string reveal(string path)
 {
     string result = "";
     System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(path);
     // FIXME
     return result;
 }
 // Constructor
 public ThumbnailEventArgs(System.Drawing.Bitmap bmp, string filename,int count, int totalcount)
 {
     this.bmp = bmp;
     this.filename = filename;
     this.count = count;
     this.totalCount = totalcount;
 }
Example #25
0
 public override Bitmap load(string filename, bool isLinear)
 {
     // regular image, load using Java api
     System.Drawing.Bitmap bi = new
         System.Drawing.Bitmap(filename);
     int width = bi.Width;
     int height = bi.Height;
     System.Drawing.Color tmpColour;
     byte[] pixels = new byte[4 * width * height];
     for (int y = 0, index = 0; y < height; y++) {
         for (int x = 0; x < width; x++, index += 4) {
             tmpColour = bi.GetPixel(x,y);
             pixels[index + 0] = tmpColour.R;
             pixels[index + 1] = tmpColour.G;
             pixels[index + 2] = tmpColour.B;
             pixels[index + 3] = tmpColour.A;
         }
     }
     if (!isLinear) {
         for (int index = 0; index < pixels.Length; index += 4) {
             pixels[index + 0] = Color.NATIVE_SPACE.rgbToLinear(pixels[index + 0]);
             pixels[index + 1] = Color.NATIVE_SPACE.rgbToLinear(pixels[index + 1]);
             pixels[index + 2] = Color.NATIVE_SPACE.rgbToLinear(pixels[index + 2]);
         }
     }
     return new BitmapRGBA8(width, height, pixels);
 }
        public static System.Drawing.Bitmap create_hue_bitmap(int width, int height)
        {
            var bitmap = new System.Drawing.Bitmap(width, height);

            using (var gfx = System.Drawing.Graphics.FromImage(bitmap))
            {
                var colorblend = new System.Drawing.Drawing2D.ColorBlend();
                const int num_steps = 34;
                var range_steps = EnumerableUtil.RangeSteps(0.0, 1.0, num_steps);

                colorblend.Colors = new System.Drawing.Color[num_steps];
                colorblend.Positions = new float[num_steps];

                double _sat = 1.0;
                double _val = 1.0;

                var colors = range_steps.Select(x => VisioAutomation.UI.ColorUtil.HSVToSystemDrawingColor(x, _sat, _val));
                var positions = range_steps.Select(x => (float) x);

                EnumerableUtil.FillArray( colorblend.Colors, colors );
                EnumerableUtil.FillArray(colorblend.Positions, positions);

                using (var brush_rainbow = new System.Drawing.Drawing2D.LinearGradientBrush(
                    new System.Drawing.Point(0, 0),
                    new System.Drawing.Point(bitmap.Width, 0),
                    System.Drawing.Color.Black,
                    System.Drawing.Color.White))
                {
                    brush_rainbow.InterpolationColors = colorblend;
                    gfx.FillRectangle(brush_rainbow, 0, 0, bitmap.Width, bitmap.Height);
                }
            }
            return bitmap;
        }
Example #27
0
        public static byte[] CreateAvatar(int sideLength, System.IO.Stream fromStream)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            using (var image = System.Drawing.Image.FromStream(fromStream))
            using (var thumbBitmap = new System.Drawing.Bitmap(sideLength, sideLength))
            {

                var a = Math.Min(image.Width, image.Height);

                var x = (image.Width - a) / 2;

                var y = (image.Height - a) / 2;

                using (var thumbGraph = System.Drawing.Graphics.FromImage(thumbBitmap))
                {

                    thumbGraph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

                    thumbGraph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                    thumbGraph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                    var imgRectangle = new System.Drawing.Rectangle(0, 0, sideLength, sideLength);

                    thumbGraph.DrawImage(image, imgRectangle, x, y, a, a, System.Drawing.GraphicsUnit.Pixel);

                    thumbBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                }

            }
            return (ms.ToArray());
        }
Example #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ThumbnailCreator"/> class.
        /// </summary>
        /// <param name="tnSettings">The <see cref="ThumbnailSettings"/> to use.</param>
        /// <param name="worker">The <see cref="System.ComponentModel.BackgroundWorker"/>worker to use.
        /// </param>
        public ThumbnailCreator(ThumbnailSettings tnSettings, System.ComponentModel.BackgroundWorker worker)
        {
            this._tnSettings = tnSettings;
            this._worker = worker;

            #if false
            _imageCodec = GetEncoder (System.Drawing.Imaging.ImageFormat.Png);
            _qualityParameter = new System.Drawing.Imaging.EncoderParameter (
                    System.Drawing.Imaging.Encoder.Quality, 75L);
            _qualityParameters = new System.Drawing.Imaging.EncoderParameters (1);
            _qualityParameters.Param[0] = _qualityParameter;
            #else
            _imageCodec = GetEncoder (System.Drawing.Imaging.ImageFormat.Jpeg);
            _qualityParameter = new System.Drawing.Imaging.EncoderParameter (
                    System.Drawing.Imaging.Encoder.Quality, 75L);
            _qualityParameters = new System.Drawing.Imaging.EncoderParameters (1);
            _qualityParameters.Param[0] = _qualityParameter;
            #endif

            #if false
            using (System.Drawing.Bitmap bitmap1 = new System.Drawing.Bitmap (1, 1))
                {
                System.Drawing.Imaging.EncoderParameters paramList =
                        bitmap1.GetEncoderParameterList (_imageCodec.Clsid);
                System.Drawing.Imaging.EncoderParameter[] encParams = paramList.Param;
                foreach (System.Drawing.Imaging.EncoderParameter p in encParams)
                    {
                    THelper.Information ("Type {0}, GUID {1}", p.ValueType, p.Encoder.Guid);
                    }

                paramList.Dispose ();
                }
            #endif
        }
Example #29
0
 public Koala()
 {
     name = "Koala";
     family = "Herbavore";
     food = "Leaves";
     image = new System.Drawing.Bitmap("koala.jpg");
 }
        static void MakeImagesNegative(string sourceDirectoryPath, string targetDirectoryPath)
        {
            string[] filenames = System.IO.Directory.GetFiles(sourceDirectoryPath);

            foreach (var filename in filenames)
            {
                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(filename);
                Parallel.For(0, bitmap.Height, (bitmapRowIndex) =>
                {
                    lock (bitmap)
                    {
                        for (int bitmapColIndex = 0; bitmapColIndex < bitmap.Width; bitmapColIndex++)
                        {

                            var pixel = bitmap.GetPixel(bitmapColIndex, bitmapRowIndex);
                            var negativePixel = System.Drawing.Color.FromArgb(
                                byte.MaxValue - pixel.A,
                                byte.MaxValue - pixel.R,
                                byte.MaxValue - pixel.G,
                                byte.MaxValue - pixel.B);

                            bitmap.SetPixel(bitmapColIndex, bitmapRowIndex, negativePixel);
                        }
                    }
                });

                bitmap.Save(filename.Replace(sourceDirectoryPath, targetDirectoryPath));
            }
        }
Example #31
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="orginalImagePat">原图片地址</param>
        /// <param name="thumNailPath">缩略图地址</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="model">生成缩略的模式</param>
        public static void MakeThumNail(string originalImagePath, string thumNailPath, int width, int height, string model)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int thumWidth  = width;     //缩略图的宽度
            int thumHeight = height;    //缩略图的高度

            int x = 0;
            int y = 0;

            int originalWidth  = originalImage.Width;   //原始图片的宽度
            int originalHeight = originalImage.Height;  //原始图片的高度

            switch (model)
            {
            case "HW":          //指定高宽缩放,可能变形
                break;

            case "W":           //指定宽度,高度按照比例缩放
                thumHeight = originalImage.Height * width / originalImage.Width;
                break;

            case "H":           //指定高度,宽度按照等比例缩放
                thumWidth = originalImage.Width * height / originalImage.Height;
                break;

            case "Cut":         //指定高宽裁剪,剧中裁剪
                if ((double)originalImage.Width / (double)originalImage.Height > (double)thumWidth / (double)thumHeight)
                {
                    originalHeight = originalImage.Height;
                    originalWidth  = originalImage.Height * thumWidth / thumHeight;
                    y = 0;
                    x = (originalImage.Width - originalWidth) / 2;
                }
                else
                {
                    originalWidth  = originalImage.Width;
                    originalHeight = originalWidth * height / thumWidth;
                    x = 0;
                    y = (originalImage.Height - originalHeight) / 2;
                }
                break;

            case "MW":          //指定最大宽度,超出后按最大宽度缩放
                if (thumWidth > originalWidth)
                {
                    thumWidth  = originalImage.Width;
                    thumHeight = originalImage.Height;
                }
                else
                {
                    thumHeight = originalImage.Height * width / originalImage.Width;
                }
                break;

            case "MH":          //指定最大高度,超出后按最大高度缩放
                if (thumHeight > originalHeight)
                {
                    thumWidth  = originalImage.Width;
                    thumHeight = originalImage.Height;
                }
                else
                {
                    thumWidth = originalImage.Width * height / originalImage.Height;
                }
                break;

            default:
                break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(thumWidth, thumHeight);

            //新建一个画板
            System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量查值法
            graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            graphic.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            graphic.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, thumWidth, thumHeight), new System.Drawing.Rectangle(x, y, originalWidth, originalHeight), System.Drawing.GraphicsUnit.Pixel);

            try
            {
                bitmap.Save(thumNailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                graphic.Dispose();
            }
        }
Example #32
0
 public Invert(Bitmap b, System.IntPtr Scan0, int stride, int height_start, int height_end, ThreadHandler thInfo)
     : base(b, Scan0, stride, height_start, height_end, thInfo)
 {
 }
Example #33
0
        private static void Main(string[] args)
        {
            Arguments = new Dictionary <string, string>();
            foreach (var a in args)
            {
                int i = a.IndexOf('=');
                if (i > 0)
                {
                    string k = a.Substring(0, i);
                    string v = a.Substring(i + 1);
                    Arguments.Add(k, v);
                }
            }
            mode             = args[0];
            infile           = args[1];
            outfile          = args[2];
            Media.SearchPath = "media";

            if (mode == "scene2assets")
            {
                string scenename = args[3];
                var    element   = new VEngine.FileFormats.GameScene(infile);
                element.Load();
                int           unnamed = 0;
                StringBuilder sceneb  = new StringBuilder();
                var           rand    = new Random();
                foreach (var m in element.Meshes)
                {
                    string name = "mesh" + (unnamed++);
                    SaveMeshToFile(m, name, outfile);
                    sceneb.AppendLine("mesh3d " + name + ".mesh3d");
                }
                File.WriteAllText(outfile + "/" + scenename, sceneb.ToString());
            }
            if (mode == "obj2raw")
            {
                var element = Object3dManager.LoadFromObjSingle(infile);
                element.SaveRaw(outfile);
            }
            if (mode == "obj2rawtangsmooth")
            {
                var element = Object3dManager.LoadFromObjSingle(infile);
                element.RecalulateNormals(Object3dManager.NormalRecalculationType.Smooth, 1);
                element.SaveRawWithTangents(outfile);
            }
            if (mode == "raw2rawtang")
            {
                var element = Object3dManager.LoadFromRaw(infile);
                element.SaveRawWithTangents(outfile);
            }
            if (mode == "obj2rawtang")
            {
                var element = Object3dManager.LoadFromObjSingle(infile);
                element.SaveRawWithTangents(outfile);
            }
            if (mode == "objscene2assets")
            {
                Console.WriteLine("Conversion started");
                var elements = Object3dManager.LoadSceneFromObj(infile + ".obj", infile + ".mtl");

                var           map       = new List <string>();
                var           r         = new Random();
                StringBuilder sceneb    = new StringBuilder();
                string        scenename = args[3];

                Console.WriteLine("Found elements " + elements.Count);
                foreach (var m in elements)
                {
                    string n = m.GetInstance(0).Name;
                    if (n == null || n.Length == 0 || map.Contains(n))
                    {
                        n = m.GetLodLevel(0).Info3d.Manager.Name;
                    }
                    if (n == null || n.Length == 0 || map.Contains(n))
                    {
                        n = m.GetLodLevel(0).Material.Name;
                    }
                    if (n == null || n.Length == 0 || map.Contains(n))
                    {
                        n = Path.GetFileNameWithoutExtension(m.GetLodLevel(0).Material.DiffuseTexture.FileName);
                    }
                    if (n == null || n.Length == 0 || map.Contains(n))
                    {
                        n = Path.GetFileNameWithoutExtension(m.GetLodLevel(0).Material.BumpTexture.FileName);
                    }
                    if (n == null || n.Length == 0 || map.Contains(n))
                    {
                        n = Path.GetFileNameWithoutExtension(m.GetLodLevel(0).Material.NormalsTexture.FileName);
                    }
                    while (n == null || n.Length == 0 || map.Contains(n))
                    {
                        n = "unknown_" + r.Next();
                    }
                    Console.WriteLine("Converting mesh " + n);

                    SaveMeshToFile(m, n, outfile);
                    sceneb.AppendLine("mesh3d " + n + ".mesh3d");
                }
                Console.WriteLine("Saving scene");
                File.WriteAllText(outfile + "/" + scenename, sceneb.ToString());
            }

            if (mode == "ply2raw")
            {
                var ai          = new AssimpContext();
                var vertexinfos = new List <VertexInfo>();
                var mi          = ai.ImportFile(infile, PostProcessSteps.Triangulate);
                foreach (var m in mi.Meshes)
                {
                    var indices = m.GetIndices();

                    for (int i = 0; i < indices.Length; i++)
                    {
                        int f  = indices[i];
                        var vp = m.Vertices[f];
                        var vn = m.Normals[f];
                        var vt = (m.TextureCoordinateChannels.Length == 0 || m.TextureCoordinateChannels[0].Count <= f) ? new Assimp.Vector3D(0) : m.TextureCoordinateChannels[0][f];
                        var vi = new VertexInfo()
                        {
                            Position = new Vector3(vp.X, vp.Y, vp.Z),
                            Normal   = new Vector3(vn.X, vn.Y, vn.Z),
                            UV       = new Vector2(vt.X, vt.Y)
                        };
                        vertexinfos.Add(vi);
                    }
                }

                var element = new Object3dManager(vertexinfos);
                element.SaveRaw(outfile);
            }
            if (mode == "generateterrain")
            {
                RequireArgs("resolution", "in", "out", "size", "uvscale", "height");
                var    img        = new System.Drawing.Bitmap(Arguments["in"]);
                int    resolution = int.Parse(Arguments["resolution"]);
                string ofile      = Arguments["out"];
                float  size       = float.Parse(Arguments["size"], System.Globalization.CultureInfo.InvariantCulture) / 2.0f;
                float  uvscale    = float.Parse(Arguments["uvscale"], System.Globalization.CultureInfo.InvariantCulture);
                float  height     = float.Parse(Arguments["height"], System.Globalization.CultureInfo.InvariantCulture);
                int    lx         = 1;
                var    t          = VEngine.Generators.Object3dGenerator.CreateTerrain(new Vector2(-size), new Vector2(size), new Vector2(uvscale), Vector3.UnitY, resolution, (x, y) =>
                {
                    int xpx = (int)(x * img.Size.Width);
                    int ypx = (int)(y * img.Size.Height);
                    if (xpx >= img.Size.Width)
                    {
                        xpx = img.Size.Width - 1;
                    }
                    if (ypx >= img.Size.Height)
                    {
                        ypx = img.Size.Height - 1;
                    }
                    var col  = img.GetPixel(xpx, ypx);
                    int zxzs = (int)(x * 100.0);
                    if (zxzs > lx)
                    {
                        Console.WriteLine(zxzs);
                    }
                    if (zxzs > lx)
                    {
                        lx = zxzs;
                    }
                    return(((float)(col.R) / 255.0f) * height);
                });
                Console.WriteLine("Starting saving");
                t.SaveRawWithTangents(ofile);
            }
            if (mode == "assimp2assets")
            {
                // convert.exe assimp2assets infile.dae outdir outname.scene
                var ai        = new AssimpContext();
                var usednames = new List <string>();
                var mi        = ai.ImportFile(infile, PostProcessSteps.Triangulate | PostProcessSteps.GenerateSmoothNormals);

                int    cnt       = 0;
                var    scenesb   = new StringBuilder();
                string scenename = args[3];
                doublefaced = args.Length == 5 && args[4] == "doublefaced";
                foreach (var m in mi.Materials)
                {
                    string name = usednames.Contains(m.Name) ? (m.Name + (unnamed++).ToString()) : m.Name;
                    var    sb   = new StringBuilder();
                    sb.AppendLine(string.Format("diffuse {0} {1} {2}", ftos(m.ColorDiffuse.R), ftos(m.ColorDiffuse.G), ftos(m.ColorDiffuse.B)));
                    sb.AppendLine(string.Format("roughness {0}", ftos(1.0f / (m.Shininess + 1.0f))));
                    sb.AppendLine(string.Format("metalness {0}", ftos(0.0f)));
                    sb.AppendLine();

                    if (m.HasTextureDiffuse)
                    {
                        sb.AppendLine("node");
                        sb.AppendLine(string.Format("texture {0}", Path.GetFileName(m.TextureDiffuse.FilePath)));
                        sb.AppendLine("mix REPLACE");
                        sb.AppendLine("target DIFFUSE");
                        sb.AppendLine("modifier LINEARIZE");
                        sb.AppendLine();
                    }
                    if (m.HasTextureReflection)
                    {
                        sb.AppendLine("node");
                        sb.AppendLine(string.Format("texture {0}", Path.GetFileName(m.TextureReflection.FilePath)));
                        sb.AppendLine("mix REPLACE");
                        sb.AppendLine("target ROUGHNESS");
                        sb.AppendLine();
                    }
                    if (m.HasTextureSpecular)
                    {
                        sb.AppendLine("node");
                        sb.AppendLine(string.Format("texture {0}", Path.GetFileName(m.TextureSpecular.FilePath)));
                        sb.AppendLine("mix REPLACE");
                        sb.AppendLine("target ROUGHNESS");
                        sb.AppendLine();
                    }
                    if (m.HasTextureNormal)
                    {
                        sb.AppendLine("node");
                        sb.AppendLine(string.Format("texture {0}", Path.GetFileName(m.TextureNormal.FilePath)));
                        sb.AppendLine("mix REPLACE");
                        sb.AppendLine("target NORMAL");
                        sb.AppendLine();
                    }
                    if (m.HasTextureDisplacement)
                    {
                        sb.AppendLine("node");
                        sb.AppendLine(string.Format("texture {0}", Path.GetFileName(m.TextureDisplacement.FilePath)));
                        sb.AppendLine("mix REPLACE");
                        sb.AppendLine("target BUMP");
                        sb.AppendLine();
                    }
                    Console.WriteLine("Saving " + outfile + "/" + name + ".material");
                    File.WriteAllText(outfile + "/" + name + ".material", sb.ToString());
                    matdict.Add(cnt, outfile + "/" + name + ".material");
                    cnt++;
                }
                recurseNode(mi, mi.RootNode, scenesb, Matrix4x4.Identity);
                Console.WriteLine("Saving " + outfile + "/" + scenename);
                File.WriteAllText(outfile + "/" + scenename, scenesb.ToString());
            }


            Console.WriteLine("Done");
        }
        /// <summary>
        /// 加图片水印
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="watermarkFilename">水印文件名</param>
        /// <param name="watermarkStatus">图片水印位置:0=不使用 1=左上 2=中上 3=右上 4=左中 ... 9=右下</param>
        /// <param name="quality">是否是高质量图片 取值范围0--100</param>
        /// <param name="watermarkTransparency">图片水印透明度 取值范围1--10 (10为不透明)</param>

        public static void AddImageSignPic(string Path, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            System.Drawing.Image    img = System.Drawing.Image.FromFile(Path);
            System.Drawing.Graphics g   = System.Drawing.Graphics.FromImage(img);

            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            System.Drawing.Image watermark = new System.Drawing.Bitmap(watermarkFilename);

            if (watermark.Height >= img.Height || watermark.Width >= img.Width)
            {
                return;
            }

            System.Drawing.Imaging.ImageAttributes imageAttributes = new System.Drawing.Imaging.ImageAttributes();
            System.Drawing.Imaging.ColorMap        colorMap        = new System.Drawing.Imaging.ColorMap();

            colorMap.OldColor = System.Drawing.Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = System.Drawing.Color.FromArgb(0, 0, 0, 0);
            System.Drawing.Imaging.ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            float transparency = 0.5F;

            if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
            {
                transparency = (watermarkTransparency / 10.0F);
            }

            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 1.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 1.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, transparency, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f,         0.0f, 1.0f }
            };

            System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;

            switch (watermarkStatus)
            {
            case 1:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)(img.Height * (float).01);
                break;

            case 2:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)(img.Height * (float).01);
                break;

            case 3:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)(img.Height * (float).01);
                break;

            case 4:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 5:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 6:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 7:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 8:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 9:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;
            }

            g.DrawImage(watermark, new System.Drawing.Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, System.Drawing.GraphicsUnit.Pixel, imageAttributes);

            System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
            System.Drawing.Imaging.ImageCodecInfo   ici    = null;
            foreach (System.Drawing.Imaging.ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }
            qualityParam[0] = quality;

            System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                img.Save(filename, ici, encoderParams);
            }
            else
            {
                img.Save(filename);
            }

            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();
        }
Example #35
0
        public override System.Drawing.Image CreateDrawingImage(System.Drawing.Color foreground, System.Drawing.Color background)
        {
            int barWidth = (int)x;

            if (barWidth <= 0)
            {
                barWidth = 1;
            }
            int barDistance = (int)n;

            if (barDistance <= barWidth)
            {
                barDistance = barWidth + 1;
            }
            int barShort = (int)size;

            if (barShort <= 0)
            {
                barShort = 1;
            }
            int barTall = (int)barHeight;

            if (barTall <= barShort)
            {
                barTall = barShort + 1;
            }
            byte[] bars  = GetBarsPostnet(code);
            int    width = bars.Length * barDistance;
            byte   flip  = 1;

            if (codeType == PLANET)
            {
                flip    = 0;
                bars[0] = 0;
                bars[bars.Length - 1] = 0;
            }
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, barTall);
            int seg1 = barTall - barShort;

            for (int i = 0; i < seg1; ++i)
            {
                int idx = 0;
                for (int k = 0; k < bars.Length; ++k)
                {
                    bool dot = (bars[k] == flip);
                    for (int j = 0; j < barDistance; ++j)
                    {
                        bmp.SetPixel(idx++, i, (dot && j < barWidth) ? foreground : background);
                    }
                }
            }
            for (int i = seg1; i < barTall; ++i)
            {
                int idx = 0;
                for (int k = 0; k < bars.Length; ++k)
                {
                    for (int j = 0; j < barDistance; ++j)
                    {
                        bmp.SetPixel(idx++, i, (j < barWidth) ? foreground : background);
                    }
                }
            }
            return(bmp);
        }
Example #36
0
 private void InitializeTexture2D()
 {
     this.tex = new Texture2D();
     System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(this.textureFile);
     this.tex.Initialize(bmp);
 }
Example #37
0
        private void bind(string sjhm)
        {
            //获取用户信息
            StringBuilder sqlKeHu = new StringBuilder();

            sqlKeHu.AppendFormat(@"SELECT * FROM dbo.hy_hyzlxxb WHERE sjhm='" + sjhm + "'");
            DataTable dt = DataFactory.SqlDataBase(RequestSession.GetSessionUser().AdminHotelid.ToString()).GetDataTableBySQL(sqlKeHu);

            if (dt.Rows.Count > 0)
            {
                string     adminhotelid = RequestSession.GetSessionUser().AdminHotelid.ToString();//adminhotelid
                string     sql          = string.Format(@"  SELECT (SELECT TOP 1 id FROM dbo.Hotel WHERE Hotel.AdminHotelid=@AdminHotelid)hotelid,Hotel_Admin.type FROM dbo.Hotel_Admin
                    where Hotel_Admin.AdminHotelid=@AdminHotelid");
                SqlParam[] parmAdd      = new SqlParam[] {
                    new SqlParam("@AdminHotelid", adminhotelid)
                };
                DataTable sql1s     = DataFactory.SqlDataBase().GetDataTableBySQL(new StringBuilder(sql), parmAdd);
                string    hotelid   = ""; //酒店ID
                string    hotelType = ""; //酒店类型
                if (sql1s != null && sql1s.Rows.Count > 0)
                {
                    hotelid   = sql1s.Rows[0]["hotelid"].ToString();
                    hotelType = sql1s.Rows[0]["type"].ToString();
                }
                else
                {
                }

                if (dt.Rows[0]["fxurl"] != null && dt.Rows[0]["fxurl"].ToString() != "")
                {
                    fxsrc.Src = "~/QR_code/MemberQRCode/" + dt.Rows[0]["fxurl"] + ".jpg";
                }
                else
                {
                    //查询WeChatInfo,获取NOTIFY_URL
                    //获取用户信息
                    string        NOTIFY_URL = "";
                    StringBuilder sqlInfo    = new StringBuilder();
                    sqlInfo.AppendFormat(@"SELECT * FROM dbo.WeChatInfo WHERE AdminHotelid='" + adminhotelid + "'");
                    DataTable dtInfo = DataFactory.SqlDataBase().GetDataTableBySQL(sqlInfo);
                    if (dtInfo != null && dtInfo.Rows.Count > 0)
                    {
                        NOTIFY_URL = dtInfo.Rows[0]["NOTIFY_URL"].ToString();
                    }
                    else
                    {
                    }

                    QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                    qrCodeEncoder.QRCodeEncodeMode   = QRCodeEncoder.ENCODE_MODE.BYTE;
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                    qrCodeEncoder.QRCodeVersion      = 0;//范围值是0-40
                    qrCodeEncoder.QRCodeScale        = 4;
                    String data;
                    if (hotelType == "0")
                    {
                        data = "http://" + NOTIFY_URL + "/Reservation/HotelDetails.aspx?AdminHotelid=" + adminhotelid + "&hotelid=" + hotelid + "&sjhm=" + sjhm + "";
                    }
                    else
                    {
                        data = "http://" + NOTIFY_URL + "/Reservation/HotelList.aspx?AdminHotelid=" + adminhotelid;
                    }
                    System.Drawing.Bitmap  image   = qrCodeEncoder.Encode(data, Encoding.UTF8);
                    System.IO.MemoryStream MStream = new System.IO.MemoryStream();
                    string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + hotelid;

                    image.Save(Server.MapPath("~/QR_code/MemberQRCode/") + filename + ".jpg");
                    image.Save(MStream, System.Drawing.Imaging.ImageFormat.Gif);
                    fxsrc.Src     = "~/QR_code/MemberQRCode/" + filename + ".jpg";
                    hdFxurl.Value = filename + ".jpg";
                    StringBuilder sqlUpdateKeHu = new StringBuilder();
                    sqlUpdateKeHu.AppendFormat(@"update Base_UserInfo set  fxurl='" + filename + "'  where User_Account='" + sjhm + "'");
                    DataTable dtUpdate = DataFactory.SqlDataBase().GetDataTableBySQL(sqlUpdateKeHu);
                }
            }
            else
            {
                return;
                //Response.Redirect("../member/MemberCenter.aspx");
            }
        }
Example #38
0
 public FrameInfo(System.Drawing.Bitmap frame)
 {
     this.frame = frame;
 }
Example #39
0
 public Bitmap(Image original, Size newSize)
 {
     WrappedBitmap = new System.Drawing.Bitmap(original, newSize);
 }
Example #40
0
 public Bitmap(string filename)
 {
     WrappedBitmap = new System.Drawing.Bitmap(filename);
 }
Example #41
0
 public Bitmap(Image original)
 {
     WrappedBitmap = new System.Drawing.Bitmap(original);
 }
Example #42
0
 public Bitmap(Image original, int width, int height)
 {
     WrappedBitmap = new System.Drawing.Bitmap(original, width, height);
 }
Example #43
0
 public Bitmap(int width, int height)
 {
     WrappedBitmap = new System.Drawing.Bitmap(width, height);
 }
Example #44
0
 public Bitmap(int width, int height, System.Drawing.Graphics g)
 {
     WrappedBitmap = new System.Drawing.Bitmap(width, height, g);
 }
Example #45
0
 public Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0)
 {
     WrappedBitmap = new System.Drawing.Bitmap(width, height, stride,
                                               (System.Drawing.Imaging.PixelFormat)format, scan0);
 }
Example #46
0
 public Bitmap(int width, int height, PixelFormat format)
 {
     WrappedBitmap = new System.Drawing.Bitmap(width, height, (System.Drawing.Imaging.PixelFormat)format);
 }
Example #47
0
 public Bitmap(Stream stream)
 {
     WrappedBitmap = new System.Drawing.Bitmap(stream);
 }
Example #48
0
 public Bitmap(Stream stream, bool useIcm)
 {
     WrappedBitmap = new System.Drawing.Bitmap(stream, useIcm);
 }
Example #49
0
 public Bitmap(string filename, bool useIcm)
 {
     WrappedBitmap = new System.Drawing.Bitmap(filename, useIcm);
 }
Example #50
0
 public Bitmap(Type type, string resource)
 {
     WrappedBitmap = new System.Drawing.Bitmap(type, resource);
 }
Example #51
0
        /// <summary>
        /// 生成校验码图片。
        /// </summary>
        /// <param name="code">验证码文本。</param>
        /// <returns></returns>
        public static System.Drawing.Bitmap GenerateVerifyCodeImage(string code)
        {
            int fSize    = VerifyCode.FontSize;
            int iPadding = VerifyCode.Padding;

            int fWidth      = fSize + iPadding;
            int imageWidth  = code.Length * fWidth + iPadding * 2 + fWidth;
            int imageHeight = fSize * 2 + iPadding;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight);

            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);

            g.Clear(VerifyCode.BackColor);

            System.Random rand = new System.Random();

            int left, top, top1, top2;

            int n1 = (imageHeight - fSize - iPadding * 2);
            int n2 = n1 / 4;

            top1 = n2;
            top2 = n2 * 2;

            System.Drawing.Font  f;
            System.Drawing.Brush b;

            int cindex, findex;

            #region 随机字体和颜色的验证码字符
            cindex = rand.Next(ForeColors.Length);
            for (int i = 0; i < code.Length; i++)
            {
                findex = rand.Next(Fonts.Length);

                f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
                b = new System.Drawing.SolidBrush(ForeColors[cindex]);

                if (i % 2 == 1)
                {
                    top = top2;
                }
                else
                {
                    top = top1;
                }

                left = i * fWidth;

                g.DrawString(code.Substring(i, 1), f, b, left, top);
            }
            #endregion

            //#region 给背景添加随机生成的燥点
            //if (VerifyCode.HasPinto && VerifyCode.Pinto > 0)
            //{

            //    //System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.LightGray, 0);
            //    System.Drawing.Pen pen = new System.Drawing.Pen(VerifyCode.BackColor, 0);
            //    int c = System.Convert.ToInt32(image.Width * image.Height * VerifyCode.Pinto);

            //    for (int i = 0; i < c; i++)
            //    {
            //        int x = rand.Next(image.Width);
            //        int y = rand.Next(image.Height);

            //        g.DrawRectangle(pen, x, y, 1, 1);
            //    }
            //}
            //#endregion

            //画一个边框 边框颜色为Color.Gainsboro
            //g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
            g.Dispose();

            //产生波形
            if (VerifyCode.BendingAngle != 0)
            {
                image = VerifyCode.TwistImage(image, VerifyCode.BackColor, true, VerifyCode.BendingAngle, 4);
            }
            DrawCurve(image, VerifyCode.ForeColors[rand.Next(0, VerifyCode.ForeColors.Length)]);
            return(image);
        }
Example #52
0
 public void DrawToBitmap(System.Drawing.Bitmap bitmap, System.Drawing.Rectangle targetBounds)
 {
 }
Example #53
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径(相对路径)</param>
        /// <param name="thumbnailPath">缩略图路径(相对路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(Utils.GetMapPath(originalImagePath));
            int towidth  = width;
            int toheight = height;

            int x  = 0;
            int y  = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
            case "HW":    //指定高宽缩放(可能变形)
                break;

            case "W":    //指定宽,高按比例
                toheight = originalImage.Height * width / originalImage.Width;
                break;

            case "H":    //指定高,宽按比例
                towidth = originalImage.Width * height / originalImage.Height;
                break;

            case "Cut":    //指定高宽裁减(不变形)
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y  = 0;
                    x  = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x  = 0;
                    y  = (originalImage.Height - oh) / 2;
                }
                break;

            default:
                break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                        new System.Drawing.Rectangle(x, y, ow, oh),
                        System.Drawing.GraphicsUnit.Pixel);

            try
            {
                //保存缩略图
                bitmap.Save(Utils.GetMapPath(thumbnailPath));
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
Example #54
0
        /// <summary>
        /// 画一条由两条连在一起构成的随机正弦函数曲线作干扰线
        /// </summary>
        /// <param name="image"></param>
        /// <param name="color"></param>
        private static void DrawCurve(System.Drawing.Bitmap image, System.Drawing.Color color)
        {
            int fontSize = image.Height / 3;

            int imageH = image.Height;
            int imageL = image.Width;

            System.Random rand = new System.Random();
            double        A    = rand.Next(1, imageH / 2);                                    // 振幅
            double        b    = rand.Next(-imageH / 4, imageH / 4);                          // Y轴方向偏移量
            double        f    = rand.Next(-imageH / 4, imageH / 4);                          // X轴方向偏移量
            double        T    = rand.Next(System.Convert.ToInt32(imageH * 1.5), imageL * 2); // 周期
            double        w    = (2 * System.Math.PI) / T;
            double        py   = 0;

            int    px1 = 0;                                                                                     // 曲线横坐标起始位置
            int    px2 = rand.Next(System.Convert.ToInt32(imageL / 2), System.Convert.ToInt32(imageL * 0.667)); // 曲线横坐标结束位置
            double px;

            for (px = px1; px <= px2; px += 0.9)
            {
                if (w != 0)
                {
                    py = A * System.Math.Sin(w * px + f) + b + imageH / 2;  // y = Asin(ωx+φ) + b
                    int i = (int)((fontSize - 6) / 4);
                    while (i > 0)
                    {
                        int w2 = System.Convert.ToInt32(px + i);
                        if (w2 < 0)
                        {
                            w2 = 0;
                        }
                        if (w2 >= image.Width)
                        {
                            w2 = image.Width - 1;
                        }
                        int h2 = System.Convert.ToInt32(py + i);
                        if (h2 < 0)
                        {
                            h2 = 0;
                        }
                        if (h2 >= image.Height)
                        {
                            h2 = image.Height - 1;
                        }
                        image.SetPixel(w2, h2, color);  // 这里画像素点比imagettftext和imagestring性能要好很多
                        i--;
                    }
                }
            }

            A   = rand.Next(1, imageH / 2);                                    // 振幅
            f   = rand.Next(-imageH / 4, imageH / 4);                          // X轴方向偏移量
            T   = rand.Next(System.Convert.ToInt32(imageH * 1.5), imageL * 2); // 周期
            w   = (2 * System.Math.PI) / T;
            b   = py - A * System.Math.Sin(w * px + f) - imageH / 2;
            px1 = px2;
            px2 = imageL;
            for (px = px1; px <= px2; px += 0.9)
            {
                if (w != 0)
                {
                    py = A * System.Math.Sin(w * px + f) + b + imageH / 2;  // y = Asin(ωx+φ) + b
                    int i = (int)((fontSize - 8) / 4);
                    while (i > 0)
                    {
                        int w2 = System.Convert.ToInt32(px + i);
                        if (w2 < 0)
                        {
                            w2 = 0;
                        }
                        if (w2 >= image.Width)
                        {
                            w2 = image.Width - 1;
                        }
                        int h2 = System.Convert.ToInt32(py + i);
                        if (h2 < 0)
                        {
                            h2 = 0;
                        }
                        if (h2 >= image.Height)
                        {
                            h2 = image.Height - 1;
                        }
                        image.SetPixel(w2, h2, color);  // 这里(while)循环画像素点比imagettftext和imagestring用字体大小一次画出(不用这while循环)性能要好很多
                        i--;
                    }
                }
            }
        }
Example #55
0
        public WaitingRoom()
        {
            Microsoft.Xna.Framework.Rectangle area = new Microsoft.Xna.Framework.Rectangle(
                (int)MyGame.ScreenCenter.X - _buttonWidth / 2
                , (int)(MyGame.ScreenCenter.Y * 1.75f) - _buttonHeight / 2
                , _buttonWidth
                , _buttonHeight);

            _buttonBack     = MyGame.ContentManager.Load <Texture2D>("Images/buttonScroll");
            _roomBackground = MyGame.ContentManager.Load <Texture2D>("Images/WaitingBack");
            _playerUIBack   = MyGame.ContentManager.Load <Texture2D>("Images/playerScroll");

            Texture2D messageBack = MyGame.ContentManager.Load <Texture2D>("Images/messageScroll");

            Rectangle stretchAreaButton = new Rectangle(15, 20, 70, 60);

            UIElements.StretchableImage stretchButtonTexture = new UIElements.StretchableImage(_buttonBack, stretchAreaButton);

            _startButton = new UIElements.SimpleButton(stretchButtonTexture, area, "Start Game");

            _playerUIs = new List <UIElements.LargePLayerUI>();

            _posStart = new Vector2(MyGame.ScreenArea.Width / 5, 470f);
            _offset   = new Vector2(MyGame.ScreenArea.Width / 5, 0f);


            //Create QR Code

            QRCodeEncoder encoder = new QRCodeEncoder();
            string        ip      = Utils.LocalIPAddress();

            Console.WriteLine("\n\n\n\nServer ip : " + ip + "\n\n\n");

            if (ip == "")
            {
                Rectangle stretchAreaMessage           = new Rectangle(30, 30, 40, 40);
                UIElements.StretchableImage stretchImg = new UIElements.StretchableImage(messageBack, stretchAreaMessage);

                Console.WriteLine("Creating dialog");
                _dialog = new ConditionalDialogBox(
                    delegate() { return(Utils.LocalIPAddress() != ""); }
                    , "Network could not be reached\n"
                    + "Please find de way to connect to a reliable, working network\n"
                    + "(Unice hotsport is NOT one of those networks...)"
                    , new Microsoft.Xna.Framework.Rectangle((int)MyGame.ScreenCenter.X, (int)MyGame.ScreenCenter.Y, 600, 600)
                    , stretchImg);

                _dialog.Position = MyGame.ScreenCenter;
                _dialog.Show();
            }
            else
            {
                System.Drawing.Bitmap qrCodeImage = encoder.Encode(ip);

                Color[] pixels = new Color[qrCodeImage.Width * qrCodeImage.Height];
                for (int y = 0; y < qrCodeImage.Height; y++)
                {
                    for (int x = 0; x < qrCodeImage.Width; x++)
                    {
                        System.Drawing.Color c = qrCodeImage.GetPixel(x, y);
                        pixels[(y * qrCodeImage.Width) + x] = new Color(c.R, c.G, c.B, c.A);
                    }
                }

                _QRCode = new Texture2D(
                    MyGame.SpriteBatch.GraphicsDevice,
                    qrCodeImage.Width,
                    qrCodeImage.Height);

                _QRCode.SetData <Color>(pixels);

                int recWidth = MyGame.ScreenArea.Width / 8;
                _QrCodeArea = new Rectangle((int)(MyGame.ScreenCenter.X - recWidth / 2), 30, recWidth, recWidth);

                NodeJSClient.ServerCom.Instance.playerConnectCB = OnPlayerConnect;
                NodeJSClient.ServerCom.Instance.Execute();

                //initializeRadialUI();
            }
        }
        static System.Drawing.Bitmap MergeAlphaChannel(System.Drawing.Bitmap original, System.Drawing.Bitmap alphaChannelBmp)
        {
            int w = original.Width;
            int h = original.Height;

            System.Drawing.Bitmap             resultBmp     = new System.Drawing.Bitmap(original);
            System.Drawing.Imaging.BitmapData resultBmpData = resultBmp.LockBits(new System.Drawing.Rectangle(0, 0, w, h), System.Drawing.Imaging.ImageLockMode.ReadWrite, original.PixelFormat);
            System.Drawing.Imaging.BitmapData alphaBmpData  = alphaChannelBmp.LockBits(new System.Drawing.Rectangle(0, 0, w, h), System.Drawing.Imaging.ImageLockMode.ReadOnly, alphaChannelBmp.PixelFormat);
            IntPtr resultScan0    = resultBmpData.Scan0;
            IntPtr alphaScan0     = alphaBmpData.Scan0;
            int    resultStride   = resultBmpData.Stride;
            int    lineByteCount  = resultStride;
            int    totalByteCount = lineByteCount * h;

            unsafe
            {
                byte *dest = (byte *)resultScan0;
                byte *src  = (byte *)alphaScan0;
                for (int i = 0; i < totalByteCount;)
                {
                    // *(dest + 3) = 150;
                    //replace  alpha channel with data from alphaBmpData
                    byte oldAlpha = *(dest + 3);
                    byte src_B    = *(src);     //b
                    byte src_G    = *(src + 1); //g
                    byte src_R    = *(src + 2); //r
                    //convert rgb to gray scale: from  this equation...
                    int y = (src_R * 77) + (src_G * 151) + (src_B * 28);
                    *(dest + 3) = (byte)(y >> 8);
                    //*(dest + 3) = (byte)((new_B + new_G + new_R) / 3);

                    dest += 4;
                    src  += 4;
                    i    += 4;
                }
            }
            alphaChannelBmp.UnlockBits(alphaBmpData);
            resultBmp.UnlockBits(resultBmpData);
            return(resultBmp);
        }
Example #57
0
        private void SaveTexture(byte[, ][] picBlocks, int mapWidth, int mapHeight, int blockWidth, int blockHeight)
        {
            //透明处理
            foreach (byte[] data in picBlocks)
            {
                for (int i = 0, j = data.Length; i < j; i += 4)
                {
                    data[i + 3] = 255;
                }
            }

            //组装
            byte[] mapData = new byte[mapWidth * mapHeight * 4];
            for (int j = 0; j < picBlocks.GetLength(1); j++)
            {
                for (int i = 0; i < picBlocks.GetLength(0); i++)
                {
                    byte[] data = picBlocks[i, j];

                    Rectangle blockRect = new Rectangle();
                    blockRect.X      = i * blockWidth;
                    blockRect.Y      = j * blockHeight;
                    blockRect.Width  = Math.Min(mapWidth - blockRect.X, blockWidth);
                    blockRect.Height = Math.Min(mapHeight - blockRect.Y, blockHeight);

                    int length = blockRect.Width * 4;
                    if (blockRect.X == 0 && blockRect.Width == mapWidth) //整块复制
                    {
                        int startIndex = mapWidth * 4 * blockRect.Y;
                        Buffer.BlockCopy(data, 0, mapData, startIndex, blockRect.Width * blockRect.Height * 4);
                    }
                    else //逐行扫描
                    {
                        int offset = 0;
                        for (int y = blockRect.Top, y0 = blockRect.Bottom; y < y0; y++)
                        {
                            int startIndex = (y * mapWidth + blockRect.X) * 4;
                            Buffer.BlockCopy(data, offset, mapData, startIndex, length);
                            offset += blockWidth * 4;
                        }
                    }
                }
            }

            try
            {
                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(
                    mapWidth,
                    mapHeight,
                    mapWidth * 4,
                    System.Drawing.Imaging.PixelFormat.Format32bppArgb,
                    Marshal.UnsafeAddrOfPinnedArrayElement(mapData, 0));

                bitmap.Save(DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + (this.mapData?.ID ?? 0).ToString("D9") + ".png",
                            System.Drawing.Imaging.ImageFormat.Png);

                bitmap.Dispose();
            }
            catch
            {
            }
        }
 void GenerateMaskWithWinGdiPlus(int w, int h)
 {
     //1. create 32 bits for mask image
     this.a_alphaBmp = new System.Drawing.Bitmap(w, h);
     //2. create graphics based on a_alphaBmp
     using (System.Drawing.Graphics gfxBmp = System.Drawing.Graphics.FromImage(a_alphaBmp))
     {
         gfxBmp.Clear(System.Drawing.Color.Black);
         //ClipProxyImage clippingProxy = new ClipProxyImage(image);
         //clippingProxy.Clear(ColorRGBA.Black);
         VertexSource.Ellipse ellipseForMask = new PixelFarm.Agg.VertexSource.Ellipse();
         System.Random        randGenerator  = new Random(1432);
         int num = (int)maskAlphaSliderValue;
         int lim = num - 1;
         for (int i = 0; i < lim; ++i)
         {
             ellipseForMask.Reset(randGenerator.Next() % w,
                                  randGenerator.Next() % h,
                                  randGenerator.Next() % 100 + 20,
                                  randGenerator.Next() % 100 + 20,
                                  100);
             // set the color to draw into the alpha channel.
             // there is not very much reason to set the alpha as you will get the amount of
             // transparency based on the color you draw.  (you might want some type of different edeg effect but it will be minor).
             //rasterizer.AddPath(ellipseForMask.MakeVxs());
             //sclineRasToBmp.RenderWithColor(clippingProxy, rasterizer, sclnPack,
             //   ColorRGBA.Make((int)((float)i / (float)num * 255), 0, 0, 255));
             VxsHelper.FillVxsSnap(gfxBmp, ellipseForMask.MakeVertexSnap(), ColorRGBA.Make((int)((float)i / (float)num * 255), 0, 0, 255));
         }
         //the last one
         ellipseForMask.Reset(Width / 2, Height / 2, 110, 110, 100);
         //fill
         VxsHelper.FillVxsSnap(gfxBmp, ellipseForMask.MakeVertexSnap(), new ColorRGBA(0, 0, 0, 255));
         //rasterizer.AddPath(ellipseForMask.MakeVertexSnap());
         //sclineRasToBmp.RenderWithColor(clippingProxy, rasterizer, sclnPack, new ColorRGBA(0, 0, 0, 255));
         ellipseForMask.Reset(ellipseForMask.originX, ellipseForMask.originY, ellipseForMask.radiusX - 10, ellipseForMask.radiusY - 10, 100);
         //rasterizer.AddPath(ellipseForMask.MakeVertexSnap());
         //sclineRasToBmp.RenderWithColor(clippingProxy, rasterizer, sclnPack, new ColorRGBA(255, 0, 0, 255));
         VxsHelper.FillVxsSnap(gfxBmp, ellipseForMask.MakeVertexSnap(), new ColorRGBA(255, 0, 0, 255));
         //for (i = 0; i < num; i++)
         //{
         //    if (i == num - 1)
         //    {
         //        ellipseForMask.Reset(Width / 2, Height / 2, 110, 110, 100);
         //        //fill
         //        VxsHelper.DrawVxsSnap(gfxBmp, ellipseForMask.MakeVertexSnap(), new ColorRGBA(0, 0, 0, 255));
         //        //rasterizer.AddPath(ellipseForMask.MakeVertexSnap());
         //        //sclineRasToBmp.RenderWithColor(clippingProxy, rasterizer, sclnPack, new ColorRGBA(0, 0, 0, 255));
         //        ellipseForMask.Reset(ellipseForMask.originX, ellipseForMask.originY, ellipseForMask.radiusX - 10, ellipseForMask.radiusY - 10, 100);
         //        //rasterizer.AddPath(ellipseForMask.MakeVertexSnap());
         //        //sclineRasToBmp.RenderWithColor(clippingProxy, rasterizer, sclnPack, new ColorRGBA(255, 0, 0, 255));
         //        VxsHelper.DrawVxsSnap(gfxBmp, ellipseForMask.MakeVertexSnap(), new ColorRGBA(255, 0, 0, 255));
         //    }
         //    else
         //    {
         //        ellipseForMask.Reset(randGenerator.Next() % w,
         //                 randGenerator.Next() % h,
         //                 randGenerator.Next() % 100 + 20,
         //                 randGenerator.Next() % 100 + 20,
         //                 100);
         //        // set the color to draw into the alpha channel.
         //        // there is not very much reason to set the alpha as you will get the amount of
         //        // transparency based on the color you draw.  (you might want some type of different edeg effect but it will be minor).
         //        //rasterizer.AddPath(ellipseForMask.MakeVxs());
         //        //sclineRasToBmp.RenderWithColor(clippingProxy, rasterizer, sclnPack,
         //        //   ColorRGBA.Make((int)((float)i / (float)num * 255), 0, 0, 255));
         //        VxsHelper.DrawVxsSnap(gfxBmp, ellipseForMask.MakeVertexSnap(), ColorRGBA.Make((int)((float)i / (float)num * 255), 0, 0, 255));
         //    }
         //}
     }
 }
 /// <summary>
 /// 将图片加水印下载至本地
 /// </summary>
 /// <param name="sqlvalue">一级(客户、商品或其它)</param>
 /// <param name="SqlType">类型</param>
 /// <param name="dt">数据源</param>
 /// <param name="ImgUrl">水印图片路径</param>
 /// <param name="arguments">二级(批号或其它)</param>
 private void UplaodImg(string sqlvalue, string SqlType, DataTable dt, string ImgUrl, string arguments)
 {
     try
     {
         if (dt.Rows.Count > 0)
         {
             string str = HttpRuntime.AppDomainAppPath;
             //存放质检图片路径
             string filePath = str + "FPImgupload";
             if (!Directory.Exists(filePath))
             {
                 Directory.CreateDirectory(filePath);
             }
             //创建临时文件夹(一级文件夹)
             string url = str + "FPImgupload" + "\\" + SqlType + "\\" + sqlvalue;
             if (!FileExists(url))
             {
                 LogQueue.Write(LogType.Error, "QualityInspectionReport/UplaodImg", "一级文件夹创建失败");
                 throw new Exception("一级文件夹创建失败");
             }
             Create_YZ            YZ     = new Create_YZ();
             string               path   = filePath + "\\" + SqlType + "\\" + sqlvalue;//带印章质检报告图片路径
             string               yzpath = str + ImgUrl;
             System.Drawing.Image image1 = new System.Drawing.Bitmap(829, 1169);
             if (!dt.Columns.Contains("grp"))
             {
                 throw new Exception("数据源表缺少必须分组列:grp");
             }
             //根据二级将图片分组 grp为数据库分组字段,不可删除
             var query = from g in dt.AsEnumerable()
                         group g by new { g1 = g.Field <string>("grp") } into source
                 select new { pihao = source.Key.g1 };
             //重置路径
             string reset = path;
             foreach (var item in query)
             {
                 ////每次循环重置路径
                 path = reset;
                 url  = str + "FPImgupload" + "\\" + SqlType + "\\" + sqlvalue + "\\" + item.pihao;
                 if (!FileExists(url))
                 {
                     LogQueue.Write(LogType.Error, "QualityInspectionReport/UplaodImg", "二级文件夹创建失败");
                     throw new Exception("二级文件夹创建失败");
                 }
                 //拼接上分组字段
                 path = path + "\\" + item.pihao;
                 //Log.Debug("path+", path);
                 var       columns = dt.AsEnumerable().Where <DataRow>(r => r["grp"].ToString() == item.pihao.ToString());
                 DataTable table   = dt.Clone();
                 foreach (DataRow dr in columns)
                 {
                     table.ImportRow(dr);
                 }
                 SaveNewPicture(path, table, YZ, yzpath);
             }
         }
     }
     catch (Exception ex)
     {
         LogQueue.Write(LogType.Error, "QualityInspectionReport/UplaodImg", ex.ToString());
         throw new Exception(ex.ToString());
     }
 }
        public byte[] GetPdfTpuStampeTableBUS(XmlDocument tpu, XmlDocument pru)
        {
            ReportDocument document = new ReportDocument();

            document.setXML(tpu, tpu.DocumentElement.Name);
            System.IO.Stream str = null;
            Hashtable        ht  = new Hashtable();

            XmlDocument XMLData = new XmlDocument();

            XMLData.LoadXml(pru.OuterXml);

            // Estrae i valori dei parametri
            System.Xml.XmlNodeList nl = XMLData.SelectNodes("params/p");
            foreach (System.Xml.XmlNode xn in nl)
            {
                ht.Add(xn.Attributes["name"].Value, xn.InnerText);
            }

            document.SetParameters(ht);

            // Estrae le tabelle
            DataTable        dt          = new DataTable();
            StringCollection sCollection = new StringCollection();

            System.Xml.XmlNodeList nlt = XMLData.SelectNodes("params/t");
            foreach (System.Xml.XmlNode xn in nlt)
            {
                sCollection.Add(xn.InnerXml);
            }
            DataSet ds = new DataSet();

            System.IO.MemoryStream memStream;
            System.IO.StreamWriter sWriter;

            foreach (string tabella in sCollection)
            {
                ds.Tables.Clear();
                memStream = new System.IO.MemoryStream();
                sWriter   = new System.IO.StreamWriter(memStream);
                sWriter.Write(tabella);

                sWriter.Flush();
                memStream.Position = 0;

                ds.ReadXml(memStream);

                if (ds.Tables.Count > 0)
                {
                    dt = ds.Tables[0];
                }

                sWriter.Dispose();
                memStream.Dispose();
            }
            document.AddData(dt);
            byte[] ser = null;
            try
            {
                XDocument xTpu = XDocument.Parse(tpu.InnerXml);
                //elementi picture
                var picturesTag = from nd in xTpu.Root.DescendantNodesAndSelf().OfType <XElement>()
                                  where nd.Name.LocalName.Equals("pictureBox")
                                  select nd;
                //estrae gli attributi delle picture
                var pictures = from nd in picturesTag
                               select new
                {
                    Name     = nd.Attribute("name").Value,
                    FileName = nd.Element("file").Attribute("value").Value,
                    Width    = int.Parse(nd.Attribute("width").Value),
                    Heigth   = int.Parse(nd.Attribute("height").Value)
                };
                //aggiunge le picture alla stampa
                foreach (var pic in pictures)
                {
                    String keyImg = System.IO.Path.GetFileNameWithoutExtension(pic.FileName);

                    Com.Delta.Web.Cache.Types.TpuBinaryResource im =
                        CacheManager <Com.Delta.Web.Cache.Types.TpuBinaryResource> .get(
                            (CacheKeys)Enum.Parse(typeof(CacheKeys), keyImg, true),
                            VincoloType.FILESYSTEM);

                    System.IO.MemoryStream ms = new System.IO.MemoryStream(im.File);
                    System.Drawing.Bitmap  bb = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(ms);
                    document.AddPicture(pic.Name, bb, true);
                }

                ser = document.SerializeToPdfStream();
            }
            catch
            {
            }
            return(ser);
        }