Exemplo n.º 1
0
        /// <summary>
        /// 图片缓存
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        public string getImageCache(string img, Card card)
        {
            if (cfg.width <= 0 && cfg.height <= 0)
            {
                return(img);
            }
            string md5 = MyUtils.GetMD5HashFromFile(img);

            if (MyUtils.Md5isEmpty(md5) || cfg.imagecache == null)
            {
                //md5为空
                return(img);
            }
            string file = MyPath.Combine(cfg.imagecache, md5);

            if (!File.Exists(file))
            {
                //生成缓存
                Bitmap bmp = MyBitmap.readImage(file);
                //缩放
                if (card != null && card.IsType(CardType.TYPE_PENDULUM))
                {
                    bmp = MyBitmap.Zoom(bmp, cfg.pwidth, cfg.pheight);
                }
                else
                {
                    bmp = MyBitmap.Zoom(bmp, cfg.width, cfg.height);
                }
                //保存文件
                MyBitmap.SaveAsJPEG(bmp, file, 100);
            }
            return(img);
        }
Exemplo n.º 2
0
 private void btnSave_Click(object sender, EventArgs e)
 {
     if (dlgSaveFile.ShowDialog(this) == DialogResult.OK)
     {
         MyBitmap.Save(dlgSaveFile.FileName, ImageFormat.Bmp);
     }
 }
Exemplo n.º 3
0
        private void Redraw()
        {
            if (this.disableRedrawing)
            {
                return;
            }

            var selectedSpec    = this.config.GetSpecById((int)this.tilesetComboBox.SelectedItem);
            var selectedPalette = this.palettes.BackgroundPalettes.First(p => p.Id == (int)this.paletteComboBox.SelectedItem);

            var bgSpec      = selectedSpec.GetBgSpec();
            var blocking    = MyBitmap.FromFile(bgSpec.BlockingFile).Scale(2);
            var nonBlocking = MyBitmap.FromFile(bgSpec.NonBlockingFile).Scale(2);
            var threats     = MyBitmap.FromFile(bgSpec.ThreatFile).Scale(2);

            var packed = Packer.Pack(new Size[] { blocking.Size, nonBlocking.Size, threats.Size }, maxWidth);

            var width  = packed.Max(tpl => tpl.Item1.X + tpl.Item2.Width);
            var height = packed.Max(tpl => tpl.Item1.Y + tpl.Item2.Height);

            var blockingPosition = packed.First(tpl => tpl.Item2 == blocking.Size);

            packed.Remove(blockingPosition);
            var nonBlockingPosition = packed.First(tpl => tpl.Item2 == nonBlocking.Size);

            packed.Remove(nonBlockingPosition);
            var threatsPosition = packed.First(); // only one left

            var palette = this.palettes.BackgroundPalettes[this.SelectedPalette];
            var bgColor = palette.Palettes.First().ActualColors.First();

            var bigBitmap = new MyBitmap(2 * width + 30, 2 * height + 30, bgColor);

            for (var i = 0; i <= 3; i++)
            {
                var bitmap = new MyBitmap(width, height, bgColor);

                var blockingClone = blocking.Clone();
                blockingClone.UpdateColors(blockingClone.UniqueColors(), palette.Palettes[i].ActualColors);
                var nonBlockingClone = nonBlocking.Clone();
                nonBlockingClone.UpdateColors(nonBlockingClone.UniqueColors(), palette.Palettes[i].ActualColors);
                var threatsClone = threats.Clone();
                threatsClone.UpdateColors(threatsClone.UniqueColors(), palette.Palettes[i].ActualColors);

                bitmap.DrawImage(blockingClone, blockingPosition.Item1.X, blockingPosition.Item1.Y);
                bitmap.DrawImage(nonBlockingClone, nonBlockingPosition.Item1.X, nonBlockingPosition.Item1.Y);
                bitmap.DrawImage(threatsClone, threatsPosition.Item1.X, threatsPosition.Item1.Y);

                bigBitmap.DrawImage(bitmap, 10 + (i % 2) * (bitmap.Width + 10), 10 + (i / 2) * (bitmap.Height + 10));
            }

            this.pictureBox.Image = bigBitmap.ToBitmap();

            var newWidth  = Math.Max(bigBitmap.Width, minWidth);
            var newHeight = bigBitmap.Height + heightOffset;

            this.Width  = newWidth + widthOffset;
            this.Height = Math.Min(newHeight, maxHeight);
            this.Refresh();
        }
Exemplo n.º 4
0
        public Bitmap GetBitmap()
        {
            uEye.Defines.Status statusRet = 0;

            // Get last image memory
            Int32 s32LastMemId;
            Int32 s32Width;
            Int32 s32Height;

            statusRet = m_Camera.Memory.GetLast(out s32LastMemId);
            statusRet = m_Camera.Memory.Lock(s32LastMemId);
            statusRet = m_Camera.Memory.GetSize(s32LastMemId, out s32Width, out s32Height);

            Bitmap MyBitmap;

            statusRet = m_Camera.Memory.ToBitmap(s32LastMemId, out MyBitmap);

            // clone bitmap
            Rectangle cloneRect = new Rectangle(0, 0, s32Width, s32Height);

            System.Drawing.Imaging.PixelFormat format = System.Drawing.Imaging.PixelFormat.Format32bppArgb;
            Bitmap cloneBitmap = MyBitmap.Clone(cloneRect, format);

            // unlock image buffer
            statusRet = m_Camera.Memory.Unlock(s32LastMemId);
            MyBitmap.Dispose();
            return(cloneBitmap);
        }
Exemplo n.º 5
0
        public void PrepareSprite(MyBitmap source)
        {
            if (this.ActualSprite != null)
            {
                throw new Exception("Not expected");
            }

            var sprite = source.GetPart(this.X, this.Y, Constants.SpriteWidth, Constants.SpriteHeight);

            sprites.Add(ImageFlags.None, sprite);
        }
        //转换图片
        public void ToImg(string img, string saveimg1, string saveimg2)
        {
            if (!File.Exists(img))
            {
                return;
            }
            Bitmap bmp = new Bitmap(img);

            MyBitmap.SaveAsJPEG(MyBitmap.Zoom(bmp, imgSet.W, imgSet.H),
                                saveimg1, imgSet.quilty);
            MyBitmap.SaveAsJPEG(MyBitmap.Zoom(bmp, imgSet.w, imgSet.h),
                                saveimg2, imgSet.quilty);
        }
Exemplo n.º 7
0
        /// <summary>
        /// 图片缓存
        /// </summary>
        /// <param name="img"></param>
        /// <param name="card"></param>
        /// <returns></returns>
        public string GetImageCache(string img, Card card)
        {
            if (!this.cfg.reimage)
            {
                //不需要调整
                return(img);
            }
            bool isPendulum = card.IsType(CardType.TYPE_PENDULUM);

            if (isPendulum)
            {
                if (this.cfg.pwidth <= 0 && this.cfg.pheight <= 0)
                {
                    return(img);
                }
            }
            else
            {
                if (this.cfg.width <= 0 && this.cfg.height <= 0)
                {
                    return(img);
                }
            }
            string md5 = MyUtils.GetMD5HashFromFile(img);

            if (MyUtils.Md5isEmpty(md5) || this.cfg.imagecache == null)
            {
                //md5为空
                return(img);
            }
            string file = MyPath.Combine(this.cfg.imagecache, md5);

            if (!File.Exists(file))
            {
                //生成缓存
                Bitmap bmp = MyBitmap.ReadImage(img);
                //缩放
                if (isPendulum)
                {
                    bmp = MyBitmap.Zoom(bmp, this.cfg.pwidth, this.cfg.pheight);
                }
                else
                {
                    bmp = MyBitmap.Zoom(bmp, this.cfg.width, this.cfg.height);
                }
                //保存文件
                MyBitmap.SaveAsJPEG(bmp, file, 100);
            }
            return(file);
        }
Exemplo n.º 8
0
        private MyBitmap GenerateImage()
        {
            var result = new MyBitmap(Constants.BgWidth, Constants.BgHeight);
            var lines  = this.textBox.Lines.Where(l => !string.IsNullOrEmpty(l)).ToList();

            if (lines.Count != Constants.BgHeight / Constants.NesTileSize)
            {
                MessageBox.Show($"Invalid number of lines in the text box, should be {Constants.BgHeight / Constants.NesTileSize}");
                return(null);
            }

            var i = 0;

            foreach (var line in lines)
            {
                var split = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (split.Length != Constants.BgWidth / Constants.NesTileSize)
                {
                    MessageBox.Show($"Invalid number of ids in line {i}, should be {Constants.BgWidth / Constants.NesTileSize}");
                    return(null);
                }

                var ids = new List <int>();
                foreach (var s in split)
                {
                    int id;
                    if (!int.TryParse(s, out id))
                    {
                        MessageBox.Show($"Non-number in line {i}: {s}");
                        return(null);
                    }

                    ids.Add(id);
                }

                for (var j = 0; j < ids.Count; j++)
                {
                    var id   = ids[j];
                    var tile = this.tiles[id];
                    var x    = j * Constants.NesTileSize;
                    var y    = i * Constants.NesTileSize;
                    result.DrawImage(tile, x, y);
                }

                i++;
            }

            return(result);
        }
Exemplo n.º 9
0
        //转换图片
        //public void ToImg(string img, string saveimg1, string saveimg2)
        public void ToImg(string img, string saveimg1)
        {
            if (!File.Exists(img))
            {
                return;
            }

            Bitmap bmp = new Bitmap(img);

            MyBitmap.SaveAsJPEG(MyBitmap.Zoom(bmp, this.imgSet.W, this.imgSet.H),
                                saveimg1, this.imgSet.quilty);
            //MyBitmap.SaveAsJPEG(MyBitmap.Zoom(bmp, imgSet.w, imgSet.h),
            //					saveimg2, imgSet.quilty);
            bmp.Dispose();
        }
Exemplo n.º 10
0
        private void RefreshMyBitmapImage()
        {
            using (MemoryStream memory = new MemoryStream())
            {
                _MyBitmap = new BitmapImage();
                _EditableBitmap.Bitmap.Save(memory, ImageFormat.Bmp);
                memory.Position = 0;

                MyBitmap.BeginInit();
                MyBitmap.StreamSource = memory;
                MyBitmap.CacheOption  = BitmapCacheOption.OnLoad;
                MyBitmap.EndInit();

                OnPropertyChanged("MyBitmap");
            }
        }
Exemplo n.º 11
0
        private void LoadDirectory()
        {
            this.images = new Dictionary <string, Bitmap>();
            var directory = new DirectoryInfo(this.directoryTextBox.Text);

            int?width  = null;
            int?height = null;

            foreach (var file in directory.EnumerateFiles().OrderBy(f => f.Name))
            {
                int ignore;
                if (!int.TryParse(file.Name.Substring(0, file.Name.Length - file.Extension.Length), out ignore))
                {
                    continue;
                }

                var image = MyBitmap.FromFile(file.FullName);

                if (width == null)
                {
                    width = image.Width;
                }
                else if (width != image.Width)
                {
                    throw new Exception("Invalid width " + file.Name);
                }

                if (height == null)
                {
                    height = image.Height;
                }
                else if (height != image.Height)
                {
                    throw new Exception("Invalid height " + file.Name);
                }

                this.images.Add(file.Name, image.Scale((int)this.zoomPicker.Value).ToBitmap());
            }

            this.framesListBox.Items.Clear();
            foreach (var item in images.Keys)
            {
                this.framesListBox.Items.Add(item);
            }

            this.StartAnimation();
        }
Exemplo n.º 12
0
        //removed thumbnail
        #region 转换图片
        public void ConvertImages(string imgpath, string gamepath, bool isreplace)
        {
            string picspath = MyPath.Combine(gamepath, "pics");

            //string thubpath = MyPath.Combine(picspath, "thumbnail");
            string[] files = Directory.GetFiles(imgpath);
            int      i     = 0;
            int      count = files.Length;

            foreach (string f in files)
            {
                if (this.isCancel)
                {
                    break;
                }

                i++;
                this.worker.ReportProgress(i / count, string.Format("{0}/{1}", i, count));
                string ex    = Path.GetExtension(f).ToLower();
                string name  = Path.GetFileNameWithoutExtension(f);
                string jpg_b = MyPath.Combine(picspath, name + ".jpg");
                //string jpg_s = MyPath.Combine(thubpath, name + ".jpg");
                if (ex == ".jpg" || ex == ".png" || ex == ".bmp")
                {
                    if (File.Exists(f))
                    {
                        Bitmap bmp = new Bitmap(f);
                        //大图,如果替换,或者不存在
                        if (isreplace || !File.Exists(jpg_b))
                        {
                            MyBitmap.SaveAsJPEG(MyBitmap.Zoom(bmp, this.imgSet.W, this.imgSet.H),
                                                jpg_b, this.imgSet.quilty);
                        }
                        //小图,如果替换,或者不存在
                        //if (isreplace || !File.Exists(jpg_s))
                        //{
                        //	MyBitmap.SaveAsJPEG(MyBitmap.Zoom(bmp, imgSet.w, imgSet.h),
                        //						jpg_s, imgSet.quilty);

                        //}
                    }
                }
            }
        }
Exemplo n.º 13
0
        public void PreparePalettes(Palettes palettes, PaletteMapping paletteMapping, int attsUpdate = 0)
        {
            var sprite = this.sprites[ImageFlags.None];
            var spriteWithPalettesApplied = new MyBitmap(sprite.Width, sprite.Height);
            var palette = palettes.SpritesPalette[paletteMapping.ToPalette + attsUpdate];

            for (var x = 0; x < sprite.Width; x++)
            {
                for (var y = 0; y < sprite.Height; y++)
                {
                    var color         = sprite.GetPixel(x, y);
                    var mappedColorId = paletteMapping.ColorMappings.First(c => c.Color == color).To;
                    var mappedColor   = palette.ActualColors[mappedColorId];
                    spriteWithPalettesApplied.SetPixel(mappedColor, x, y);
                }
            }

            sprites.Add(ImageFlags.Palettes, spriteWithPalettesApplied);
        }
Exemplo n.º 14
0
        public static void ProcessFont(string fontBmp, IList <MyBitmap> tiles, IList <int> atts = null)
        {
            var emptyFound       = false;
            var secondEmptyFound = false;
            var fontBitmap       = MyBitmap.FromFile(fontBmp);

            for (var y = 0; y < fontBitmap.Height; y += Constants.SpriteHeight)
            {
                for (var x = 0; x < fontBitmap.Width; x += Constants.SpriteWidth)
                {
                    var part = fontBitmap.GetPart(x, y, Constants.SpriteWidth, Constants.SpriteHeight);
                    if (part.IsSolidColor(part.GetPixel(0, 0)))
                    {
                        if (!emptyFound)
                        {
                            emptyFound = true;
                            tiles.Add(part);
                            if (atts != null)
                            {
                                atts.Add(1);
                            }
                        }
                        else
                        {
                            secondEmptyFound = true;
                        }
                    }
                    else
                    {
                        if (secondEmptyFound)
                        {
                            throw new Exception("Empty font tile in the middle of other tiles");
                        }

                        tiles.Add(part);
                        if (atts != null)
                        {
                            atts.Add(1);
                        }
                    }
                }
            }
        }
Exemplo n.º 15
0
        private Bitmap DrawBullet(Bitmap image, Animation animation, bool flip, int zoom)
        {
            var width  = image.Width;
            var height = image.Height;

            var xOff = Constants.SpriteWidth * zoom;
            var yOff = Constants.SpriteHeight * zoom;

            var newImage = new MyBitmap(width + xOff * 2, height + yOff * 2, this.pictureBox.BackColor);

            newImage.DrawImage(MyBitmap.FromBitmap(image), xOff, yOff);

            if (animation.Offsets.GunXOff >= 0)
            {
                var bullet       = this.bulletConfig.Bullets.First(b => b.BulletId == animation.BulletId);
                var flipFlags    = bullet.GetFlipFlags(flip);
                var bulletBitmap = bullet.Sprite.GetSprite(
                    this.applyPaletteCheckbox.Checked,
                    flipFlags.HasFlag(ImageFlags.VFlip),
                    flipFlags.HasFlag(ImageFlags.HFlip),
                    this.pictureBox.BackColor).Clone();

                var scaled = bulletBitmap.Scale(zoom);
                if (flip)
                {
                    newImage.DrawImage(
                        scaled,
                        xOff + animation.Offsets.GunXOffFlip * zoom,
                        yOff + animation.Offsets.GunYOffFlip * zoom);
                }
                else
                {
                    newImage.DrawImage(
                        scaled,
                        xOff + animation.Offsets.GunXOff * zoom,
                        yOff + animation.Offsets.GunYOff * zoom);
                }
            }


            return(newImage.ToBitmap());
        }
Exemplo n.º 16
0
 private void btnSave_Click(object sender, EventArgs e)
 {
     if (dlgSaveFile.ShowDialog(this) == DialogResult.OK)
     {
         MyBitmap.Save(dlgSaveFile.FileName, ImageFormat.Bmp);
         // byte[] imgBuf = new byte[2*WIDTH*HEIGHT];
         //File.WriteAllBytes(dlgSaveFile.FileName+".bin", imgBuf);
         try
         {
             using (var fs = new FileStream(dlgSaveFile.FileName + ".bin", FileMode.Create, FileAccess.Write))
             {
                 fs.Write(imgBuf, 0, totalImageSize);
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine("Exception caught in process: {0}", ex);
         }
     }
 }
Exemplo n.º 17
0
        private MyBitmap CreateSingleBitmap(IEnumerable <MyBitmap> bitmaps)
        {
            var positions    = Packer.Pack(bitmaps.Select(b => b.Size), Constants.PickerWidth);
            var bitmapsCopy  = bitmaps.ToList();
            var backColor    = MyBitmap.NesGreyscale[0];
            var resultBitmap = new MyBitmap(1, 1, backColor);

            foreach (var tuple in positions)
            {
                var position = tuple.Item1;
                var size     = tuple.Item2;

                var bitmap = bitmapsCopy.First(b => b.Size == size);
                bitmapsCopy.Remove(bitmap);

                resultBitmap.DrawImage(bitmap, position.X, position.Y, true, backColor);
            }

            return(resultBitmap);
        }
Exemplo n.º 18
0
        private void rgb565swapped(ref byte[] imgBuf, int width, int height, int pixelsize, int totalImageSize)
        {
            byte[] rawData = new byte[totalImageSize];
            Buffer.BlockCopy(imgBuf, 0, rawData, 0, totalImageSize);  // then we can keep the result in imgBuf

            // Mirror the picture line by line
            long pixWidth = pixelsize * width;
            long i        = 0;
            long j        = 0;

            for (long h = 0; h < height; h++)
            {
                long offset = h * pixWidth;
                for (long w = 0; w < pixWidth; w++)
                {
                    i = offset + w;
                    j = offset + (pixWidth - 1) - w;
                    if (i < 0 || i >= totalImageSize || j < 0 || j >= totalImageSize)
                    {
                        Trace.WriteLine("h=" + h + " offset=" + offset + " pixw=" + pixWidth + " i=" + i + " j=" + j);
                    }
                    else
                    {
                        imgBuf[i] = rawData[j];
                    }
                }
            }
            Trace.WriteLine("ConvertImageFileFormat: mirroring done");

            // Convert the raw data to bitmap format
            Rectangle  rect  = new Rectangle(0, 0, width, height);
            BitmapData bData = MyBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, MyBitmap.PixelFormat);

            IntPtr ptr = bData.Scan0;

            System.Runtime.InteropServices.Marshal.Copy(imgBuf, 0, ptr, totalImageSize);
//            byte[] pt = System.Runtime.InteropServices.Marshal.st  PtrToStructure(ptr , typeof( bData.Scan0 ));
//            Buffer.BlockCopy(imgBuf,0, pt, 0, totalImageSize);

            MyBitmap.UnlockBits(bData);
        }
Exemplo n.º 19
0
        private void LoadButtonClick(object sender, System.EventArgs e)
        {
            this.story = Story.Read(this.storyTextBox.Text);
            this.stringsConfig = StringsConfig.Read(this.stringsTextBox.Text);
            var tiles = new List<MyBitmap>();
            TitleDialog.ProcessFont(this.fontTextBox.Text, tiles);

            var strings = new List<StringToRedner>();

            foreach (var strData in this.story.Strings)
            {
                if (strData.X < 1 || strData.Y < 1)
                {
                    throw new System.Exception("Invalid string position");
                }

                var str = this.stringsConfig.Strings.First(s => s.Id == strData.StringId).Value;
                if (str.Length > 30)
                {
                    throw new System.Exception("Invalid string length");
                }

                strings.Add(new StringToRedner(strData.X, strData.Y, str.ToLower()));
            }

            strings.Add(new StringToRedner(PressStartX, PressStartY, PressStart));

            var bmp = new MyBitmap(512, 448, System.Drawing.Color.Black); // 448 means NTSC
            foreach (var str in strings)
            {
                var x = str.X;
                foreach (var chr in str.Str.ToCharArray())
                {
                    var tile = tiles[TitleDialog.Chars.IndexOf(chr)].Scale(BitmapZoom);
                    bmp.DrawImage(tile, x * Constants.SpriteWidth * BitmapZoom, (str.Y - 1) * Constants.SpriteHeight * BitmapZoom); // - 1 because of NTSC
                    x++;
                }
            }

            this.pictureBox.Image = bmp.ToBitmap();
        }
Exemplo n.º 20
0
        private Bitmap CreateBitmap(int[][] input, int width, int height, bool addLines = false)
        {
            var bitmap = new MyBitmap(width, height);

            for (var x = 0; x < width; x++)
            {
                for (var y = 0; y < height; y++)
                {
                    var index = input[x][y];
                    if (index > 1)
                    {
                        index = index % (Colors.Length - 2) + 2;
                    }

                    var color = Colors[index];
                    bitmap.SetPixel(color, x, y);
                }
            }

            var scaledBitmap = bitmap.Scale(this.scale);

            if (addLines)
            {
                for (var screen = 0; screen < width * this.scale; screen += Constants.ScreenWidthInTiles * this.scale)
                {
                    for (var y = 0; y < height * this.scale; y++)
                    {
                        scaledBitmap.SetPixel(Color.Black, screen, y);
                    }
                }

                for (var y = 0; y < height * this.scale; y++)
                {
                    scaledBitmap.SetPixel(Color.Black, width * this.scale - 1, y);
                }
            }

            return(scaledBitmap.ToBitmap());
        }
Exemplo n.º 21
0
        /// <summary>
        /// Special method for rendering the explosion.
        /// </summary>
        public Bitmap GetExplosionBitmap(
            Color backColor,
            bool applyPalettes,
            int zoom)
        {
            // Get flags for the request.
            var flags = GetFlags(applyPalettes, false, false, false);

            // Checked if a cached bitmap is available, return it if it is.
            var dictionary = this.cachedBitmaps[zoom - 1];

            if (dictionary.ContainsKey(flags))
            {
                return(dictionary[flags]);
            }

            // Create bitmap.
            var width  = Constants.ExplosionWidth;
            var height = Constants.ExplosionHeight;
            var image  = new MyBitmap(width, height, backColor);

            // Draw each sprite.
            foreach (var sprite in this.Sprites)
            {
                // Get the correct sprite image.
                var spriteImage = sprite.GetSprite(applyPalettes, sprite.VFlip, sprite.HFlip);

                // Draw the image.
                image.DrawImage(spriteImage, sprite.X, sprite.Y);
            }

            // Scale image.
            var result = image.Scale(zoom).ToBitmap();

            // Save result for later and return.
            dictionary.Add(flags, result);
            return(result);
        }
Exemplo n.º 22
0
        public void CutImages(string imgpath, bool isreplace)
        {
            int count = this.cardlist.Length;
            int i     = 0;

            foreach (Card c in this.cardlist)
            {
                if (this.isCancel)
                {
                    break;
                }

                i++;
                this.worker.ReportProgress((i / count), string.Format("{0}/{1}", i, count));
                string jpg     = MyPath.Combine(imgpath, c.id + ".jpg");
                string savejpg = MyPath.Combine(this.mseHelper.ImagePath, c.id + ".jpg");
                if (File.Exists(jpg) && (isreplace || !File.Exists(savejpg)))
                {
                    Bitmap bp = new Bitmap(jpg);
                    Bitmap bmp;
                    if (c.IsType(CardType.TYPE_XYZ))//超量
                    {
                        bmp = MyBitmap.Cut(bp, this.imgSet.xyzArea);
                    }
                    else if (c.IsType(CardType.TYPE_PENDULUM))//P怪兽
                    {
                        bmp = MyBitmap.Cut(bp, this.imgSet.pendulumArea);
                    }
                    else//一般
                    {
                        bmp = MyBitmap.Cut(bp, this.imgSet.normalArea);
                    }
                    bp.Dispose();
                    MyBitmap.SaveAsJPEG(bmp, savejpg, this.imgSet.quilty);
                    //bmp.Save(savejpg, ImageFormat.Png);
                }
            }
        }
Exemplo n.º 23
0
        private void GetLogoData(StringBuilder builder, MyBitmap logo, int[,] logoIds)
        {
            builder.AppendLine(
                @";****************************************************************
; Logo                                                          ;
;****************************************************************
");

            var logoX         = ((256 - logo.Width) / 2) / Constants.SpriteHeight;
            var logoY         = 5;
            var initLogoAddrs = 8192 + logoX + logoY * 32;

            builder.AppendLine($"LOGO_X = {ToHex(logoX)}");
            builder.AppendLine($"LOGO_Y = {ToHex(logoY)}");
            builder.AppendLine($"INITIAL_LOGO_ADDR_L = {ToHex(initLogoAddrs % 256)}");
            builder.AppendLine($"INITIAL_LOGO_ADDR_H = {ToHex(initLogoAddrs / 256)}");
            builder.AppendLine($"LOGO_ROW_LENGTH = {ToHex(logoIds.GetLength(0))}");
            builder.AppendLine($"LOGO_ROWS = {ToHex(logoIds.GetLength(1))}");
            builder.AppendLine("Logo:");
            for (var y = 0; y < logoIds.GetLength(1); y++)
            {
                builder.Append("  .byte ");
                for (var x = 0; x < logoIds.GetLength(0); x++)
                {
                    if (x > 0)
                    {
                        builder.Append(", ");
                    }

                    builder.Append(ToHex(logoIds[x, y]));
                }

                builder.AppendLine();
            }

            builder.AppendLine();
        }
Exemplo n.º 24
0
        private string GetCode(MyBitmap logo, int[,] logoIds, int cursorId)
        {
            var builder = new StringBuilder();

            builder.AppendLine(
                @"LogoAndTextDataStart:

;****************************************************************
; LogoAndTextData                                               ;
; Holds info for rendering the logo and text (auto-generated)   ;
;****************************************************************
");
            GetLogoData(builder, logo, logoIds);
            GetStringsData(builder);

            builder.AppendLine();
            builder.AppendLine($"CURSOR_TILE = {ToHex(cursorId)}");
            builder.AppendLine();

            builder.AppendLine(@"
LogoAndTextDataEnd:");

            return(builder.ToString());
        }
Exemplo n.º 25
0
        /// <summary>
        /// Method for rendering a grid bitmap.
        /// </summary>
        public Bitmap GetGridBitmap(
            Color backColor,
            bool applyPalettes,
            bool showBoxes,
            bool vFlip,
            bool hFlip,
            int zoom,
            Offsets offsets,
            bool transparent   = false,
            bool transparentBg = false)
        {
            // Get flags for the request.
            var flags = GetFlags(applyPalettes, showBoxes, vFlip, hFlip, transparent, transparentBg);

            // Checked if a cached bitmap is available, return it if it is.
            var dictionary = this.cachedBitmaps[zoom - 1];

            if (dictionary.ContainsKey(flags))
            {
                return(dictionary[flags]);
            }

            // Create bitmap.
            var width  = this.Width * Constants.SpriteWidth;
            var height = this.Height * Constants.SpriteHeight;
            var image  = new MyBitmap(width, height, backColor);

            // Figure out flip.
            var isFlip = (hFlip || vFlip);

            // Draw each sprite.
            for (var spriteX = 0; spriteX < this.Width; spriteX++)
            {
                for (var spriteY = 0; spriteY < this.Height; spriteY++)
                {
                    // Sprites are aligned like:
                    //   1 2 3
                    //   4 5 6
                    var spriteId = spriteX + (spriteY * this.Width);
                    var sprite   = this.Sprites[spriteId];

                    // Figure out flips.
                    var shouldBeVFlip = sprite.VFlip ^ vFlip;
                    var shouldBeHFlip = sprite.HFlip ^ hFlip;

                    // Get the correct sprite image.
                    var spriteImage = sprite.GetSprite(applyPalettes, shouldBeVFlip, shouldBeHFlip, backColor);

                    // Calculate sprite's position.
                    var x = spriteX * Constants.SpriteWidth;
                    var y = spriteY * Constants.SpriteHeight;

                    if (vFlip)
                    {
                        y = height - y - Constants.SpriteHeight;
                    }

                    if (hFlip)
                    {
                        x = width - x - Constants.SpriteWidth;
                    }

                    // Draw the image.
                    image.DrawImage(spriteImage, x, y);
                }
            }

            if (showBoxes && offsets.XOff != 255)
            {
                image.DrawRectangle(MyBitmap.ThreatBoxColor, offsets.XOff, offsets.YOff, offsets.XOff + offsets.Width, offsets.YOff + offsets.Height);
            }

            // Scale image.
            var result = image.Scale(zoom).ToBitmap(transparent ? Constants.TransparentAlpha : 255, transparentBg ?  backColor : (Color?)null);

            // Save result for later and return.
            dictionary.Add(flags, result);
            return(result);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Special method for rendering the player.
        /// </summary>
        public Bitmap GetPlayerBitmap(
            SpriteConfig config,
            Color backColor,
            bool applyPalettes,
            bool showBoxes,
            bool hFlip,
            int zoom,
            bool transparentBg = false)
        {
            // Get flags for the request.
            var flags = GetFlags(applyPalettes, showBoxes, false, hFlip, false, transparentBg);

            // Checked if a cached bitmap is available, return it if it is.
            var dictionary = this.cachedBitmaps[zoom - 1];

            if (dictionary.ContainsKey(flags))
            {
                return(dictionary[flags]);
            }

            // Assume game position equals the offsets.
            var gameX = Constants.PlayerXOffset;
            var gameY = Constants.PlayerYOffset;

            // Calculate image size. Get a max of all frames.
            var maxX   = config.Frames.Max(f => f.Sprites.Max(s => gameX + Player.GetXOffset(s, hFlip)));
            var maxY   = config.Frames.Max(f => f.Sprites.Max(s => gameY + Player.GetYOffset(s)));
            var width  = maxX + Constants.SpriteWidth;
            var height = maxY + Constants.SpriteHeight;
            var image  = new MyBitmap(width, height, backColor);

            // Draw each sprite.
            foreach (var sprite in this.Sprites)
            {
                // Get the correct sprite image.
                var spriteImage = sprite.GetSprite(applyPalettes, sprite.VFlip, sprite.HFlip ^ hFlip);

                // Draw the image.
                image.DrawImage(spriteImage, gameX + Player.GetXOffset(sprite, hFlip), gameY + Player.GetYOffset(sprite));
            }

            if (showBoxes)
            {
                // Platform box.
                var platformBoxX1 = gameX;
                var platformBoxY1 = gameY;
                var platformBoxX2 = platformBoxX1 + Constants.PlayerPlatformBoxWidth;
                var platformBoxY2 = platformBoxY1 + Constants.PlayerPlatformBoxHeight;
                image.DrawRectangle(MyBitmap.PlatformBoxColor, platformBoxX1, platformBoxY1, platformBoxX2, platformBoxY2);

                // Threat box.
                var threatBoxX1 = gameX + Constants.PlayerThreatBoxXOff;
                var threatBoxY1 = gameY + Constants.PlayerThreatBoxYOff;
                var threatBoxX2 = threatBoxX1 + Constants.PlayerThreatBoxWidth;
                var threatBoxY2 = threatBoxY1 + (this.Name == "Crouch" ? Constants.PlayerThreatBoxHeightCrouch : Constants.PlayerThreatBoxHeight);
                image.DrawRectangle(MyBitmap.ThreatBoxColor, threatBoxX1, threatBoxY1, threatBoxX2, threatBoxY2);

                // Gun point.
                var gunYOff = this.Name == "Crouch" ? Constants.PlayerGunYOffCrouch : Constants.PlayerGunYOff;
                var gunXOff = hFlip ? Constants.PlayerGunOXffL : Constants.PlayerGunOXffR;
                image.SetPixel(MyBitmap.GunColor, gameX + gunXOff, gameY + gunYOff);

                // Game position.
                image.SetPixel(MyBitmap.XYColor, gameX, gameY);
            }

            // Scale image.
            var result = image.Scale(zoom).ToBitmap(backgroundColor: transparentBg ? backColor : (Color?)null);

            // Save result for later and return.
            dictionary.Add(flags, result);
            return(result);
        }
Exemplo n.º 27
0
 public MyBitmap GetChrImage() => MyBitmap.FromFile(this.ChrImagePath());
Exemplo n.º 28
0
        /*
         * public static CloudBlob ConvertImageFileFormat(CloudBlob blob, int imageWidth, int imageHeight, TraceWriter log)
         *      {
         *          // define an image (bitmap) with the right characteristics matching the input given in the HTTP request
         *          Size size = new Size(imageWidth, imageHeight);
         *          //Size size = new Size(320, 240);
         *          //Size size = new Size(640, 480);
         *
         *          // read the blob length
         *          blob.FetchAttributes();
         *          long rawfileLength = blob.Properties.Length;
         *          log.Info("ConvertImageFileFormat: rawfileLength=" + rawfileLength + " width=" + size.Width + " height=" + size.Height);
         *
         *          // read the raw blob data into a byte array (imageData)
         *          byte[] rawData = new byte[rawfileLength];
         *          byte[] modifData = new byte[rawfileLength];
         *          blob.DownloadToByteArray(rawData,0);
         *          log.Info("ConvertImageFileFormat: downloaded blob");
         *          //for (int i=0; i<8;  i++)    { log.Info("ConvertImageFileFormat: rawData=" + rawData[i]);   }
         *
         *          // Modify original picture (easier here than on Arduino)
         *          // Mirror the picture line by line
         *          long pixWidth = 2 * size.Width; // 2 bytes per pixel in RGB565
         *          long i = 0;
         *          long j = 0;
         *          for (long h=0; h<size.Height;h++)
         *          {
         *              long offset = h * pixWidth;
         *              for (long w=0; w<pixWidth;w++)
         *              {
         *                  i = offset + w;
         *                  j = offset + (pixWidth - 1) - w;
         *                  if (i < 0 || i >= rawfileLength || j < 0 || j >= rawfileLength)
         *                  {
         *                      log.Info("h=" + h + " offset=" + offset + " pixw=" + pixWidth + " i=" + i + " j=" + j);
         *                  } else
         *                  {
         *                      modifData[i] = rawData[j];
         *                  }
         *              }
         *          }
         *          log.Info("ConvertImageFileFormat: mirroring done");
         *
         *          // copy the raw data into the bitmapdata
         *          PixelFormat pxFormat = PixelFormat.Format16bppRgb565;  // OV7670 raw output format
         *          var bitmap = new Bitmap(size.Width, size.Height, pxFormat);
         *          Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
         *          BitmapData bData = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
         *
         *          IntPtr ptr = bData.Scan0;
         *          int len = modifData.Length;
         *      //    IntPtr modifDataIptr = modifData;
         *          log.Info("ConvertImageFileFormat: modifData.Length=" + modifData.Length + " bitmap.Width=" + bitmap.Width + " bitmap.Height=" + bitmap.Height + " ptr=" + ptr + " bdata.Stride=" + bData.Stride);
         *          System.Runtime.InteropServices.Marshal.Copy(modifData, 0, ptr, len);
         *          //System.Runtime.InteropServices.Marshal.Copy(modifData, ptr, 0, modifData.Length);
         *          log.Info("ConvertImageFileFormat: x5");
         *          bitmap.UnlockBits(bData);
         *          log.Info("ConvertImageFileFormat: x6");
         *          log.Info("ConvertImageFileFormat: (bData.Stride * bData.Height)=" + bData.Stride + "*" + bData.Height + "= " + (bData.Stride * bData.Height) + " Should equal size of blob");
         *
         *          // Dump imagedata
         *      /*    IntPtr ptr = bData.Scan0;
         *          int bytes  = Math.Abs(bData.Stride) * bitmap.Height;
         *          byte[] rgbValues = new byte[bytes];
         *          // Copy the RGB values into the array (only used for printout).
         *          System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
         *          for (int i=0; i<5;  i++)    { log.Info("ConvertImageFileFormat: rgbValues=" + rgbValues[i]);   }
         */
        // Encode to JPEG
        //create an encoder parameter for the image quality

        /*           EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
         *         //get the jpeg codec
         *         ImageCodecInfo imgCodec = GetEncoderInfo("image/jpeg");
         *         //create a collection of all parameters that we will pass to the encoder
         *         EncoderParameters encoderParams = new EncoderParameters(1);
         *         //set the quality parameter for the codec
         *         encoderParams.Param[0] = qualityParam;
         *
         *         // copy the bitmapdata to a new memorystream in the desired file format
         *         MemoryStream outStream = new MemoryStream();
         *         outStream.Position = 0;
         *         bitmap.Save(outStream, imgCodec, encoderParams);
         *
         *         log.Info("ConvertImageFileFormat: memStream data: " + outStream.Length + " pos: " + outStream.Position );
         *
         *         //dump memStream
         *         //   outStream.Position = 0;
         *         //   for (int i=0; i<5;  i++)    { log.Info("ConvertImageFileFormat: DUMP=" + outStream.ReadByte());   }
         *
         *         // Retrieve storage account from connection string.
         *         CloudStorageAccount storageAccount = CloudStorageAccount.Parse(STORAGE_ACCOUNT_CS);
         *         CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
         *         CloudBlobContainer container = blobClient.GetContainerReference(STORAGE_CONTAINER_NAME);
         *         log.Info("ConvertImageFileFormat: x8");
         *
         *         string newFilename = blob.Name + ".jpg";
         *         CloudBlockBlob newBlob = container.GetBlockBlobReference(newFilename);
         *         outStream.Position = 0;
         *         newBlob.UploadFromStream(outStream);
         *         log.Info("ConvertImageFileFormat: JPG generated:" + newFilename);
         *
         *         // and also save to BMP for debugging
         *         outStream.Position = 0;
         *         bitmap.Save(outStream, System.Drawing.Imaging.ImageFormat.Bmp);
         *         string bmpFilename = blob.Name + ".bmp";
         *         CloudBlockBlob bmpBlob = container.GetBlockBlobReference(bmpFilename);
         *         outStream.Position = 0;
         *         bmpBlob.UploadFromStream(outStream);
         *         log.Info("ConvertImageFileFormat: BMP generated:" + bmpFilename );
         *
         *         return newBlob;
         *     }
         *
         *     private static ImageCodecInfo GetEncoderInfo(String mimeType)
         *     {
         *         int j;
         *         ImageCodecInfo[] encoders;
         *         encoders = ImageCodecInfo.GetImageEncoders();
         *         for(j = 0; j < encoders.Length; ++j)
         *         {
         *             if(encoders[j].MimeType == mimeType)
         *                 return encoders[j];
         *         }
         *         return null;
         *     }
         *
         */

        private void DataReceivedHandlerORG(object sender, SerialDataReceivedEventArgs e)
        {
            //byte R; byte G; byte B; //byte Cb; byte Y0; byte Cr; byte Y1;
            //UInt16 Ri; UInt16 Gi1; UInt16 Gi2; UInt16 Gi; UInt16 Bi;

            int   bytesInBuffer = 0;
            int   bytesRead = 0;
            var   header_buffer = new byte[100];
            var   buffer = new byte[2 * WIDTH]; //2* to accomodate for yvu422 or rgb565 coding (two bytes per pixel)
            Color pix1 = Color.Black; Color pix2 = Color.Black;

            _readingImageSession += 1;
            //Trace.WriteLine("START Reading image. Session=" + _readingImageSession.ToString() + "  _readingImage=" + _readingImage.ToString());
            //LblStatus("START");
            try
            {
                //var sw = new Stopwatch();
                //sw.Start();

                var sp = (SerialPort)sender;
                if (!sp.IsOpen)
                {
                    Trace.WriteLine("*** Port already open.  Session:" + _readingImageSession.ToString());
                    return;
                }

                if (!_readingImage)
                {
                    // look for header info
                    bytesRead = 0;
                    // look for "###" probably indicating first byte in header
                    while (sp.ReadChar() != '#')
                    {
                        ;
                    }
                    if ((sp.ReadChar() == '#') && (sp.ReadChar() == '#'))
                    {
                        if (sp.BytesToRead > 0)
                        {
                            bytesInBuffer = sp.BytesToRead;
                            bytesRead     = sp.Read(header_buffer, 0, 15); //15: *RDY* (5bytes) + width (2b) + height (2b) + pixelSize (2b) + totalBytes (4b)
                            PrintBuffer(header_buffer, bytesRead);
                        }
                        //LblStatus($"bytesRead: bytes={buffer.Length}: {buffer[0]}-{buffer[1]}-{buffer[2]}-{buffer[3]}-{buffer[4]}");

                        if (bytesRead > 4 && header_buffer[0] == '*' && header_buffer[1] == 'R' && header_buffer[2] == 'D' && header_buffer[3] == 'Y' && header_buffer[4] == '*')  // Look for *RDY* to sync image start
                        {
                            _readingImage = true;
                            Trace.WriteLine("Setting ReadingImage. Session=" + _readingImageSession.ToString() + "  ReadingImage=" + _readingImage.ToString());
                            // reader width, height and size information:
                            width          = (int)((byte)(header_buffer[6]) << 8 | (byte)(header_buffer[5]));
                            height         = (int)((byte)(header_buffer[8]) << 8 | (byte)(header_buffer[7]));
                            pixelSize      = (int)((byte)(header_buffer[10]) << 8 | (byte)(header_buffer[9]));
                            totalImageSize = (int)(
                                (byte)(header_buffer[14]) << 24 | (byte)(header_buffer[13]) << 16 |
                                    (byte)(header_buffer[12]) << 8 | (byte)(header_buffer[11]));
                            if ((width != WIDTH) || (height != HEIGHT))
                            {
                                String s = "";
                                for (int i = 0; i < 13; i++)
                                {
                                    s = s + " " + i.ToString() + ":" + header_buffer[i].ToString();
                                }
                                Trace.WriteLine("*** DUMP: " + s);
                                Trace.WriteLine("*** ERROR: Height or width inconsistent. height=" + height.ToString() + " HEIGHT=" + HEIGHT.ToString() + " width=" + width.ToString() + " WIDTH=" + WIDTH.ToString());
                            }
                            bytesRead        = 0;
                            header_buffer[0] = 0;
                            byteCount        = 0;
                            Trace.WriteLine("*** *RDY* found. Session:" + _readingImageSession.ToString() + " width:" + width.ToString() + "  height:" + height.ToString() + "  size:" + totalImageSize.ToString());
                            //LblStatus("Found *RDY*");
                            LblStatus($"Reading image from serial port {cboSerialPorts.SelectedText}...");
                        }
                    }
                }
                else
                {
                    // (continue to) read the image data
                    //Application.DoEvents();  //allow GUI to catch up
                    if (!sp.IsOpen)
                    {
                        return;
                    }
                    while (yy < height)
                    {
                        //Application.DoEvents();  //allow GUI to catch up
                        while (xx < width)
                        {
                            if (sp.BytesToRead > 0)
                            {
                                int maxBytesToRead = (width - xx);
                                bytesInBuffer = sp.BytesToRead;
                                bytesRead     = sp.Read(buffer, 0, maxBytesToRead); // read as many bytes as possible up to max line lenght
                                xx           += bytesRead;
                                //PrintBuffer(buffer, bytesRead);
                                //Trace.WriteLine("read:" +  " xx=" + xx.ToString() + "  yy=" + yy.ToString() + "  Received bytes=" + bytesRead.ToString());
                            }
                        }
                        if (xx == width)   // if end of line, reset counters to read next line. This is needed to ensure re-entrance
                        {
                            //PrintBuffer(buffer, bytesRead);
                            //Trace.WriteLine("*** BEFORE MyBitmap.SetPixel:" +  " i=" + i.ToString() + "  xx=" + xx.ToString() + "  yy=" + yy.ToString() + "  Received bytes=" + bytesRead.ToString());

                            //MyBitmap.SetPixel(i, yy, Color.FromArgb(1, buffer[i], buffer[i], buffer[i]));

                            int   i;
                            Color c;
                            switch (ColorSpace)
                            {
                            case COLORSPACE.YUV422:
                                for (i = 0; i < width / 4; i += 2)    // 4 bytes pr 2 pixels
                                {
                                    yvu422_RGB(buffer, i * 4, ref pix1, ref pix2);
                                    MyBitmap.SetPixel(i, yy, pix1);
                                    MyBitmap.SetPixel(i + 1, yy, pix2);
                                    if (i == 80 - 1)
                                    {
                                        /*Trace.WriteLine("Sess:" + _readingImageSession.ToString() +
                                         * " i=" + i.ToString() + "  yy=" + yy.ToString() +
                                         * " Y0=" + Y0.ToString() + "  Cb=" + Cb.ToString() +
                                         * " Y1=" + Y1.ToString() + "  Cr=" + Cr.ToString() +
                                         * " ---   R=" + R.ToString() + " G=" + G.ToString() + " B=" + B.ToString());*/
                                    }
                                }
                                break;

                            case COLORSPACE.RGB565:

                                //HERTIL: lav det her om til et kald i main_yvu og brug algoritmen nedenfor (er taget fra Azure funktionen)

                                for (i = 0; i < width; i += 1)      // 2 bytes pr 1 pixels
                                {
                                    /*buffer[i*2] = 0;
                                     * buffer[i*2+1] = 128;
                                     * /*R = (byte) ( (int)(buffer[2*i]) >> 3);
                                     * G = (byte) (((buffer[2*i] & 0x07)<<3) + (buffer[2*i+1] >> 5));
                                     * B = (byte) ((int) (buffer[2*i+1] & 0x1F));
                                     */

                                    // R R R R R G G G   G G G B B B B B

                                    /*Ri =  (byte) ((UInt16) (buffer[2*i]) >> 3);
                                     *     //Ri =  (byte) ((UInt16) 8 * Ri );
                                     * Gi1 = (byte) ((UInt16) (buffer[2*i]) & 0b00000111);
                                     * Gi1 = (byte)((UInt16)8 * Gi1);
                                     * Gi2 = (byte) ((UInt16)    (buffer[2*i+1]) >> 5);
                                     * Gi =  (byte) (Gi1 + Gi2);
                                     * Bi =  (byte) ((UInt16) (buffer[2*i+1]) & 0b00011111);
                                     * R = (byte) Ri;
                                     * G = (byte) Gi;
                                     * B = (byte) Bi;
                                     *
                                     *
                                     * /*R = (byte) (( buffer[2*i+1] >> 3)<<3);
                                     * G = (byte) (((buffer[2*i+1] & 0x07)<<3) + (buffer[2*i] >> 5));
                                     * B = (byte) ( buffer[2*i] & 0x1F);
                                     *
                                     *
                                     * R = buffer[i*2];
                                     * G = buffer[i*2];
                                     * B = buffer[i*2];
                                     *
                                     *
                                     * // generate test image:
                                     * /*if (i < width)
                                     * {
                                     *  R = (byte)((8 * i + 8 * yy) % 255);
                                     *  G = (byte)((4 * i + 3 * yy) % 255);
                                     *  B = (byte)((2 * i + 6 * yy) % 255);
                                     * }*/

                                    //rgb565swapped(imgBuf, 2*i, ref pix1);  // 2 bytes per pixel
                                    MyBitmap.SetPixel(i, yy, pix1);
                                    //c = Color.FromArgb(R, G, B);
                                    //c = Color.FromArgb(R, G, B);
                                    //MyBitmap.SetPixel(i, yy, c);
                                    //Trace.WriteLine("*** i=" + i.ToString() + " yy=" + yy.ToString() + " c=" + c.Name + " RGB=" + R.ToString() + " " + G.ToString() + " " + B.ToString());
                                }
                                break;
                            }
                            yy += 1;
                            //Trace.WriteLine("*** Line read. Session:" + _readingImageSession.ToString() + " xx=" + xx.ToString() + "  yy=" + yy.ToString() + "  bytesRead=" + bytesRead.ToString());
                            xx = 0;
                        }
                    }
                    if ((yy == height) && (xx == 0) && _readingImage)
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            MyBitmap.Save(memoryStream, ImageFormat.Bmp);

                            picImage.Invoke((MethodInvoker)(() =>
                            {
                                picImage.Image = Image.FromStream(memoryStream);
                            }));
                        }
                        Trace.WriteLine("*** FINISH Session:" + _readingImageSession.ToString() + " xx=" + xx.ToString() + "  yy=" + yy.ToString() + "  Received bytes=" + byteCount.ToString());
                        Application.DoEvents();  //allow GUI to catch up
                        _readingImage = false;
                        yy            = 0;
                    }
                }
            }
            catch (Exception ex)
            {
                LblStatus($"Error: {ex.Message}");
            }
            finally
            {
                if ((byteCount >= totalImageSize) && (byteCount > 0))
                {
                    //sw.Stop();
                    //LblStatus($"Image was read. Time taken: {sw.ElapsedMilliseconds} ms");
                    Trace.WriteLine("***FINISH: Image was read");
                    Thread.Sleep(500);
                    Application.DoEvents();
                    if (!btnStop.Enabled)
                    {
                        CloseSerialPort();
                    }
                    //Trace.WriteLine("Session:" + _readingImageSession.ToString() + " *** Clear serial buffer");
                    //sp.ReadExisting();
                    _readingImage = false;
                    Trace.WriteLine("Releasing readingImage. Session=" + _readingImageSession.ToString() + "  ReadingImage=" + _readingImage.ToString());
                }
            }
        }
Exemplo n.º 29
0
        private void LoadButtonClick(object sender, EventArgs e)
        {
            var fileName = this.inputTextBox.Text;

            if (!File.Exists(fileName))
            {
                MessageBox.Show("File doesn't exit");
            }

            this.bitmap = MyBitmap.FromFile(fileName);

            if (this.bitmap.Width != Constants.BgWidth || this.bitmap.Height != Constants.BgHeight)
            {
                MessageBox.Show($"Incorrect size, should be {Constants.BgWidth}x{Constants.BgHeight}");
            }

            this.tiles     = new List <MyBitmap>();
            this.positions = new List <Point>();
            var indices = new int[32, 24];

            for (var y = 0; y < this.bitmap.Height / Constants.NesTileSize; y++)
            {
                for (var x = 0; x < this.bitmap.Width / Constants.NesTileSize; x++)
                {
                    var smallImage = bitmap.GetPart(x * Constants.NesTileSize, y * Constants.NesTileSize, Constants.NesTileSize, Constants.NesTileSize);
                    if (this.tiles.Any(v => v.Equals(smallImage)))
                    {
                        indices[x, y] = this.tiles.IndexOf(smallImage);
                    }
                    else
                    {
                        this.tiles.Add(smallImage);
                        this.positions.Add(new Point(x * Constants.NesTileSize, y * Constants.NesTileSize));
                        indices[x, y] = this.tiles.Count - 1;
                    }
                }
            }

            const int entryWidth        = 65;
            const int horizontalSpacing = 8;
            const int entriesInRow      = 7;
            const int leftPadding       = 12;
            const int imageWidth        = entryWidth + (entryWidth + horizontalSpacing) * (entriesInRow - 1) + leftPadding;
            const int entryHeight       = 33;
            const int verticalSpacing   = 2;
            const int topPadding        = 12;
            var       rowCount          = (this.tiles.Count + entriesInRow - 1) / entriesInRow;
            var       imageHeight       = rowCount * entryHeight + (rowCount - 1) * verticalSpacing + topPadding;

            this.smallImagesBitmap = new MyBitmap(imageWidth, imageHeight);

            var font = new Font("Calibri", 8);

            for (var i = 0; i < this.tiles.Count; i++)
            {
                var x        = (i % entriesInRow) * (entryWidth + horizontalSpacing) + leftPadding;
                var y        = (i / entriesInRow) * (entryHeight + verticalSpacing) + topPadding;
                var tile     = this.tiles[i].Scale(2);
                var subImage = new MyBitmap(entryWidth, entryHeight);
                subImage.DrawImage(tile, (entryWidth - tile.Width) / 2, 0);

                var tempBitmap = subImage.ToBitmap();
                using (var g = Graphics.FromImage(tempBitmap))
                {
                    g.DrawString(string.Format("{0:D3}: {1:D3}/{2:D3}", i, this.positions[i].X, this.positions[i].Y), font, Brushes.Black, 0, 18);
                }

                this.smallImagesBitmap.DrawImage(MyBitmap.FromBitmap(tempBitmap), x, y);
            }

            this.smallImagesPanel.BackgroundImage = this.smallImagesBitmap.ToBitmap();

            var str = string.Empty;

            for (var y = 0; y < this.bitmap.Height / Constants.NesTileSize; y++)
            {
                for (var x = 0; x < this.bitmap.Width / Constants.NesTileSize; x++)
                {
                    str += indices[x, y].ToString("D3") + " ";
                }

                str += Environment.NewLine;
            }

            this.textBox.Text = str;
            this.UpdateImage();
        }
Exemplo n.º 30
0
        private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            int bytesInBuffer = 0;
            int bytesRead     = 0;

            byte[] buffer = new byte[2 * WIDTH * HEIGHT];  //2* to accomodate for yvu422 or rgb565 coding (two bytes per pixel)

            byte  R; byte G1; byte G2; byte G; byte B;
            Color pix1 = Color.Black; Color pix2 = Color.Black;
            Int32 idx = 0;

            _readingImageSession += 1;
            //Trace.WriteLine("START Reading image. Session=" + _readingImageSession.ToString() + "  _readingImage=" + _readingImage.ToString());
            //LblStatus("START");
            try
            {
                //var sw = new Stopwatch();
                //sw.Start();

                var sp = (SerialPort)sender;
                if (!sp.IsOpen)
                {
                    Trace.WriteLine("*** Port already open.  Session:" + _readingImageSession.ToString());
                    return;
                }

                // read the header
                while (!ReadHeaderFromSerial(sp, ref width, ref height, ref pixelSize, ref totalImageSize))
                {
                    ;
                }
                idx = 0;

                // (continue to) read the image data
                while (idx < totalImageSize)
                {
                    bytesInBuffer = sp.BytesToRead;
                    if (bytesInBuffer > 0)
                    {
                        if (bytesInBuffer > (totalImageSize - idx))
                        {
                            bytesInBuffer = (totalImageSize - idx);
                        }
                        bytesRead = sp.Read(buffer, 0, bytesInBuffer);  // read as many bytes as possible up to max line lenght
                                                                        // copy to right place in imgBuf
                        Buffer.BlockCopy(buffer, 0, imgBuf, idx, bytesRead);
                        idx += bytesRead;
                        //PrintBuffer(buffer, bytesRead);
                        //PrintBuffer(imgBuf, idx);
                    }
                }
                Trace.WriteLine("idx=" + idx.ToString());

                // process the data

                int    pixHeight = pixelSize * height;
                int    i         = 0;
                byte[] rawData   = new byte[totalImageSize];
                Buffer.BlockCopy(imgBuf, 0, rawData, 0, totalImageSize);  // then we can keep the result in imgBuf
                switch (ColorSpace)
                {
                case COLORSPACE.YUV422:

                    for (int y = 0; y < height; y++)
                    {
                        for (int x = 0; x < width; x += 2)
                        {
                            i = (y * width * pixelSize) + x * 2;
                            yvu422_RGB(imgBuf, i, ref pix1, ref pix2);
                            MyBitmap.SetPixel(x + 1, height - 1 - y, pix1);
                            MyBitmap.SetPixel(x, height - 1 - y, pix2);
                        }
                    }
                    break;

                case COLORSPACE.RGB565:      // Not used for OV7670
                    i = 0;
                    for (int x = 0; x < width; x++)
                    {
                        for (int y = 0; y < height; y++)
                        {
                            i = (x * height * pixelSize) + y;
                            // R R R R R G G G   G G G B B B B B
                            B  = (byte)(imgBuf[i] & 0b11111000);
                            G1 = (byte)(((byte)(imgBuf[i] & 0b00000111)) << 3);
                            G2 = (byte)(((byte)(imgBuf[i + 1] & 0b11100000)) >> 5);
                            G  = (byte)(G1 & G2);
                            R  = (byte)(((byte)(imgBuf[i + 1] & 0b00011111)) << 3);
                            MyBitmap.SetPixel(x, y, Color.FromArgb(R, G, B));
                            //MyBitmap.SetPixel(height - 1 - y, width - x - 1, Color.FromArgb(R, G, B));
                        }
                    }
                    break;

                default:
                    break;
                }

                // display the image
                using (var memoryStream = new MemoryStream())
                {
                    MyBitmap.Save(memoryStream, ImageFormat.Bmp);
                    picImage.Invoke((MethodInvoker)(() =>
                    {
                        picImage.Image = Image.FromStream(memoryStream);
                    }));
                }
                Application.DoEvents();  //allow GUI to catch up
            }

/*            catch (Exception ex)
 *          {
 *              LblStatus($"Error: {ex.Message}");
 *          }
 */         finally
            {
                Trace.WriteLine("***FINISH: Image was read");
                Thread.Sleep(500);
                Application.DoEvents();
                if (!btnStop.Enabled)
                {
                    CloseSerialPort();
                }
                Trace.WriteLine("Releasing readingImage. Session=" + _readingImageSession.ToString() + "  ReadingImage=" + _readingImage.ToString());
            }
        }