RotateFlip() private method

private RotateFlip ( RotateFlipType rotateFlipType ) : void
rotateFlipType RotateFlipType
return void
Esempio n. 1
1
        public void AddFrame(Bitmap bmp)
        {
            bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);

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

            if (countFrames == 0)
            {
                this.stride = (UInt32)bmpDat.Stride;
                this.width = bmp.Width;
                this.height = bmp.Height;
                CreateStream();
            }

            int result = AviReadingMethods.AVIStreamWrite(aviStream,
                countFrames, 1,
                bmpDat.Scan0,
                (Int32)(stride * height),
                0, 0, 0);

            if (result != 0)
            {
                throw new Exception("Problem podczas otwierania pliku AVI" + result.ToString());
            }

            bmp.UnlockBits(bmpDat);
            countFrames++;
        }
Esempio n. 2
0
        public Image rotateImage(Image img, int angle)
        {
            
            var bmp = new Bitmap(img);

            using (Graphics gfx = Graphics.FromImage(bmp))
            {
                gfx.Clear(Color.White);
                gfx.DrawImage(img, 0, 0, img.Width, img.Height);
            }

            if(angle == 90)
            {
                bmp.RotateFlip(RotateFlipType.Rotate90FlipNone);
            }
            else if(angle == 180 )
            {
                bmp.RotateFlip(RotateFlipType.Rotate180FlipNone);
            }
            else if (angle == 270)
            {
                bmp.RotateFlip(RotateFlipType.Rotate270FlipNone);
            }

            return bmp;
        }
        private void LoadDisplay(PictureBox pBox, Bitmap robotBitmap, Robot robot)
        {
            switch(robot.getOrientation())
            {
                case("W"):
                {
                    //  Rotate 90 degrees counter clockwise
                    robotBitmap.RotateFlip(RotateFlipType.Rotate270FlipNone);
                    pBox.Image = robotBitmap;
                }
                break;
                case ("S"):
                    {
                        //  Rotate 90 degrees counter clockwise
                        robotBitmap.RotateFlip(RotateFlipType.Rotate180FlipNone);
                        pBox.Image = robotBitmap;
                    }
                    break;
                case ("E"):
                    {
                        //  Rotate 90 degrees counter clockwise
                        robotBitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
                        pBox.Image = robotBitmap;
                    }
                    break;
                default:
                    break;
            }

            //  Position the robot's initial position on the arena
            pBox.Location = new Point(X_map(robot.getPositionX()), Y_map(robot.getPositionY()));
        }
Esempio n. 4
0
        public void Draw(Graphics graphics)
        {
            bitmap.Dispose();
            bitmap = new Bitmap("c:/sprite.jpg");

            switch (currentDirrection) {

                case "left": {
                    bitmap.RotateFlip(RotateFlipType.Rotate180FlipY);
                    break;
                }

                case "up": {
                    bitmap.RotateFlip(RotateFlipType.Rotate270FlipX);
                    break;
                }

                case "down": {
                    bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
                    break;
                }

                default: {
                    break;
                }

            }

            graphics.DrawImage(bitmap,displayArea);
        }
        public object UploadPic(PublicOperationUploadPicModel value)
        {
            try
            {
                string picStr = value.picStr;

                byte[] bytes = Convert.FromBase64String(picStr);
                System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
                // Image img = System.Drawing.Image.FromStream(ms);

                string filename = DateTime.Now.ToString("yyyyMMddHHmmssffffff") + ".png";
                //   string DirUrl = HttpContext.Current.Server.MapPath("~/temp/");
                //if (!System.IO.Directory.Exists(DirUrl))      //检测文件夹是否存在,不存在则创建
                //{
                //    System.IO.Directory.CreateDirectory(DirUrl);
                //}
                //string path = AppDomain.CurrentDomain.BaseDirectory + "/temp/";
                //string returnpath = "/temp/" + filename;
                //img.Save(Path.Combine(path, filename));
                var fname  = "/temp/" + filename;
                var ioname = Core.MallIO.GetImagePath(fname);
                // files.Add(ioname);
                try
                {
                    System.Drawing.Bitmap bitImg = new System.Drawing.Bitmap(100, 100);
                    bitImg = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(ms);
                    //bitImg = ResourcesHelper.GetThumbnail(bitImg, 735, 480); //处理成对应尺寸图片
                    //iphone图片旋转
                    switch (value.orientation)
                    {
                    case 3: bitImg.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); break;

                    case 6: bitImg.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone); break;

                    case 8: bitImg.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone); break;

                    default: break;
                    }
                    var path = AppDomain.CurrentDomain.BaseDirectory + "/temp/";
                    bitImg.Save(Path.Combine(path, filename));
                    //Core.MallIO.CreateFile(fname, ms);
                    //file.SaveAs(Path.Combine(path, filename));
                }
                catch (Exception)
                {
                }

                return(new { success = true, Src = ioname, RomoteImage = Core.MallIO.GetRomoteImagePath(ioname) });
            }
            catch (MallException he)
            {
                return(new { success = false, Msg = he.Message });
            }
            catch (Exception e)
            {
                return(new { success = false, Msg = e.Message });
            }
        }
        protected byte[] ResizeImage(byte[] image, int maxHeight = 360)
        {
            byte[] dc;

            System.Drawing.Image oBMP = null;

            using (var ms = new MemoryStream(image))
            {
                oBMP = System.Drawing.Image.FromStream(ms);
                ms.Close();
            }

            UInt16 orientCode = 1;

            try
            {
                using (var ms2 = new MemoryStream(image))
                {
                    var r = new ExifLib.ExifReader(ms2);
                    r.GetTagValue(ExifLib.ExifTags.Orientation, out orientCode);
                }
            }
            catch { }

            int nHeight = maxHeight; // This is 36x10 line:7700 GenScreen
            int nWidth  = int.Parse((Math.Round(decimal.Parse(oBMP.Width.ToString()) * (nHeight / decimal.Parse(oBMP.Height.ToString())))).ToString());

            var nBMP = new System.Drawing.Bitmap(oBMP, nWidth, nHeight);

            using (System.IO.MemoryStream sm = new System.IO.MemoryStream())
            {
                // 1 = do nothing
                if (orientCode == 3)
                {
                    // rotate 180
                    nBMP.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                }
                else if (orientCode == 6)
                {
                    //rotate 90
                    nBMP.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                }
                else if (orientCode == 8)
                {
                    // same as -90
                    nBMP.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
                }
                nBMP.Save(sm, System.Drawing.Imaging.ImageFormat.Jpeg);
                sm.Position = 0;
                dc          = new byte[sm.Length + 1];
                sm.Read(dc, 0, dc.Length); sm.Close();
            }
            oBMP.Dispose(); nBMP.Dispose();

            return(dc);
        }
Esempio n. 7
0
        private bool loadCubeMapSide(int texture, TextureTarget side_target, win.Bitmap image)
        {
            if (image == null)
            {
                image = Properties.Resources.ErrorTexture;

                ImageTexture.Rescale(ref image);
            }

            GL.BindTexture(TextureTarget.TextureCubeMap, texture);

            win.Imaging.BitmapData pixelData;
            win.Rectangle          imgRect;
            IntPtr pTexImage;

            bool?rotCW = null;

            if (side_target == TextureTarget.TextureCubeMapPositiveY)      // Top
            {
                rotCW = false;                                             // CCW
            }
            else if (side_target == TextureTarget.TextureCubeMapNegativeY) // Bottom
            {
                rotCW = true;                                              // CW
            }

            if (rotCW.HasValue)
            {
                if (rotCW.Value)
                {
                    // Clockwise by 90 degrees
                    image.RotateFlip(win.RotateFlipType.Rotate90FlipNone);
                }
                else
                {
                    // Counterclockwise by -90 degrees
                    image.RotateFlip(win.RotateFlipType.Rotate270FlipNone);
                }
            }

            imgRect   = new win.Rectangle(0, 0, image.Width, image.Height);
            pixelData = image.LockBits(imgRect, win.Imaging.ImageLockMode.ReadOnly,
                                       System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            pTexImage = pixelData.Scan0;

            // copy image data into 'target' side of cube map
            GL.TexImage2D(side_target, 0, PixelInternalFormat.Rgba, image.Width, image.Height, 0,
                          PixelFormat.Bgra, PixelType.UnsignedByte, pTexImage);

            image.UnlockBits(pixelData);

            return(true);
        }
Esempio n. 8
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">The current instance of the 
        /// <see cref="T:ImageProcessor.ImageFactory" /> class containing
        /// the image to process.</param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory" /> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            Bitmap newImage = null;
            Image image = factory.Image;

            try
            {
                const int Orientation = (int)ExifPropertyTag.Orientation;
                if (!factory.PreserveExifData && factory.ExifPropertyItems.ContainsKey(Orientation))
                {
                    newImage = new Bitmap(image);

                    int rotationValue = factory.ExifPropertyItems[Orientation].Value[0];
                    switch (rotationValue)
                    {
                        case 1: // Landscape, do nothing
                            break;

                        case 8: // Rotated 90 right
                            // De-rotate:
                            newImage.RotateFlip(RotateFlipType.Rotate270FlipNone);
                            break;

                        case 3: // Bottoms up
                            newImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
                            break;

                        case 6: // Rotated 90 left
                            newImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
                            break;
                    }

                    // Reassign the image.
                    image.Dispose();
                    image = newImage;
                }
            }
            catch (Exception ex)
            {
                if (newImage != null)
                {
                    newImage.Dispose();
                }

                throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
            }

            return image;
        }
Esempio n. 9
0
        public void Histogram(Bitmap image)
        {
            Bitmap d = new Bitmap(256, 1025);
            int[] hist = new int[255];

            for (int i = 0; i < image.Width; i++)
            {
                for (int j = 0; j < image.Height; j++)
                {
                    int br = Convert.ToInt16(image.GetPixel(i, j).GetBrightness() * 50);
                    hist[br]++;
                }
            }

            for (int i = 0; i < 255; i++)
            {
                for (int j = 0; j < hist[i]; j++)
                {
                    d.SetPixel(i, j / 80, Color.Black);
                }
            }

            d.RotateFlip(RotateFlipType.Rotate180FlipNone);
            pictureBox2.Image = d;
        }
Esempio n. 10
0
        private void btnTakePicture_Click(object sender, EventArgs e)
        {
            const string STR_ShowCamera = "Show Camera";
            if (imageResizer1.btnTakePicture.Text == STR_ShowCamera)
            {
                imageResizer1.pctCamera.Visible = true;
                imageResizer1.btnTakePicture.Text = "Take Picture";
                return;
            }
            if (cam != null)
            {
                Cursor.Current = Cursors.WaitCursor;

                if (m_ip != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(m_ip);
                    m_ip = IntPtr.Zero;
                }

                m_ip = cam.Click();
                Bitmap b = new Bitmap(cam.Width, cam.Height, cam.Stride, PixelFormat.Format24bppRgb, m_ip);
                b.RotateFlip(RotateFlipType.RotateNoneFlipY);

                imageResizer1.BaseImage = b;
                imageResizer1.pctCamera.Visible = false;
                imageResizer1.btnTakePicture.Text = STR_ShowCamera;

                Cursor.Current = Cursors.Default;
            }

        }
Esempio n. 11
0
        public void GetHistogram(Bitmap image)
        {
            Bitmap diagram = new Bitmap(256, 512);
            int[] histogram = new int[255];

            for (int i = 0; i < image.Width; i++)
            {
                for (int j = 0; j < image.Height; j++)
                {
                    int br = Convert.ToInt16(image.GetPixel(i, j).GetBrightness() * 100);
                    histogram[br]++;
                }
            }

            for (int i = 0; i < 255; i++)
            {
                for (int j = 0; j < histogram[i]; j++)
                {
                    diagram.SetPixel(i, j / 100, Color.Black);
                }
            }

            diagram.RotateFlip(RotateFlipType.Rotate180FlipNone);
            pictureBox2.Image = diagram;
        }
Esempio n. 12
0
 public void AnalyseLayout_RotatedImage(RotateFlipType? rotation)
 {
     using (var img = new Bitmap(@".\phototest.tif")) {
         if (rotation.HasValue) img.RotateFlip(rotation.Value);
         engine.DefaultPageSegMode = PageSegMode.AutoOsd;
         using (var page = engine.Process(img)) {
             using (var pageLayout = page.GetIterator()) {
                 pageLayout.Begin();
                 do {
                     var result = pageLayout.GetProperties();
                     // Note: The orientation always seem to be 'PageUp' in Tesseract 3.02 according to this test.
                     Assert.That(result.Orientation, Is.EqualTo(Orientation.PageUp));
                     if (rotation == RotateFlipType.Rotate180FlipNone) {
                         // This isn't correct...
                         Assert.That(result.WritingDirection, Is.EqualTo(WritingDirection.LeftToRight));
                         Assert.That(result.TextLineOrder, Is.EqualTo(TextLineOrder.TopToBottom));
                     } else if (rotation == RotateFlipType.Rotate90FlipNone) {
                         Assert.That(result.WritingDirection, Is.EqualTo(WritingDirection.TopToBottom));
                         Assert.That(result.TextLineOrder, Is.EqualTo(TextLineOrder.RightToLeft));
                     } else if (rotation == null) {
                         Assert.That(result.WritingDirection, Is.EqualTo(WritingDirection.LeftToRight));
                         Assert.That(result.TextLineOrder, Is.EqualTo(TextLineOrder.TopToBottom));
                     }
                     // Not sure...
                 } while (pageLayout.Next(PageIteratorLevel.Block));
             }
         }
     }
 }
Esempio n. 13
0
        internal void Set(Bitmap bitmap)
        {
            bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);

            var data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            GL.BindTexture(TextureTarget.Texture2D, tex);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba,
                bitmap.Width, bitmap.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
            bitmap.UnlockBits(data);

            Width = bitmap.Width;
            Height = bitmap.Height;

            bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
        }
Esempio n. 14
0
        public Texture(string _mapPath, bool flipY = true)
        {
            using (Stream s = Interface.GetStreamFromPath (_mapPath)) {

                try {
                    Map = _mapPath;

                    Bitmap bitmap = new Bitmap (s);

                    if (flipY)
                        bitmap.RotateFlip (RotateFlipType.RotateNoneFlipY);

                    BitmapData data = bitmap.LockBits (new System.Drawing.Rectangle (0, 0, bitmap.Width, bitmap.Height),
                        ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                    createTexture (data.Scan0, data.Width, data.Height);

                    bitmap.UnlockBits (data);

                    GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
                    GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

                    GL.GenerateMipmap (GenerateMipmapTarget.Texture2D);

                } catch (Exception ex) {
                    Debug.WriteLine ("Error loading texture: " + Map + ":" + ex.Message);
                }
            }
        }
Esempio n. 15
0
        private Bitmap DrawWheelBtnMouse(Size pictSize, bool icon)
        {
            double ration = icon ? 1.05 : 0.8;
            Bitmap bmp = new Bitmap(pictSize.Width, pictSize.Height);
            Graphics gp = Graphics.FromImage(bmp);
            gp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
            int width = (int)Math.Min(bmp.Width * ration, bmp.Height * ration);
            if (width > Resources.base_mouse.Width)
                width = Resources.base_mouse.Width;
            int height = width;
            Point pos;
            if (icon)
                pos = new Point((bmp.Width - width) / 2, (bmp.Height - height) / 2);
            else
                pos = new Point((bmp.Width - width) / 2, (bmp.Height - height) / 4);
            Rectangle r = new Rectangle(pos, new Size(width, height));
            gp.DrawImage(Resources.base_mouse, r.X, r.Y, r.Width, r.Height);            
            gp.DrawImage(Resources.btn_middle_modifier, r.X, r.Y, r.Width, r.Height);
            DrawTrigger(m_trigger, gp, r);
            gp.DrawImage(Resources.btn_wheel_down, r.X, r.Y, r.Width, r.Height);
            gp.DrawImage(Resources.btn_wheel_up, r.X, r.Y, r.Width, r.Height);            
            gp.Dispose();

            // If buttons are swaped then flip the image
            bool swapedButtons = Win32.GetSystemMetrics(Win32.SM_SWAPBUTTON) == 0 ? false : true;
            if (swapedButtons) bmp.RotateFlip(RotateFlipType.Rotate180FlipY);         
   
            return bmp;
        }
Esempio n. 16
0
        private void HandleLoadingBitmapData(Bitmap bitmap, bool flipY = true)
        {
            /* .net library has methods for converting many image formats so I exploit that by using 
              * .net to convert any filetype to a bitmap.  Then the bitmap is locked into memory so
              * that the garbage collector doesn't touch it, and it is read via OpenGL glTexImage2D. */
            if (flipY) bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);     // bitmaps read from bottom up, so flip it
            Resolution = bitmap.Size;

            // must be Format32bppArgb file format, so convert it if it isn't in that format
            var bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            // set the texture target and then generate the texture ID
            TextureTarget = TextureTarget.Texture2D;
            GPUAddress = GL.GenTexture();

            GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1); // set pixel alignment
            GL.BindTexture(TextureTarget, GPUAddress);     // bind the texture to memory in OpenGL

            //Gl.TexParameteri(TextureTarget, TextureParameterName.GenerateMipmap, 0);
            GL.TexImage2D(TextureTarget, 0, PixelInternalFormat.Rgba8, bitmapData.Width, bitmapData.Height, 0, Pencil.Gaming.Graphics.PixelFormat.Bgra, Pencil.Gaming.Graphics.PixelType.UnsignedByte, bitmapData.Scan0);
            GL.TexParameter(TextureTarget, TextureParameterName.TextureMagFilter, (int)MagFilter);
            GL.TexParameter(TextureTarget, TextureParameterName.TextureMinFilter, (int)MinFilter);


            if (ShouldGenerateMipmaps) GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);

            NeedsUpdate = false;

            bitmap.UnlockBits(bitmapData);
        }
        public void LoadTexture(string textureId, string path)
        {
            Debug.Assert(File.Exists(path));

            var id = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2D, id);

            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

            var image = new Bitmap(path);
            var width = image.Width;
            var height = image.Height;

            image.RotateFlip(RotateFlipType.Rotate180FlipY);

            var data = image.LockBits(
                new Rectangle(0, 0, width, height),
                ImageLockMode.ReadOnly,
                DrawingPixelFormat.Format32bppArgb);

            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, width, height, 0,
                PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);

            image.UnlockBits(data);

            _textureDatabase.Add(textureId, new Texture(id, width, height));
        }
Esempio n. 18
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            Bitmap newImage = null;
            Image image = factory.Image;

            try
            {
                RotateFlipType rotateFlipType = this.DynamicParameter;

                newImage = new Bitmap(image);

                // Flip
                newImage.RotateFlip(rotateFlipType);

                image.Dispose();
                image = newImage;
            }
            catch (Exception ex)
            {
                if (newImage != null)
                {
                    newImage.Dispose();
                }

                throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
            }

            return image;
        }
        protected override System.Drawing.Image GetThumbnailInner()
        {
            Bitmap result = new Bitmap( 80, 48, PixelFormat.Format32bppArgb );

            using( Bitmap portrait = new Bitmap( 48, 32, PixelFormat.Format8bppIndexed ) )
            {
                Bitmap wholeImage = ToBitmap();
                wholeImage.CopyRectangleToPointNonIndexed(
                    ThumbnailRectangle,
                    result,
                    new Point( ( 48 - ThumbnailRectangle.Width ) / 2, ( 48 - ThumbnailRectangle.Height ) / 2 ),
                    Palettes[0],
                    false );

                ColorPalette palette2 = portrait.Palette;
                Palette.FixupColorPalette( palette2, Palettes );
                portrait.Palette = palette2;
                wholeImage.CopyRectangleToPoint( PortraitRectangle, portrait, Point.Empty, Palettes[8], false );
                portrait.RotateFlip( RotateFlipType.Rotate270FlipNone );

                portrait.CopyRectangleToPointNonIndexed( new Rectangle( 0, 0, 32, 48 ), result, new Point( 48, 0 ), Palettes[8], false );
            }

            return result;
        }
Esempio n. 20
0
        private void LoadBitmap(Bitmap BitmapImage, bool FlipY = true)
        {
            /* .net library has methods for converting many image formats so I exploit that by using 
             * .net to convert any filetype to a bitmap.  Then the bitmap is locked into memory so
             * that the garbage collector doesn't touch it, and it is read via OpenGL glTexImage2D. */
            if (FlipY) BitmapImage.RotateFlip(RotateFlipType.RotateNoneFlipY);     // bitmaps read from bottom up, so flip it
            this.Size = BitmapImage.Size;

            // must be Format32bppArgb file format, so convert it if it isn't in that format
            BitmapData bitmapData = BitmapImage.LockBits(new Rectangle(0, 0, BitmapImage.Width, BitmapImage.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            // set the texture target and then generate the texture ID
            this.TextureTarget = TextureTarget.Texture2D;
            this.TextureID = Gl.GenTexture();

            Gl.PixelStorei(PixelStoreParameter.UnpackAlignment, 1); // set pixel alignment
            Gl.BindTexture(TextureTarget, TextureID);     // bind the texture to memory in OpenGL

            //Gl.TexParameteri(TextureTarget, TextureParameterName.GenerateMipmap, 0);
            Gl.TexImage2D(TextureTarget, 0, PixelInternalFormat.Rgba8, BitmapImage.Width, BitmapImage.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, bitmapData.Scan0);
            Gl.TexParameteri(TextureTarget, TextureParameterName.TextureMagFilter, TextureParameter.Nearest);
            Gl.TexParameteri(TextureTarget, TextureParameterName.TextureMinFilter, TextureParameter.Nearest);//(int)TextureParam.Linear);   // linear filter

            BitmapImage.UnlockBits(bitmapData);
            BitmapImage.Dispose();
        }
Esempio n. 21
0
        protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            try
            {
                HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
                if (flipConnections.Contains(request.GetClientIp()) || bwConnections.Contains(request.GetClientIp()))
                {
                    System.Drawing.Imaging.ImageFormat fmt;
                    MediaTypeHeaderValue mediatype = response.Content.Headers.ContentType;
                    if (response.IsSuccessStatusCode && ImageFormat(mediatype, out fmt))
                    {
                        var streamin = await response.Content.ReadAsStreamAsync();

                        using (Bitmap bmp = new Bitmap(Image.FromStream(streamin)))
                        {
                            if(flipConnections.Contains(request.GetClientIp()))
                                bmp.RotateFlip(RotateFlipType.RotateNoneFlipXY);
                            if(bwConnections.Contains(request.GetClientIp()))
                                MakeBW(bmp);
                            var msout = new MemoryStream();
                            bmp.Save(msout, fmt);
                            msout.Position=0;
                            response.Content = new StreamContent(msout);
                            response.Content.Headers.ContentType = mediatype;
                        }
                    }
                }
                return response;
            }
            catch (Exception ex)
            {
                var response = request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
                return response;
            }
        }
Esempio n. 22
0
        /// <summary>Adds a new frame to the AVI stream</summary>
        /// <param name="bmp">The image to add</param>
        public void AddFrame(Bitmap bmp, uint uiQuality, short shBitCount)
        {

            bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);

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

            if (countFrames == 0)
            {
                //this is the first frame - get size and create a new stream
                this.stride = (UInt32)bmpDat.Stride;
                this.width = bmp.Width;
                this.height = bmp.Height;
                CreateStream(uiQuality,shBitCount);
            }

            int result = Avi.AVIStreamWrite(aviStream,
                countFrames, 1,
                bmpDat.Scan0, //pointer to the beginning of the image data
                (Int32)(stride * height),
                0, 0, 0);

            if (result != 0)
            {
                throw new Exception("Error in AVIStreamWrite: " + result.ToString());
            }

            bmp.UnlockBits(bmpDat);
            countFrames++;
        }
Esempio n. 23
0
        public static uint LoadTexture(Bitmap bitmap)
        {
            uint texture;
            Rectangle rectangle;														// The Rectangle For Locking The Bitmap In Memory
            BitmapData bitmapData = null;												// The Bitmap's Pixel Data

            // Load The Bitmap
            bitmap.RotateFlip(RotateFlipType.RotateNoneFlipNone);					// Flip The Bitmap Along The Y-Axis
            rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height);			// Select The Whole Bitmap

            // Get The Pixel Data From The Locked Bitmap
            bitmapData = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            GL.GenTextures(1, out texture);												// Create One Texture

            GL.BindTexture(TextureTarget.Texture2D, texture);						// Typical Texture Generation Using Data From The Bitmap
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
            // Generate The Texture
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bitmap.Width, bitmap.Height, 0, Gr.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bitmapData.Scan0);

            if(bitmap != null)
            {
                bitmap.UnlockBits(bitmapData);										// Unlock The Pixel Data From Memory
                bitmap.Dispose();													// Clean Up The Bitmap
            }
            return texture;
        }
        /// <summary>
        /// To display the image, create a Bitmap (easist way to render to a winforms picturebox) 
        /// Write our image data pixel by pixel to the new bitmap. 
        /// </summary>
        /// <param name="colorData"></param>
        /// <param name="header"></param>
        /// <returns></returns>
        public Bitmap GetImageFromColorData(Individual individual, int width, int height)
        {
            Bitmap image = new Bitmap(width, height);

            var colorData = individual.Genome;

            for (int x = image.Width - 1; x > 0; x--)
            {
                for (int y = image.Height - 1; y > 0; y--)
                {
                    int index = TranslateXYToListIndex(x, y, image.Width);

                    if (index >= colorData.Length)
                        index = colorData.Length - 1;

                    Color color = Color.FromArgb(colorData[index].R, colorData[index].G, colorData[index].B);
                    image.SetPixel(x, y, color);
                }
            }

            //Flip the bmp to display it on screen
            image.RotateFlip(RotateFlipType.Rotate270FlipX);

            return image;
        }
Esempio n. 25
0
        public static Bitmap ScreenShot(int xx, int yy, int width, int height, ReadBufferMode buffer)
        {
            Bitmap transfermap = new Bitmap(width, height);
            System.Drawing.Imaging.BitmapData data =
               transfermap.LockBits(new Rectangle(0, 0, transfermap.Width, transfermap.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly,
                            System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            GL.ReadBuffer(buffer);
            GL.ReadPixels(xx, yy, transfermap.Width, transfermap.Height, OpenTK.Graphics.OpenGL4.PixelFormat.Rgba, PixelType.UnsignedByte, data.Scan0);

            unsafe
            {
                int PixelSize = 4;
                unsafe
                {
                    for (int y = 0; y < data.Height; y++)
                    {
                        byte* row = (byte*)data.Scan0 + (y * data.Stride);

                        for (int x = 0; x < data.Width; x++)
                        {
                            byte r = row[x * PixelSize + 2];
                            byte b = row[x * PixelSize];
                            row[x * PixelSize] = r;
                            row[x * PixelSize + 2] = b;
                        }
                    }
                }
            }

            transfermap.UnlockBits(data);
            transfermap.RotateFlip(RotateFlipType.RotateNoneFlipY);
            return transfermap;
        }
Esempio n. 26
0
        public static int LoadTexture(string textureName, bool repeat, bool rotate)
        {
            if (textureName != null)
            {
                int id = GL.GenTexture();

                Bitmap imagen = new Bitmap(textureName);
                if (rotate)
                    imagen.RotateFlip(RotateFlipType.Rotate180FlipY);
                BitmapData bitmapdata = imagen.LockBits(new Rectangle(0, 0, imagen.Width, imagen.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                GL.BindTexture(TextureTarget.Texture2D, id);
                if (repeat)
                {
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
                }
                else
                {
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
                }

                GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (float)TextureEnvMode.Modulate);

                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.GenerateMipmap, 1);
                GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgb, imagen.Width, imagen.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgr, PixelType.UnsignedByte, bitmapdata.Scan0);

                imagen.UnlockBits(bitmapdata);
                imagen.Dispose();

                return id;
            }
            return 0;
        }
Esempio n. 27
0
        private void button2_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            // Release any previous buffer
            if (m_ip != IntPtr.Zero)
            {
                Marshal.FreeCoTaskMem(m_ip);
                m_ip = IntPtr.Zero;
            }

            // capture image
            m_ip = capturer.Click();
            Bitmap b = new Bitmap(capturer.Width, capturer.Height, capturer.Stride, PixelFormat.Format24bppRgb, m_ip);

            // If the image is upsidedown
            b.RotateFlip(RotateFlipType.RotateNoneFlipY);
            capturer.Dispose();
            capturer = null;
            GC.Collect();

            image.Image = b;
            originalImage = (Image) image.Image.Clone();
            disableControl(false);
            button3.Visible = true;

            Cursor.Current = Cursors.Default;
        }
Esempio n. 28
0
        internal ComBitmap(IntPtr bitmapData, int width, int height, int stride, PixelFormat format)
        {
            _bitmapData = bitmapData;

            _myBitmap = new Bitmap(width, height, stride, format, bitmapData);
            _myBitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
        }
        public static Bitmap AddReflection(Image bmp, int percentage, int transparency)
        {
            Bitmap b = new Bitmap(bmp);
            b.RotateFlip(RotateFlipType.RotateNoneFlipY);
            b = b.Clone(new Rectangle(0, 0, b.Width, (int)(b.Height * ((float)percentage / 100))), PixelFormat.Format32bppArgb);
            BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

            byte alpha;
            int nOffset = bmData.Stride - b.Width * 4;
            transparency.Mid(0, 255);

            unsafe
            {
                byte* p = (byte*)(void*)bmData.Scan0;

                for (int y = 0; y < b.Height; ++y)
                {
                    for (int x = 0; x < b.Width; ++x)
                    {
                        alpha = (byte)(transparency - transparency * (y + 1) / b.Height);
                        if (p[3] > alpha) p[3] = alpha;
                        p += 4;
                    }
                    p += nOffset;
                }
            }

            b.UnlockBits(bmData);

            return b;
        }
        /// <summary>
        /// Gets the file bytes.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="uploadedFile">The uploaded file.</param>
        /// <returns></returns>
        public override Stream GetFileContentStream( HttpContext context, HttpPostedFile uploadedFile )
        {
            if ( uploadedFile.ContentType == "image/svg+xml" )
            {
                return base.GetFileContentStream( context, uploadedFile );
            }
            else
            {
                Bitmap bmp = new Bitmap( uploadedFile.InputStream );

                // Check to see if we should flip the image.
                var exif = new EXIFextractor( ref bmp, "\n" );
                if ( exif["Orientation"] != null )
                {
                    RotateFlipType flip = OrientationToFlipType( exif["Orientation"].ToString() );

                    // don't flip if orientation is correct
                    if ( flip != RotateFlipType.RotateNoneFlipNone )
                    {
                        bmp.RotateFlip( flip );
                        exif.setTag( 0x112, "1" ); // reset orientation tag
                    }
                }

                if ( context.Request.QueryString["enableResize"] != null )
                {
                    Bitmap resizedBmp = RoughResize( bmp, 1024, 768 );
                    bmp = resizedBmp;
                }

                var stream = new MemoryStream();
                bmp.Save( stream, ContentTypeToImageFormat( uploadedFile.ContentType ) );
                return stream;
            }
        }
Esempio n. 31
0
        /// <summary>
        /// Converts the pixel data to an image
        /// </summary>
        /// <returns></returns>
        public System.Drawing.Bitmap ToImage(RotateFlipType rotation = RotateFlipType.Rotate180FlipX)
        {
            byte[] byteData = new byte[Data.Length];
            Buffer.BlockCopy(Data, 0, byteData, 0, Data.Length);

            PixelFormat format = PixelFormat.Undefined;

            if (BytesPerPixel == 1)
            {
                format = PixelFormat.Format8bppIndexed;
            }
            else if (BytesPerPixel == 2)
            {
                format = PixelFormat.Format16bppRgb555;
            }
            else if (BytesPerPixel == 3)
            {
                format = PixelFormat.Format24bppRgb;
            }
            else if (BytesPerPixel == 4)
            {
                format = PixelFormat.Format32bppArgb;
            }
            else
            {
                throw new Exception(string.Format("Unknown pixel format for byte count: {0}", BytesPerPixel));
            }

            System.Drawing.Bitmap image = CopyDataToBitmap(ImageWidth, ImageHeight, byteData, format);
            image.RotateFlip(rotation);

            return(image);
        }
Esempio n. 32
0
        /// <summary>
        /// Draw Reflection
        /// </summary>
        /// <param name="img">Set Image</param>
        /// <param name="toBG">Set Color of Background</param>
        /// <param name="RotateFlipType">Rotation Type. Default value is Rotate180FlipX</param>
        /// <param name="LinearGradientMode">Gradient Mode. Default value is Vertical</param>
        /// <param name="Length">Length of the Mirror. Default value is 100</param>
        /// <returns></returns>
        public static Image DrawReflection(Image img, Color toBG,
                                           RotateFlipType RotateFlipType         = RotateFlipType.Rotate180FlipX,
                                           LinearGradientMode LinearGradientMode = LinearGradientMode.Vertical,
                                           int Length = 100) // img is the original image.
        {
            //This is the static function that generates the reflection...
            int height = img.Height + Length;                                                                                               //Added height from the original height of the image.

            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(img.Width, height, PixelFormat.Format64bppPArgb);                         //A new bitmap.
            Brush brsh = new LinearGradientBrush(new Rectangle(0, 0, img.Width + 10, height), Color.Transparent, toBG, LinearGradientMode); //The Brush that generates the fading effect to a specific color of your background.

            bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);                                                            //Sets the new bitmap's resolution.
            using (System.Drawing.Graphics grfx = System.Drawing.Graphics.FromImage(bmp))                                                   //A graphics to be generated from an image (here, the new Bitmap we've created (bmp)).
            {
                System.Drawing.Bitmap bm = (System.Drawing.Bitmap)img;                                                                      //Generates a bitmap from the original image (img).
                grfx.DrawImage(bm, 0, 0, img.Width, img.Height);                                                                            //Draws the generated bitmap (bm) to the new bitmap (bmp).
                System.Drawing.Bitmap bm1 = (System.Drawing.Bitmap)img;                                                                     //Generates a bitmap again from the original image (img).
                bm1.RotateFlip(RotateFlipType);                                                                                             //Flips and rotates the image (bm1).
                grfx.DrawImage(bm1, 0, img.Height);                                                                                         //Draws (bm1) below (bm) so it serves as the reflection image.
                Rectangle rt = new Rectangle(0, img.Height, img.Width, Length);                                                             //A new rectangle to paint our gradient effect.
                grfx.FillRectangle(brsh, rt);                                                                                               //Brushes the gradient on (rt).
            }

            return(bmp); //Returns the (bmp) with the generated image.
        }
Esempio n. 33
0
 private Bitmap ReadFrameBitmap(AviSynthClip asc, int position)
 {
     Bitmap bmp = null;
     try
     {
         bmp = new Bitmap(asc.VideoWidth, asc.VideoHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
         // Lock the bitmap's bits.
         Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
         System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
         try
         {
             // Get the address of the first line.
             IntPtr ptr = bmpData.Scan0;
             // Read data
             asc.ReadFrame(ptr, bmpData.Stride, position);
         }
         finally
         {
             // Unlock the bits.
             bmp.UnlockBits(bmpData);
         }
         bmp.RotateFlip(RotateFlipType.Rotate180FlipX);
         return bmp;
     }
     catch (Exception)
     {
         if (bmp != null) bmp.Dispose();
         throw;
     }
 }
Esempio n. 34
0
    static void Main()
    {
        // A simple source for demonstration purposes. Modify this path as necessary.
        string[] files  = System.IO.Directory.GetFiles(@"C:\Users\Public\Pictures\Sample Pictures", "*.jpg");
        string   newDir = @"C:\Users\Public\Pictures\Sample Pictures\Modified";

        System.IO.Directory.CreateDirectory(newDir);

        //  Method signature: Parallel.ForEach(IEnumerable<TSource> source, Action<TSource> body)
        Parallel.ForEach(files, currentFile =>
        {
            // The more computational work you do here, the greater
            // the speedup compared to a sequential foreach loop.
            string filename = System.IO.Path.GetFileName(currentFile);
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(currentFile);

            bitmap.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
            bitmap.Save(System.IO.Path.Combine(newDir, filename));

            // Peek behind the scenes to see how work is parallelized.
            // But be aware: Thread contention for the Console slows down parallel loops!!!
            Console.WriteLine("Processing {0} on thread {1}", filename,
                              Thread.CurrentThread.ManagedThreadId);
        }                   //close lambda expression
                         ); //close method invocation

        // Keep the console window open in debug mode.
        Console.WriteLine("Processing complete. Press any key to exit.");
        Console.ReadKey();
    }
Esempio n. 35
0
 void BtnSnapClick(object sender, EventArgs e)
 {
     m_ip=cam.Click();
     b = new Bitmap(cam.Width, cam.Height, cam.Stride, PixelFormat.Format24bppRgb,m_ip);
     b.RotateFlip(RotateFlipType.RotateNoneFlipY);
     this.Close();
 }
Esempio n. 36
0
        /// <summary>
        /// Converts the pixel data to an image
        /// </summary>
        /// <returns></returns>
        public System.Drawing.Bitmap ToImage(RotateFlipType rotation = RotateFlipType.Rotate180FlipX)
        {
            PixelFormat format = PixelFormat.Undefined;

            if (BytesPerPixel == 1)
            {
                format = PixelFormat.Format8bppIndexed;
            }
            else if (BytesPerPixel == 2)
            {
                format = PixelFormat.Format16bppRgb555;
            }
            else if (BytesPerPixel == 3)
            {
                format = PixelFormat.Format24bppRgb;
            }
            else if (BytesPerPixel == 4)
            {
                format = PixelFormat.Format32bppArgb;
            }
            else if (BytesPerPixel == 6)
            {
                format = PixelFormat.Format48bppRgb;
            }
            else if (BytesPerPixel == 8)
            {
                format = PixelFormat.Format64bppArgb;
            }
            else
            {
                throw new DjvuFormatException($"Unknown pixel format for byte count: {BytesPerPixel}");
            }

            GCHandle hData = default(GCHandle);

            System.Drawing.Bitmap image = null;
            try
            {
                hData = GCHandle.Alloc(Data, GCHandleType.Pinned);
                image = CopyDataToBitmap(Width, Height, hData.AddrOfPinnedObject(), Data.Length, format);
            }
            catch (ArgumentException aex)
            {
                throw new DjvuAggregateException("Failed to copy data to Sytem.Drawing.Bitmap.", aex);
            }
            finally
            {
                if (hData.IsAllocated)
                {
                    hData.Free();
                }
            }

            image.RotateFlip(rotation);

            return(image);
        }
Esempio n. 37
0
        public void Rotate(int pageIndex)
        {
            BitmapImage bitmapImage = this.m_Pages[pageIndex].BitmapImage;

            System.Drawing.Bitmap bitmap = this.BitmapFromSource(bitmapImage);
            bitmap.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
            System.Windows.Media.Imaging.BitmapImage flippedBitmapImage = this.BitmapImageFromBitmap(bitmap);
            this.m_Pages[pageIndex].BitmapImage = flippedBitmapImage;
        }
Esempio n. 38
0
 //----------------------------------------------------
 // Mirror the image
 //----------------------------------------------------
 public static void Mirror(System.Drawing.Bitmap from, ref System.Drawing.Bitmap to)
 {
     if (from == null)
     {
         return;
     }
     from.RotateFlip(RotateFlipType.Rotate180FlipY);
     to = from.Clone() as Bitmap;
 }
Esempio n. 39
0
        /// <summary>
        /// 将图片转换为指定的字节流
        /// </summary>
        /// <param name="filePath">图片路径</param>
        /// <returns>指定的字节流</returns>
        public static byte[] ConvertToByte(String filePath)
        {
            var m  = new System.IO.MemoryStream();
            var bp = new System.Drawing.Bitmap(filePath);

            bp.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone); //指定不进行旋转Rotate270FlipNone
            bp.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);            //将此图像以指定的格式保存到指定的流中。
            byte[] imgByte = m.GetBuffer();                                 //从内存缓冲区中读取
            return(imgByte);
        }
Esempio n. 40
0
        public void RenderBitmap()
        {
            Dispatcher.Invoke(new Action(() =>
            {
                int?OldID = TextureID;

                TextureID = GL.GenTexture();

                if (OldID.HasValue)
                {
                    GL.DeleteTexture(OldID.Value);
                }

                if (CurrentBitmap != null)
                {
                    using (System.Drawing.Bitmap iconOriginal = new System.Drawing.Bitmap(CurrentBitmap.Width, Math.Min(Math.Abs(CurrentBitmap.Height - (int)CurrentHeight), CalmpHeight), CurrentBitmap.PixelFormat))
                        using (Graphics g = Graphics.FromImage(iconOriginal))
                        {
                            if (DynSize)
                            {
                                this.SetOverlaySize((iconOriginal.Width / 15.0f) * 0.0254f); //PPI to Meters
                            }
                            g.DrawImage(CurrentBitmap, new Rectangle(0, 0, iconOriginal.Width, iconOriginal.Height), new Rectangle(0, (int)CurrentHeight, iconOriginal.Width, iconOriginal.Height), GraphicsUnit.Pixel);

                            iconOriginal.RotateFlip(RotateFlipType.RotateNoneFlipY);
                            System.Drawing.Imaging.BitmapData TextureData =
                                iconOriginal.LockBits(
                                    new System.Drawing.Rectangle(0, 0, iconOriginal.Width, iconOriginal.Height),
                                    System.Drawing.Imaging.ImageLockMode.ReadOnly,
                                    System.Drawing.Imaging.PixelFormat.Format32bppPArgb
                                    );

                            GL.BindTexture(TextureTarget.Texture2D, TextureID.Value);
                            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, TextureData.Width, TextureData.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Rgba, PixelType.UnsignedByte, TextureData.Scan0);
                            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
                            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
                            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Clamp);
                            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Clamp);

                            iconOriginal.UnlockBits(TextureData);

                            WPFTexture             = new Texture_t();
                            WPFTexture.eType       = EGraphicsAPIConvention.API_OpenGL;
                            WPFTexture.eColorSpace = EColorSpace.Auto;
                            WPFTexture.handle      = (IntPtr)TextureID.Value;

                            if (Controller != null)
                            {
                                OpenVR.Overlay.SetOverlayTexture(this.Handle, ref WPFTexture);
                            }
                        }
                }
            }));
        }
Esempio n. 41
0
        public System.Drawing.Bitmap ExportVertexColoursToBitmap()
        {
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(this.Width * 24 + 1, this.Height * 24 + 1);

            for (int x = 0; x < this.Width; x++)
            {
                for (int y = 0; y < this.Height; y++)
                {
                    this._TRRNs[x, y].ExportColoursToBitmap(bitmap);
                }
            }
            bitmap.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY);
            return(bitmap);
        }
        private Bitmap GetBitmap(int width, int height)
        {
            System.Drawing.Bitmap bitmap = null;

            bitmap = new System.Drawing.Bitmap(width, height);
            System.Drawing.Imaging.BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            //GL.ReadBuffer(ReadBufferMode.ColorAttachment0);
            GL.ReadBuffer(ReadBufferMode.ColorAttachment0);

            GL.ReadPixels(0, 0, width, height, PixelFormat.Bgr, PixelType.UnsignedByte, data.Scan0);
            bitmap.UnlockBits(data);
            bitmap.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY);
            return(bitmap);
        }
Esempio n. 43
0
        public System.Drawing.Bitmap ExportHeightmapToBitmap()
        {
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(this.Width * 24 + 1, this.Height * 24 + 1);

            for (int x = 0; x < this.Width; x++)
            {
                for (int y = 0; y < this.Height; y++)
                {
                    this._TRRNs[x, y].ExportHeightsToBitmap(bitmap, this.GetMaxHeight(), this.GetMinHeight());
                }
            }
            bitmap.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY);
            return(bitmap);
        }
        public void SaveToFileBlue()
        {
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Image.GetLength(0), Image.GetLength(1), System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            for (int i = 0; i < Image.GetLength(0); i++)
            {
                for (int j = 0; j < Image.GetLength(1); j++)
                {
                    bmp.SetPixel(i, j, System.Drawing.Color.FromArgb(Image[i, j].B, Image[i, j].B, Image[i, j].B));
                }
            }
            bmp.RotateFlip(RotateFlipType.Rotate270FlipY);
            //bmp.Save(Label + this.GetHashCode().ToString() + ".png");
            bmp.Save(name + "_edited.png");
        }
Esempio n. 45
0
 public MarqueeDisplayPage15(System.Drawing.Bitmap pLast, System.Drawing.Bitmap pNew, LedEffectsSetting pSetting)
 {
     this.effect = pSetting;
     this.step   = (float)(20 / this.effect.EntrySpeed);
     pNew.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);
     if (pLast == null)
     {
         this.oldBitmap = new System.Drawing.Bitmap(pNew.Width, pNew.Height);
     }
     else
     {
         this.oldBitmap = pLast;
     }
     this.newBitmap = pNew;
     this.Exit      = MarqueeDisplay.getExtInstance(pNew, pSetting);
 }
Esempio n. 46
0
        /// <summary>
        /// Creates an Image with a Glass Table effect
        /// </summary>
        /// <param name="_Image">Original image</param>
        /// <param name="_BackgroundColor">New image background color</param>
        /// <param name="_Reflectivity">Reflectivity (0 to 255)</param>
        public static Image DrawReflection(Image Image, Color BackColor, int Reflectivity)
        {
            if (Reflectivity > 255)
            {
                Reflectivity = 255;
            }

            // Calculate the size of the new image
            int height = (int)(Image.Height + (Image.Height * ((float)Reflectivity / 255)));

            System.Drawing.Bitmap newImage = new System.Drawing.Bitmap(Image.Width, height, PixelFormat.Format24bppRgb);
            newImage.SetResolution(Image.HorizontalResolution, Image.VerticalResolution);

            using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(newImage))
            {
                // Initialize main graphics buffer
                graphics.Clear(BackColor);
                graphics.DrawImage(Image, new Point(0, 0));
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Rectangle destinationRectangle = new Rectangle(0, Image.Size.Height, Image.Size.Width, Image.Size.Height);

                // Prepare the reflected image
                int   reflectionHeight = (Image.Height * Reflectivity) / 255;
                Image reflectedImage   = new System.Drawing.Bitmap(Image.Width, reflectionHeight);

                // Draw just the reflection on a second graphics buffer
                using (System.Drawing.Graphics gReflection = System.Drawing.Graphics.FromImage(reflectedImage))
                {
                    gReflection.DrawImage(Image, new Rectangle(0, 0, reflectedImage.Width, reflectedImage.Height),
                                          0, Image.Height - reflectedImage.Height, reflectedImage.Width, reflectedImage.Height, GraphicsUnit.Pixel);
                }
                reflectedImage.RotateFlip(RotateFlipType.RotateNoneFlipY);
                Rectangle imageRectangle = new Rectangle(destinationRectangle.X, destinationRectangle.Y,
                                                         destinationRectangle.Width, (destinationRectangle.Height * Reflectivity) / 255);

                // Draw the image on the original graphics
                graphics.DrawImage(reflectedImage, imageRectangle);

                // Finish the reflection using a gradiend brush
                LinearGradientBrush brush = new LinearGradientBrush(imageRectangle,
                                                                    Color.FromArgb(255 - Reflectivity, BackColor),
                                                                    BackColor, 90, false);
                graphics.FillRectangle(brush, imageRectangle);
            }

            return(newImage);
        }
Esempio n. 47
0
        public override Texture Load(IResource resource, LoaderParameters parameters)
        {
            Stream str = resource.OpenStream();

            SD.Bitmap bitmap = new SD.Bitmap(str);

            ImageLoaderParameters imageParams = parameters as ImageLoaderParameters;

            if (imageParams != null)
            {
                if (imageParams.FlipImage)
                {
                    bitmap.RotateFlip(SD.RotateFlipType.RotateNoneFlipY);
                }
            }

            byte[] data = GetData(bitmap);
            SD.Imaging.PixelFormat pixelFormat = bitmap.PixelFormat;
            Color[] colors = null;
            switch (pixelFormat)
            {
            case SD.Imaging.PixelFormat.Format32bppArgb:
                colors = GetRGBA(bitmap, data);
                break;

            case SD.Imaging.PixelFormat.Format24bppRgb:
                colors = GetRGB(bitmap, data);
                break;

            case SD.Imaging.PixelFormat.Format8bppIndexed:
                colors = GetIndexed(bitmap, data);
                break;

            default:
                throw new InvalidOperationException("Cannot read from that format encoding");
            }

            Texture2D tex = new Texture2D(bitmap.Width, bitmap.Height, true, SurfaceFormat.Color, new DataBuffer <Color>(colors));

            tex.Name = resource.Name;

            bitmap.Dispose();
            str.Close();

            return(tex);
        }
Esempio n. 48
0
        public static byte[] AutoRotate(byte[] imageBytes, ImageMetadata metadata = null)
        {
            try
            {
                using (System.Drawing.Bitmap from = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(new MemoryStream(imageBytes)))
                {
                    var exif = new ExifTagCollection(from);
                    if (metadata != null)
                    {
                        metadata.ReadExif(exif);
                    }

                    if (exif["Orientation"] != null)
                    {
                        RotateFlipType flip = OrientationToFlipType(exif["Orientation"].Value);

                        if (flip != RotateFlipType.RotateNoneFlipNone) // don't flip of orientation is correct
                        {
                            from.RotateFlip(flip);
                            try
                            {
                                //exif.setTag(0x112, "1"); // Optional: reset orientation tag
                            }
                            catch { }

                            MemoryStream ms = new MemoryStream();
                            from.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                            return(Stream2Bytes(ms));
                        }
                        else
                        {
                            return(imageBytes);
                        }
                    }
                    else
                    {
                        return(imageBytes);
                    }
                }
            }

            catch { }
            return(null);
        }
Esempio n. 49
0
        private void CaptureDevice_NewFrameAvailableEvent(string deviceType, int deviceIndex, System.Drawing.Bitmap bmp)
        {
            Action displayFrame = delegate
            {
                if (chb_FlipFrame.IsChecked == true)
                {
                    bmp.RotateFlip(RotateFlipType.RotateNoneFlipX);
                }
                img_Preview.Source = Utilities.ToBitmapImage(bmp, ImageFormat.Jpeg);
                Bitmap buf = new Bitmap(bmp);

                if (isVideoRecording)
                {
                    videoWriter.WriteVideoFrame(buf);
                }
            };

            img_Preview.Dispatcher.Invoke(displayFrame);
            currentFrame = bmp;
        }
Esempio n. 50
0
 public void Rotate(System.Drawing.RotateFlipType rotate)
 {
     try
     {
         System.Drawing.Bitmap B = this.Bitmap.ToBitmap();
         B.RotateFlip(rotate);
         using (MemoryStream memoryStream = new MemoryStream())
         {
             B.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
             B.Dispose();
             memoryStream.Seek(0, SeekOrigin.Begin);
             byte[] data = new byte[memoryStream.Length];
             memoryStream.Read(data, 0, (int)memoryStream.Length);
             _bitmap = new ByteArrayBitmap(data);
         }
     }
     catch (Exception ee)
     {
         DebugMessageLogger.LogError(ee);
     }
 }
Esempio n. 51
0
        /// <summary>
        /// Make a <see cref="Bitmap"/> object from the current OpenTK screen buffer
        /// </summary>
        /// <returns><see cref="Bitmap"/> object</returns>
        public async Task <Bitmap> TakeScreenshotAsync()
        {
            if (Window == null)
            {
                throw new NullReferenceException(nameof(Window));
            }

            var clientRectangle = new Rectangle(new Point(Window.ClientRectangle.X, Window.ClientRectangle.Y), new Size(Window.ClientSize.Width, Window.ClientSize.Height));

            bool complete = false;

            var        bitmap = new Bitmap(clientRectangle.Width, clientRectangle.Height);
            BitmapData data   = bitmap.LockBits(clientRectangle, ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            DrawThread.Scheduler.Add(() =>
            {
                if (GraphicsContext.CurrentContext == null)
                {
                    throw new GraphicsContextMissingException();
                }

                OpenTK.Graphics.OpenGL.GL.ReadPixels(0, 0, clientRectangle.Width, clientRectangle.Height, OpenTK.Graphics.OpenGL.PixelFormat.Bgr, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, data.Scan0);
                complete = true;
            });

            await Task.Run(() =>
            {
                while (!complete)
                {
                    Thread.Sleep(50);
                }
            });

            bitmap.UnlockBits(data);
            bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);

            return(bitmap);
        }
Esempio n. 52
0
        private void ApplyTex(Bitmap TexBitmap, int GLTexture)
        {
            try
            {
                if (TexBitmap != null)
                {
                    //Reads hardware limitation
                    int maxTexSize;
                    GL.GetInteger(GetPName.MaxTextureSize, out maxTexSize);

                    //Compatibility with onboard GPUs
                    Bitmap TextureBitmap = ResizeToPowerOf2(TexBitmap, Math.Min(maxTexSize, LIMITIMAGEDIMENSIONSTO));

                    //texture, if there is one
                    System.Drawing.Bitmap image = new System.Drawing.Bitmap(TextureBitmap);
                    image.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY);
                    System.Drawing.Imaging.BitmapData bitmapdata;
                    System.Drawing.Rectangle          rect = new System.Drawing.Rectangle(0, 0, image.Width, image.Height);

                    bitmapdata = image.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly,
                                                System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                    GL.BindTexture(TextureTarget.Texture2D, GLTexture);
                    GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgb8, image.Width, image.Height,
                                  0, (PixelFormat)(int)All.BgrExt, PixelType.UnsignedByte, bitmapdata.Scan0);

                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear);           // Linear Filtering
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear);           // Linear Filtering

                    image.UnlockBits(bitmapdata);
                    image.Dispose();

                    GL.BindTexture(TextureTarget.Texture2D, GLTexture);
                }
            }
            catch
            { }
        }
        private void DoRotate(string path)
        {
            string[] files  = System.IO.Directory.GetFiles(path, "*.jpg");
            string   newDir = @"C:\Users\Public\Pictures\Sample Pictures\Modified";

            System.IO.Directory.CreateDirectory(newDir);

            //  Method signature: Parallel.ForEach(IEnumerable<TSource> source, Action<TSource> body)
            Parallel.ForEach(files, currentFile =>
            {
                // The more computational work you do here, the greater
                // the speedup compared to a sequential foreach loop.
                string filename = System.IO.Path.GetFileName(currentFile);
                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(currentFile);

                bitmap.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                bitmap.Save(System.IO.Path.Combine(newDir, filename));
                lblImagesProcessed.Dispatcher.BeginInvoke((Action) delegate() { lblImagesProcessed.Content += filename + Environment.NewLine; });
            } //close lambda expression
                             ); //close method invocation

            //to see how much time it has taken for computation
        }
        public override System.Drawing.Bitmap ToBitmap(bool saveAlpha = false)
        {
            Bind();

            var bmp = new System.Drawing.Bitmap(Width, Height);

            System.Drawing.Imaging.BitmapData data =
                bmp.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height),
                             System.Drawing.Imaging.ImageLockMode.WriteOnly,
                             saveAlpha ?
                             System.Drawing.Imaging.PixelFormat.Format32bppArgb
                :
                             System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            GL.ReadPixels(0, 0, Width, Height, saveAlpha ? PixelFormat.Bgra : PixelFormat.Bgr, PixelType.UnsignedByte, data.Scan0);
            bmp.UnlockBits(data);

            bmp.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY);

            Unbind();

            return(bmp);
        }
Esempio n. 55
0
        public static GameTexture Load(string filename)
        {
            Bitmap bmp = new Bitmap(filename);

            bmp.Log($"Loading Texture: " + filename, DebugChannel.Log, 8);
            bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);

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

            GameTexture ret = new GameTexture();

            GL.BindTexture(TextureTarget.Texture2D, ret.textureID);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
            bmp.UnlockBits(data);


            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);

            return(ret);
        }
Esempio n. 56
0
        private void CaptureScreen()
        {
            Bitmap bmp = new Bitmap(ClientSize.Width, ClientSize.Height,
                                    System.Drawing.Imaging.PixelFormat.Format32bppRgb);

            using (bmp)
            {
                BitmapData bData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
                                                ImageLockMode.ReadWrite, bmp.PixelFormat);

                GL.ReadBuffer(ReadBufferMode.Back);
                // read the data directly into the bitmap's buffer (bitmap is stored in BGRA)
                GL.ReadPixels(0, 0, ClientSize.Width, ClientSize.Height, OpenTK.Graphics.OpenGL.PixelFormat.Bgra,
                              PixelType.UnsignedByte, bData.Scan0);

                bmp.UnlockBits(bData);
                bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);

                DateTime time = DateTime.UtcNow;

                string dir  = $"{GameFolderDir}/screenshots";
                string file =
                    $"{dir}/{time.Year}-{time.Month}-{time.Day}_{time.TimeOfDay.Hours}.{time.TimeOfDay.Minutes}.{time.TimeOfDay.Seconds}.png";

                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                using (FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite,
                                                      FileShare.ReadWrite))
                {
                    bmp.Save(fs, ImageFormat.Png);
                }
            }
        }
Esempio n. 57
0
 private void Rotate90Menu_Click(object sender,
                                 System.EventArgs e)
 {
     bmpImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
     this.Invalidate();
 }
Esempio n. 58
0
        /// <summary>
        /// see http://stackoverflow.com/questions/11273669/how-to-paste-a-transparent-image-from-the-clipboard-in-a-c-sharp-winforms-app
        /// </summary>
        static sd.Image GetImageFromClipboard()
        {
            if (swf.Clipboard.GetDataObject() == null)
            {
                return(null);
            }

            if (swf.Clipboard.GetDataObject().GetDataPresent(swf.DataFormats.Dib))
            {
                var dib = ((System.IO.MemoryStream)swf.Clipboard.GetData(swf.DataFormats.Dib)).ToArray();

                var width  = BitConverter.ToInt32(dib, 4);
                var height = BitConverter.ToInt32(dib, 8);
                var bpp    = BitConverter.ToInt16(dib, 14);

                if (bpp == 32)
                {
                    var gch = GCHandle.Alloc(dib, GCHandleType.Pinned);

                    sd.Bitmap bmp = null;

                    try {
                        var ptr = new IntPtr((long)gch.AddrOfPinnedObject() + 40);

                        bmp = new sd.Bitmap(width, height, width * 4, sdi.PixelFormat.Format32bppArgb, ptr);

                        var result = new sd.Bitmap(bmp);

                        // Images are rotated and flipped for some reason.
                        // This rotates them back.
                        result.RotateFlip(sd.RotateFlipType.Rotate180FlipX);

                        return(result);
                    } finally {
                        gch.Free();

                        if (bmp != null)
                        {
                            bmp.Dispose();
                        }
                    }
                }
            }
            if (swf.Clipboard.ContainsFileDropList())
            {
                var list = swf.Clipboard.GetFileDropList();
                if (list != null && list.Count > 0)
                {
                    var      path = list[0];
                    sd.Image bmp  = null;
                    try
                    {
                        bmp = sd.Image.FromFile(path);
                        var result = new sd.Bitmap(bmp);
                        return(result);
                    }
                    catch
                    {
                    }
                    finally
                    {
                        if (bmp != null)
                        {
                            bmp.Dispose();
                        }
                    }
                }
            }

            return(swf.Clipboard.ContainsImage() ? swf.Clipboard.GetImage() : null);
        }
Esempio n. 59
0
        //-----------------------------------------------------------------------------------------------------------------

        public void GenerateAlphaMaps(ADT adtfile, int GenerationMode)
        {
            if (GenerationMode == 0 || GenerationMode == 1) //MODE 0 & 1 (256 RGB ALPHAS, ONE PER CHUNK)
            {
                //----------------------------------------------------------------------------------------------------------
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////
                ///ALPHA MAPS TEST
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //----------------------------------------------------------------------------------------------------------
                var valuesR = new MCAL().layer;
                var valuesG = new MCAL().layer;
                var valuesB = new MCAL().layer;
                for (uint c = 0; c < adtfile.chunks.Count(); c++)
                {
                    if (adtfile.texChunks[c].alphaLayer != null)
                    {
                        var bmp = new Bitmap(64, 64);
                        //Assign the channels...
                        switch (adtfile.texChunks[c].layers.Count())
                        {
                        case 2:
                            valuesR = adtfile.texChunks[c].alphaLayer[1].layer;
                            break;

                        case 3:
                            valuesR = adtfile.texChunks[c].alphaLayer[1].layer;
                            valuesG = adtfile.texChunks[c].alphaLayer[2].layer;
                            break;

                        case 4:
                            valuesR = adtfile.texChunks[c].alphaLayer[1].layer;
                            valuesG = adtfile.texChunks[c].alphaLayer[2].layer;
                            valuesB = adtfile.texChunks[c].alphaLayer[3].layer;
                            break;

                        default:
                            //Don't do anything
                            break;
                        }
                        if (GenerationMode == 0)
                        {
                            // 64x64 ALPHAS:
                            for (int x = 0; x < 64; x++)
                            {
                                for (int y = 0; y < 64; y++)
                                {
                                    Color color;
                                    switch (adtfile.texChunks[c].layers.Count())
                                    {
                                    case 2:
                                        color = Color.FromArgb(255, valuesR[x * 64 + y], 0, 0);
                                        break;

                                    case 3:
                                        color = Color.FromArgb(255, valuesR[x * 64 + y], valuesG[x * 64 + y], 0);
                                        break;

                                    case 4:
                                        color = Color.FromArgb(255, valuesR[x * 64 + y], valuesG[x * 64 + y], valuesB[x * 64 + y]);
                                        break;

                                    default:
                                        color = Color.FromArgb(255, 0, 0, 0);
                                        break;
                                    }
                                    bmp.SetPixel(x, y, color);
                                }
                            }
                        }
                        if (GenerationMode == 1)
                        {
                            // 63x63 ALPHAS: (Last column/row = previous one)
                            for (int x = 0; x < 63; x++)
                            {
                                for (int y = 0; y < 63; y++)
                                {
                                    Color color;
                                    switch (adtfile.texChunks[c].layers.Count())
                                    {
                                    case 2:
                                        color = Color.FromArgb(255, valuesR[x * 64 + y], 0, 0);
                                        break;

                                    case 3:
                                        color = Color.FromArgb(255, valuesR[x * 64 + y], valuesG[x * 64 + y], 0);
                                        break;

                                    case 4:
                                        color = Color.FromArgb(255, valuesR[x * 64 + y], valuesG[x * 64 + y], valuesB[x * 64 + y]);
                                        break;

                                    default:
                                        color = Color.FromArgb(255, 0, 0, 0);
                                        break;
                                    }
                                    bmp.SetPixel(x, y, color);
                                    if (y == 62)
                                    {
                                        bmp.SetPixel(x, y + 1, color);
                                    }
                                    if (x == 62)
                                    {
                                        bmp.SetPixel(x + 1, y, color);
                                    }
                                    if (x == 62 && y == 62)
                                    {
                                        bmp.SetPixel(x + 1, y + 1, color);
                                    }
                                }
                            }
                        }
                        //----------------------------------------------------------------------------------------------------------
                        //Fix bmp orientation:
                        //----------------------------------------------------------------------------------------------------------
                        bmp.RotateFlip(RotateFlipType.Rotate270FlipY);
                        //----------------------------------------------------------------------------------------------------------

                        //----------------------------------------------------------------------------------------------------------
                        //Store the generated map in the array
                        //----------------------------------------------------------------------------------------------------------
                        AlphaLayers.Add(bmp);
                        //----------------------------------------------------------------------------------------------------------
                    }
                    else //Create and add an empty BMP if Null
                    {
                        var bmp = new Bitmap(64, 64);
                        AlphaLayers.Add(bmp);
                    }
                }
                //----------------------------------------------------------------------------------------------------------
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////
                ///ALPHA MAPS TEST END
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //----------------------------------------------------------------------------------------------------------
            }
            if (GenerationMode == 2 || GenerationMode == 3) //MODE 2 & 3 (A BLACK&WHITE ALPHA FOR EACH LAYER (ROUGHLY ~768 ALPHAS))
            {
                //----------------------------------------------------------------------------------------------------------
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////
                ///ALPHA MAPS TEST
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //----------------------------------------------------------------------------------------------------------
                for (uint c = 0; c < adtfile.chunks.Count(); c++)
                {
                    var chunk = adtfile.chunks[c];
                    for (int li = 0; li < adtfile.texChunks[c].layers.Count(); li++)
                    {
                        if (adtfile.texChunks[c].alphaLayer != null)
                        {
                            var values = adtfile.texChunks[c].alphaLayer[li].layer;
                            var bmp    = new System.Drawing.Bitmap(64, 64);
                            {
                                if (GenerationMode == 2)
                                {
                                    // 64x64 ALPHAS:
                                    for (int x = 0; x < 64; x++)
                                    {
                                        for (int y = 0; y < 64; y++)
                                        {
                                            Color color;
                                            if (Managers.ConfigurationManager.ADTAlphaUseA)
                                            {
                                                color = System.Drawing.Color.FromArgb(values[x * 64 + y], values[x * 64 + y], values[x * 64 + y], values[x * 64 + y]);
                                            }
                                            else
                                            {
                                                color = System.Drawing.Color.FromArgb(255, values[x * 64 + y], values[x * 64 + y], values[x * 64 + y]);
                                            }
                                            bmp.SetPixel(x, y, color);
                                        }
                                    }
                                }
                                if (GenerationMode == 3)
                                {
                                    // 63x63 ALPHAS: (Last column/row = previous one)
                                    for (int x = 0; x < 63; x++)
                                    {
                                        for (int y = 0; y < 63; y++)
                                        {
                                            Color color;
                                            if (Managers.ConfigurationManager.ADTAlphaUseA)
                                            {
                                                color = System.Drawing.Color.FromArgb(values[x * 64 + y], values[x * 64 + y], values[x * 64 + y], values[x * 64 + y]);
                                            }
                                            else
                                            {
                                                color = System.Drawing.Color.FromArgb(255, values[x * 64 + y], values[x * 64 + y], values[x * 64 + y]);
                                            }
                                            bmp.SetPixel(x, y, color);
                                            if (y == 62)
                                            {
                                                bmp.SetPixel(x, y + 1, color);
                                            }
                                            if (x == 62)
                                            {
                                                bmp.SetPixel(x + 1, y, color);
                                            }
                                            if (x == 62 && y == 62)
                                            {
                                                bmp.SetPixel(x + 1, y + 1, color);
                                            }
                                        }
                                    }
                                }
                            }
                            //----------------------------------------------------------------------------------------------------------
                            //Store the layer textures
                            //----------------------------------------------------------------------------------------------------------
                            var AlphaLayerName = adtfile.textures.filenames[adtfile.texChunks[c].layers[li].textureId].ToLower();
                            AlphaLayersNames.Add(c + ";" + li + ";" + Path.GetFileNameWithoutExtension(AlphaLayerName));
                            //----------------------------------------------------------------------------------------------------------

                            //----------------------------------------------------------------------------------------------------------
                            //Fix bmp orientation:
                            //----------------------------------------------------------------------------------------------------------
                            bmp.RotateFlip(RotateFlipType.Rotate270FlipY);
                            //----------------------------------------------------------------------------------------------------------

                            //----------------------------------------------------------------------------------------------------------
                            //Store the generated map in the array
                            //----------------------------------------------------------------------------------------------------------
                            AlphaLayers.Add(bmp);
                            //----------------------------------------------------------------------------------------------------------
                        }
                    }
                }
                //----------------------------------------------------------------------------------------------------------
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////
                ///ALPHA MAPS TEST END
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //----------------------------------------------------------------------------------------------------------
            }

            #region Splatmaps (1024x1024)
            if (GenerationMode == 4)
            {
                //Adapted from Selzier's code [https://github.com/Selzier/wow.export.unity/blob/master/src/js/3D/exporters/ADTExporter.js]

                //----------------------------------------------------------------------------------------------------------
                //Generate the splatmap json
                //----------------------------------------------------------------------------------------------------------
                #region Splatmap JSON
                string materialJSON = "{\"chunkData\":{"; // New JSON file to save material data
                for (uint c = 0; c < adtfile.chunks.Count(); c++)
                {
                    materialJSON += "\"" + c + "\":[";
                    for (int li = 0; li < adtfile.texChunks[c].layers.Count(); li++)
                    {
                        string AlphaLayerName = adtfile.textures.filenames[adtfile.texChunks[c].layers[li].textureId].ToLower();
                        if (Managers.ConfigurationManager.ADTPreserveTextureStruct)
                        {
                            AlphaLayerName = AlphaLayerName.Replace("\\", "\\\\").Replace(".blp", "");  //Remove extension and modify the path to use "\\" instead of "\"
                        }
                        else
                        {
                            AlphaLayerName = Path.GetFileNameWithoutExtension(AlphaLayerName); // Get only the filename
                        }

                        //Layer scale
                        float LayerScale = 4;
                        if (adtfile.texParams != null && adtfile.texParams.Count() >= adtfile.texChunks[c].layers[li].textureId)
                        {
                            LayerScale = (float)Math.Pow(2, (adtfile.texParams[adtfile.texChunks[c].layers[li].textureId].flags & 0xF0) >> 4);
                        }

                        materialJSON += "{\"id\":\"" + AlphaLayerName + "\",\"scale\":\"" + LayerScale + "\"},";
                    }
                    materialJSON  = materialJSON.Substring(0, materialJSON.Length - 1); // Remove tailing comma
                    materialJSON += "],";                                               // Close the subchunk array
                }
                materialJSON = materialJSON.Substring(0, materialJSON.Length - 1);      // Remove tailing comma
                string fullJSON = materialJSON + "},\"splatmapData\":{";                // Create JSON data to include splatmap data
                materialJSON += "}}";                                                   // Close the JSON data

                JObject matJSON = JObject.Parse(materialJSON);

                if (adtfile.textures.filenames.Length == 0)
                {
                    fullJSON += "\"id0\":\"null\",";
                }
                else
                {
                    for (int q = 0; q < adtfile.textures.filenames.Length; q++)
                    {
                        string textureFile = adtfile.textures.filenames[q].ToLower();

                        if (Managers.ConfigurationManager.ADTPreserveTextureStruct)
                        {
                            textureFile = textureFile.Replace("\\", "\\\\").Replace(".blp", ""); //Remove extension and modify the path to use "\\" instead of "\"
                        }
                        else
                        {
                            textureFile = Path.GetFileNameWithoutExtension(textureFile);
                        }

                        fullJSON += "\"id" + q + "\":\"" + textureFile + "\",";
                    }
                }

                fullJSON  = fullJSON.Substring(0, fullJSON.Length - 1); // remove tailing comma
                fullJSON += "}}";                                       // Close the JSON data

                SplatmapJSON = fullJSON;

                #endregion
                //----------------------------------------------------------------------------------------------------------

                //----------------------------------------------------------------------------------------------------------
                //Generate the actual splatmaps
                //----------------------------------------------------------------------------------------------------------
                #region Splatmap Bitmap

                string[] materialIDs = adtfile.textures.filenames;
                for (int i = 0; i < materialIDs.Length; i++)
                {
                    if (Managers.ConfigurationManager.ADTPreserveTextureStruct)
                    {
                        materialIDs[i] = materialIDs[i].ToLower().Replace(".blp", ""); //Remove extension for the files
                    }
                    else
                    {
                        materialIDs[i] = Path.GetFileNameWithoutExtension(materialIDs[i].ToLower());
                    }
                }
                int imageCount = IntCeil(materialIDs.Length, 4);

                //----------------------------------------------------------------------------------------------------------
                //Structure for this abomination:
                //----------------------------------------------------------------------------------------------------------
                //>A int array for every map we need that contains:
                //>A int array for each channel (4 in total A R G B) that contains:
                //>A 2D array for each pixel (1024x1024)
                int[][][,] pixelData = new int[imageCount][][, ];
                for (int p = 0; p < pixelData.Length; p++)
                {
                    pixelData[p] = new int[4][, ];
                    for (int i = 0; i < 4; i++)
                    {
                        pixelData[p][i] = new int[1024, 1024];
                    }
                }
                //----------------------------------------------------------------------------------------------------------

                // Now before we draw each sub-chunk to PNG, we need to check it's texture list in json.
                // Based on what order the textures are for that sub-chunk, we may need to draw RGBA in a different order than 0,1,2,3

                //Chunk offset
                int xOff = 0;
                int yOff = 0;

                //Loop for all the 256 texChunks
                for (int chunkIndex = 0; chunkIndex < 256; chunkIndex++)
                {
                    TexMCNK texChunk      = adtfile.texChunks[chunkIndex];
                    MCAL[]  alphaLayers   = texChunk.alphaLayer;
                    MCLY[]  textureLayers = texChunk.layers;

                    // If there is no texture data just skip it
                    if (textureLayers.Length > 0)
                    {
                        // X,Y Loop through the texChunk (data is stored as 64x64)
                        for (int x = 0; x < 64; x++)
                        {
                            for (int y = 0; y < 64; y++)
                            {
                                int alphaIndex = x * 64 + y;

                                int numberTextureLayers = matJSON["chunkData"][chunkIndex.ToString()].Count();

                                for (int k = 0; k < numberTextureLayers; k++)
                                {
                                    // k = 1, random materialID. This could be any RGBA, RGBA color!
                                    int    currentIndex = 0;
                                    string currentID    = (string)matJSON["chunkData"][chunkIndex.ToString()][k]["id"]; //Probably not a good idea to use a string though (check back on >7xx support)

                                    for (int l = 0; l < materialIDs.Length; l++)
                                    {
                                        if (materialIDs[l] == currentID)
                                        {
                                            currentIndex = l;
                                        }
                                    }
                                    int texIndex = currentIndex;

                                    // Calculate image index, 1 PNG image for each 4 textures. index 0 includes base texture on channel 0
                                    int imageIndex = IntFloor(texIndex, 4);

                                    // 0-3 RGBA. If imageIndex=0 this should not be 0 because that is basetexture
                                    int channelIndex = texIndex % 4;

                                    // 'vec3 blendTex' from the adt.fragment shader
                                    var blendTexs = new int[3];
                                    if (alphaLayers != null) //Those layers can be null
                                    {
                                        switch (alphaLayers.Length)
                                        {
                                        case 2:
                                            blendTexs[0] = alphaLayers[1].layer[alphaIndex];
                                            break;

                                        case 3:
                                            blendTexs[0] = alphaLayers[1].layer[alphaIndex];
                                            blendTexs[1] = alphaLayers[2].layer[alphaIndex];
                                            break;

                                        case 4:
                                            blendTexs[0] = alphaLayers[1].layer[alphaIndex];
                                            blendTexs[1] = alphaLayers[2].layer[alphaIndex];
                                            blendTexs[2] = alphaLayers[3].layer[alphaIndex];
                                            break;

                                        default:
                                            break;
                                        }
                                    }

                                    // 'vec4 layer_weights' from the adt.fragment shader
                                    var sumBlendTex = 0;
                                    for (int b = 0; b < blendTexs.Length; b++)
                                    {
                                        sumBlendTex += blendTexs[b];
                                    }
                                    sumBlendTex = Clamp(sumBlendTex, 0, 255);
                                    int[] layerWeights = new int[4];
                                    layerWeights[0] = 255 - sumBlendTex;
                                    layerWeights[1] = blendTexs[0];
                                    layerWeights[2] = blendTexs[1];
                                    layerWeights[3] = blendTexs[2];

                                    // Write the actual pixel data
                                    if (k == 0)
                                    {
                                        pixelData[imageIndex][channelIndex][x + xOff, y + yOff] = layerWeights[0];
                                    }
                                    else
                                    {
                                        pixelData[imageIndex][channelIndex][x + xOff, y + yOff] = layerWeights[k];
                                    }
                                }
                            }
                        }
                    }
                    //----------------------------------------------------------------------------------------------------------
                    //Change the offset
                    //----------------------------------------------------------------------------------------------------------
                    if (yOff + 64 > 960)
                    {
                        yOff = 0;
                        if (xOff + 64 <= 960)
                        {
                            xOff += 64;
                        }
                    }
                    else
                    {
                        yOff += 64;
                    }
                    //----------------------------------------------------------------------------------------------------------
                }

                //----------------------------------------------------------------------------------------------------------
                //Generate the bitmaps
                //----------------------------------------------------------------------------------------------------------
                for (int t = 0; t < imageCount; t++)
                {
                    Bitmap bmp = new Bitmap(1024, 1024);

                    for (int x = 0; x < 1024; x++)
                    {
                        for (int y = 0; y < 1024; y++)
                        {
                            Color currentColor = Color.FromArgb(
                                ZeroClamp(pixelData[t][3][x, y]), //A
                                ZeroClamp(pixelData[t][0][x, y]), //R
                                ZeroClamp(pixelData[t][1][x, y]), //G
                                ZeroClamp(pixelData[t][2][x, y])  //B
                                );

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

                    //----------------------------------------------------------------------------------------------------------
                    //Fix bmp orientation:
                    //----------------------------------------------------------------------------------------------------------
                    bmp.RotateFlip(RotateFlipType.Rotate270FlipY);
                    //----------------------------------------------------------------------------------------------------------

                    //----------------------------------------------------------------------------------------------------------
                    //Store the generated map in the list
                    //----------------------------------------------------------------------------------------------------------
                    AlphaLayers.Add(bmp);
                    //----------------------------------------------------------------------------------------------------------
                }
                //----------------------------------------------------------------------------------------------------------

                #endregion
                //----------------------------------------------------------------------------------------------------------
            }
            #endregion
        }
        public int ProcessBuffer(double sampleTime, IntPtr buffer, int bufferLength)
        {
            using (Bitmap bitmap = new Bitmap(_width, _height, _format))
            {
                BitmapData data = bitmap.LockBits(_bounds, ImageLockMode.ReadWrite, _format);

                NativeMethods.CopyMemory(data.Scan0, buffer, (uint) bufferLength);

                bitmap.UnlockBits(data);

                if (_flipImages) bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);

                UpdateImage(sampleTime, bitmap);

                if (_flipImages) bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);

                data = bitmap.LockBits(_bounds, ImageLockMode.ReadOnly, _format);

                NativeMethods.CopyMemory(buffer, data.Scan0, (uint) bufferLength);

                bitmap.UnlockBits(data);
            }

            return 0;
        }