コード例 #1
0
        void MakeCHIPLIST()
        {
            this.ChipDisplayCache = ImageUtil.Blank(this.ChipCache.Width * 4, this.ChipCache.Height, this.ChipCache);
            for (int y = 0; y < this.ChipCache.Height; y++)
            {
                Bitmap flip = ImageUtil.Copy(this.ChipCache, 0, y * 8, 8, 8);
                ImageUtil.BitBlt(this.ChipDisplayCache, 0, y * 8, 8, 8, flip, 0, 0, 0);
                flip.Dispose();

                flip = ImageUtil.Copy(this.ChipCache, 0, y * 8, 8, 8, true);
                ImageUtil.BitBlt(this.ChipDisplayCache, 8 * 1, y * 8, 8, 8, flip, 0, 0);
                flip.Dispose();

                flip = ImageUtil.Copy(this.ChipCache, 0, y * 8, 8, 8, false, true);
                ImageUtil.BitBlt(this.ChipDisplayCache, 8 * 2, y * 8, 8, 8, flip, 0, 0);
                flip.Dispose();

                flip = ImageUtil.Copy(this.ChipCache, 0, y * 8, 8, 8, true, true);
                ImageUtil.BitBlt(this.ChipDisplayCache, 8 * 3, y * 8, 8, 8, flip, 0, 0);
                flip.Dispose();
            }

            CHIPLIST.Image = this.ChipDisplayCache;
        }
コード例 #2
0
        private void P8_ValueChanged(object sender, EventArgs e)
        {
            uint addr = U.toOffset((uint)P8.Value);

            if (!U.isSafetyOffset(addr))
            {
                X_NAME_IMG.Image = null;
                return;
            }
            byte[] img = LZ77.decompress(Program.ROM.Data, addr);
            if (img.Length <= 0)
            {
                X_NAME_IMG.Image = null;
                return;
            }
            uint paletteAddr = Program.ROM.p32(JP_FONT_PALETTE_POINTER);

            if (!U.isSafetyOffset(paletteAddr))
            {
                X_NAME_IMG.Image = null;
                return;
            }
            X_NAME_IMG.Image = ImageUtil.ByteToImage16Tile(32 * 8, 4 * 8, img, 0, Program.ROM.Data, (int)paletteAddr);
        }
コード例 #3
0
ファイル: SyncCore.cs プロジェクト: ciker/WPYoudaonNote
        /// <summary>
        /// Download and save image to local.
        /// </summary>
        /// <param name="belongedNotePath">The path of belonged note.</param>
        /// <param name="imgNode">The image HtmlNode object.</param>
        /// <param name="imgRemoteUrl">The remote url of the image.</param>
        /// <param name="imgNameWithoutExt">The image name without extension.</param>
        /// <returns></returns>
        private string downloadAndSaveImageToLocal(string belongedNotePath, HtmlNode imgNode, string imgRemoteUrl, string imgNameWithoutExt)
        {
            Debug.WriteLine("Thread Id: " + Thread.CurrentThread.ManagedThreadId + " downloadAndSaveImageToLocal: " + imgRemoteUrl);
            var res = _api.DownloadAttach(imgRemoteUrl);

            var imgType   = ImageUtil.GetImageType(res.Buffer);
            var localPath = "Images\\" + imgNameWithoutExt + "." + imgType;

            double width;

            if (imgNode.Attributes.Contains("width"))
            {
                if (Double.TryParse(imgNode.Attributes["width"].Value, out width))
                {
                    if (width > _screenWidth)
                    {
                        width = _screenWidth - 25;
                    }
                }
                imgNode.Attributes["width"].Value = width.ToString(CultureInfo.InvariantCulture);
            }
            else
            {
                var actualSize = ImageUtil.GetImageSize(imgType, res.Buffer);
                width = actualSize.Width > _screenWidth ? _screenWidth - 25 : actualSize.Width;
                imgNode.Attributes.Add("width", width.ToString(CultureInfo.InvariantCulture));
            }
            // Save to disk.
            var savePath = IsoStoreUtil.SaveToIsoStore(localPath, res.Buffer);
            // Save to db.
            var imageEntity = new ImageEntity(imgNameWithoutExt, imgType.ToString(), savePath, imgRemoteUrl, belongedNotePath);

            ImageDao.InsertIfNotExist(imageEntity);

            return(savePath);
        }
コード例 #4
0
        public IObservable <ColoredFrame> GetColoredGray2Frames()
        {
            double lastHue = 0;

            Color[] palette = null;
            int     index   = -1;

            if (_framesColoredGray2 == null)
            {
                var gridProcessor = new GridProcessor {
                    Spacing = 1d
                };
                Logger.Info("Capturing at {0} frames per second...", FramesPerSecond);
                _framesColoredGray2 = Observable.Interval(TimeSpan.FromMilliseconds(1000d / FramesPerSecond))
                                      .Select(x => CaptureWindow())
                                      .Where(bmp => bmp != null)
                                      .Select(bmp => TransformationUtil.Transform(bmp, 128, 32, ResizeMode.Stretch, false, false))
                                      .Select(bmp => {
                    double hue;
                    var frame = ImageUtil.ConvertToGray2(bmp, 0.025, 0.3, out hue);
                    if (palette == null || Math.Abs(hue - lastHue) > 0.01)
                    {
                        byte r, g, b;
                        ColorUtil.HslToRgb(hue, 1, 0.5, out r, out g, out b);
                        var color = Color.FromRgb(r, g, b);
                        palette   = ColorUtil.GetPalette(new[] { Colors.Black, color }, 4);
                        lastHue   = hue;
                    }
                    return(new ColoredFrame(FrameUtil.Split(bmp.PixelWidth, bmp.PixelHeight, 2, frame), palette, index));
                })
                                      .Publish();

                StartPolling();
            }
            return(_framesColoredGray2);
        }
コード例 #5
0
        public bool UpdateQuestion(MultiChoiceSameQuestionModel model)
        {
            try
            {
                var entity = MappingUtil.Map <MultiChoiceSameQuestionModel, MultiChoiceSameQuestion>(model);

                if (entity.AddContentType == AddContentTypeEnum.PictureOnly && model.IsImageChanged)
                {
                    string tmpString;
                    ImageUtil.SaveImage("Test_" + model.TestId.ToString(), model.NewImageFileName, "", model.ImageContent, out tmpString, true);
                    entity.ImageUrl = tmpString;
                }

                _uow.MultiChoiceSameQuestions.Update(entity);
                _uow.SaveChanges();

                return(true);
            }
            catch (Exception ex)
            {
                _svcContainer.LoggingSvc.Log(ex);
                return(false);
            }
        }
コード例 #6
0
        private void ExportButton_Click(object sender, EventArgs e)
        {
            byte b2          = (byte)W2.Value;
            uint pic_address = (uint)P4.Value;

            X_ONE_STEP.Value = 0;

            int palette_type = X_PALETTE.SelectedIndex;

            string filename = ImageFormRef.SaveDialogPngOrGIF(InputFormRef);

            if (filename == "")
            {
                return;
            }

            string ext = U.GetFilenameExt(filename);

            if (ext == ".GIF")
            {
                bool r = SaveAnimeGif(filename, pic_address, palette_type, b2);
                if (!r)
                {
                    return;
                }
            }
            else
            {
                Bitmap bitmap = LoadWaitUnitIcon(pic_address, palette_type, b2);
                ImageUtil.BlackOutUnnecessaryColors(bitmap, 1);
                U.BitmapSave(bitmap, filename);
            }

            //エクスプローラで選択しよう
            U.SelectFileByExplorer(filename);
        }
コード例 #7
0
ファイル: Customer.cs プロジェクト: vendstor/vendstor
        void InitializeUI()
        {
            SoftColor = UserInterface.SoftColor;
            Color HoverColor = Color.FromArgb(200, SoftColor);

            //Change Color
            dpDateOfBirth.BackColor         = dpdCountry.NomalColor = SoftColor;
            txtFirstName.BorderColorFocused = txtLastName.BorderColorFocused = txtCustomerCode.BorderColorFocused =
                txtEmail.BorderColorFocused = txtPhoneNumber.BorderColorFocused = txtWebsite.BorderColorFocused = txtStreet.BorderColorFocused = txtCity.BorderColorFocused = txtPostCode.BorderColorFocused = SoftColor;

            btnSave.Activecolor      = btnSave.Normalcolor = btnSave.BackColor = SoftColor;
            ckbFemale.CheckedOnColor = ckbFemale.CheckedOnColor = SwitchMarkettingQuery.OnColor = SoftColor;
            //HoverColor
            btnSave.OnHovercolor = HoverColor;
            txtFirstName.BorderColorMouseHover = txtLastName.BorderColorMouseHover = txtCustomerCode.BorderColorMouseHover =
                txtEmail.BorderColorMouseHover = txtPhoneNumber.BorderColorMouseHover = txtWebsite.BorderColorMouseHover = txtStreet.BorderColorMouseHover = txtCity.BorderColorMouseHover = txtPostCode.BorderColorMouseHover = SoftColor;
            //Color Images
            imgbtnGoFirstFields.Image  = ImageUtil.ColorImage(imgbtnGoFirstFields.Image, ColorGray);
            imgbtn_Exit.Image          = ImageUtil.ColorImage(imgbtn_Exit.Image, ColorGray);
            imgbtnGoSecondFields.Image = ImageUtil.ColorImage(imgbtnGoSecondFields.Image, ColorGray);

            //Size
            this.Size = ControlDefaultSize;
        }
コード例 #8
0
                public void EnsureImage()
                {
                    var formChrome = _manager._mainWindowChrome.FormChrome;

                    if (formChrome == null)
                    {
                        return;
                    }

                    if (_resource == null || Image != null)
                    {
                        return;
                    }

                    Image = (Bitmap)System.Drawing.Image.FromStream(_resource.ToStream());

                    if (Image != null)
                    {
                        EnabledImage  = ImageUtil.GetImage(Image, ForeColor.GetValueOrDefault(Color.Black));
                        DisabledImage = ImageUtil.GetImage(Image, SystemColors.ControlDark);
                        OverImage     = ImageUtil.GetImage(Image, formChrome.PrimaryColor);
                        DownImage     = ImageUtil.GetImage(Image, Color.White);
                    }
                }
コード例 #9
0
        public static Image GetRaidResultSprite(RaidPKM raidPkm, bool active)
        {
            var sprite = SpriteUtil.GetSprite(raidPkm.Species, raidPkm.AltForm, raidPkm.Gender, 0, 0, false, raidPkm.ShinyType > 0 && raidPkm.ShinyType != 3, 8, false, raidPkm.ShinyType == 2);

            if (raidPkm.IsGigantamax)
            {
                var gm = Resources.dyna;
                sprite = ImageUtil.LayerImage(sprite, gm, (sprite.Width - gm.Width) / 2, 0);
            }

            if (raidPkm.ShinyType == 3)
            {
                // No Shiny
                var icon = Resources.no_shiny;
                sprite = ImageUtil.LayerImage(sprite, icon, 0, 0, 0.7);
            }

            if (!active)
            {
                sprite = ImageUtil.ToGrayscale(sprite);
            }

            return(sprite);
        }
コード例 #10
0
ファイル: Discount.cs プロジェクト: vendstor/vendstor
        void InitializeUI()
        {
            SoftColor = UserInterface.SoftColor;
            Color HoverColor = Color.FromArgb(200, SoftColor);

            imgbtnExit.Image           = ImageUtil.ColorImage(imgbtnExit.Image, ColorGray);
            imgbtnGoFirstFields.Image  = ImageUtil.ColorImage(imgbtnGoFirstFields.Image, ColorGray);
            imgbtnGoSecondFields.Image = ImageUtil.ColorImage(imgbtnGoSecondFields.Image, ColorGray);
            UserInterface.SetFlatButtonColor(btnAddProduct, SoftColor);
            UserInterface.SetFlatButtonColor(btnSave, SoftColor);
            //Size
            this.Size = ControlDefaultSize;
            //Default Location
            imgbtnExit.Location = new Point(833, 9);
            //Elipse
            new Bunifu.Framework.UI.BunifuElipse {
                ElipseRadius = 10
            }.TargetControl = imgbtnCash;
            new Bunifu.Framework.UI.BunifuElipse {
                ElipseRadius = 10
            }.TargetControl = imgbtnPercentage;
            ImageUtil.ColorImageButton(imgbtnCash, UserInterface.ColorGray);
            ImageUtil.ColorImageButton(imgbtnPercentage, UserInterface.ColorGray);
        }
コード例 #11
0
        public static Bitmap DrawMapStyle(
            uint obj_plist         //image
            , uint palette_plist   //palette
            , uint config_plist    //tsa
            )
        {
            //マップチップの読込
            Bitmap MapObjImage = ImageUtilMap.DrawMapChipOnly(obj_plist, palette_plist);

            if (MapObjImage == null)
            {
                MapObjImage = ImageUtil.BlankDummy();
            }
            //チップセットの読込(マップチップの画像をどう解釈するか定義するデータ)
            byte[] configUZ = ImageUtilMap.UnLZ77ChipsetData(config_plist);
            if (configUZ == null)
            {
                configUZ = new byte[0];
            }

            Bitmap mapObjCels = ImageUtil.Blank(16 * 32, ImageUtilMap.CHIPSET_SEP_BYTE / 16, MapObjImage);
            int    chip       = 0;
            int    y          = 0;

            while (chip < ImageUtilMap.CHIPSET_SEP_BYTE / 8)
            {
                for (int x = 0; x < 32; x++)
                {
                    ImageUtil.BitBlt(mapObjCels, x * 16, y * 16, 16, 16, ImageUtilMap.DrawOneChipset(chip << 2, configUZ, MapObjImage), 0, 0);

                    chip++;
                }
                y++;
            }
            return(mapObjCels);
        }
コード例 #12
0
    // 测试根据特征值和图片二进制buf比较
    public void test_match_by_feature()
    {
        // 获取特征值2048个字节
        byte[] fea       = new byte[2048];
        string file_name = Application.streamingAssetsPath + "/2.jpg";
        int    len       = 0;
        IntPtr ptr       = get_face_feature(file_name, ref len);

        if (len != 2048)
        {
            Debug.Log("get face feature error!");
            return;
        }
        Marshal.Copy(ptr, fea, 0, 2048);
        // 获取图片二进制buffer
        //System.Drawing.Image img2 = System.Drawing.Image.FromFile("d:\\8.jpg");
        //byte[] img_bytes2 = ImageUtil.img2byte(img2);
        byte[] img_bytes2 = ImageUtil.GetImageBytes(Application.streamingAssetsPath + "/1.jpg");

        IntPtr ptr_res = match_by_feature(fea, fea.Length, img_bytes2, img_bytes2.Length);
        string buf     = Marshal.PtrToStringAnsi(ptr_res);

        Debug.Log("match_by_feature res is:" + buf);
    }
コード例 #13
0
        public void SetImageSize(Topic topic, ImageLabel imageLabel)
        {
            #region validation

            if (topic == null)
            {
                throw new ArgumentNullException(nameof(topic));
            }

            if (imageLabel == null)
            {
                throw new ArgumentNullException(nameof(imageLabel));
            }

            #endregion

            using (System.IO.Stream imageStream = FileContainer.GetFileStream(imageLabel.Id, GetImageFolder(topic)))
            {
                Rect imageDimension = ImageUtil.GetDimensionFromImage(imageStream);

                imageLabel.Height = imageDimension.Height;
                imageLabel.Width  = imageDimension.Width;
            }
        }
コード例 #14
0
        private void ImportButton_Click(object sender, EventArgs e)
        {
            int    width         = 256;
            int    height        = 8 * 4; //32
            int    palette_count = 1;
            Bitmap bitmap        = ImageUtil.LoadAndConvertDecolorUI(this, null, width, height, true, palette_count);

            if (bitmap == null)
            {
                return;
            }

            byte[] image   = ImageUtil.ImageToByte16Tile(bitmap, width, height);
            byte[] palette = ImageUtil.ImageToPalette(bitmap, 1);

            //画像等データの書き込み
            Undo.UndoData undodata = Program.Undo.NewUndoData(this);
            this.InputFormRef.WriteImageData(this.D12, image, true, undodata);
            this.InputFormRef.WriteImageData(this.D16, palette, false, undodata);
            Program.Undo.Push(undodata);

            //ポインタの書き込み
            this.WriteButton.PerformClick();
        }
コード例 #15
0
        public static Bitmap DrawImageByID(uint id)
        {
            InputFormRef InputFormRef = Init(null);
            uint         addr         = InputFormRef.IDToAddr(id);

            if (addr == U.NOT_FOUND)
            {
                return(ImageUtil.BlankDummy());
            }
            uint typeFlag = Program.ROM.u8(addr);

            uint table   = Program.ROM.u32(addr + 4);
            uint tsa     = Program.ROM.u32(addr + 8);
            uint palette = Program.ROM.u32(addr + 12);

            if (typeFlag == 0x00)
            {//単体
                return(DrawOneImage(table, tsa, palette));
            }
            else
            {//10分割
                return(ImageCGForm.DrawImage(table, tsa, palette));
            }
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: balinabbb/halal
        static void Main()
        {
            var points = File.ReadLines(Points3)
                         .Select(x => x.Split('\t'))
                         .Select(x => new Point {
                X = int.Parse(x[0]), Y = int.Parse(x[1])
            })
                         .ToList();

            _solver = new TspSa();
            _solver.Init(points, Iterations);

            var best  = default(Individual);
            var count = 0;

            foreach (var current in _solver.Solve())
            {
                best = current;
                Console.Write($"\r{count++}-{current.Fitness()}");
            }

            ImageUtil.SaveAsImage(best.Genes);
            Process.Start(Path.Combine(Directory.GetCurrentDirectory(), ImageUtil.FileName));
        }
コード例 #17
0
        /// <summary>
        /// 人脸库图片选择按钮事件
        /// </summary>
        private void ChooseMultiImg(object sender, EventArgs e)
        {
            lock (locker)
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Title       = "选择图片";
                openFileDialog.Filter      = "图片文件|*.bmp;*.jpg;*.jpeg;*.png";
                openFileDialog.Multiselect = true;
                openFileDialog.FileName    = string.Empty;
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    List <string> imagePathListTemp = new List <string>();
                    var           numStart          = imagePathList.Count;
                    int           isGoodImage       = 0;

                    //保存图片路径并显示
                    string[] fileNames = openFileDialog.FileNames;
                    for (int i = 0; i < fileNames.Length; i++)
                    {
                        imagePathListTemp.Add(fileNames[i]);
                    }

                    //人脸检测以及提取人脸特征
                    ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
                    {
                        //禁止点击按钮
                        Invoke(new Action(delegate
                        {
                            chooseMultiImgBtn.Enabled = false;
                            matchBtn.Enabled          = false;
                            btnClearFaceList.Enabled  = false;
                            chooseImgBtn.Enabled      = false;
                        }));

                        //人脸检测和剪裁
                        for (int i = 0; i < imagePathListTemp.Count; i++)
                        {
                            Image image = Image.FromFile(imagePathListTemp[i]);
                            ASF_MultiFaceInfo multiFaceInfo = FaceUtil.DetectFace(pEngine, image);

                            if (multiFaceInfo.faceNum > 0)
                            {
                                imagePathList.Add(imagePathListTemp[i]);
                                MRECT rect = MemoryUtil.PtrToStructure <MRECT>(multiFaceInfo.faceRects);
                                image      = ImageUtil.CutImage(image, rect.left, rect.top, rect.right, rect.bottom);
                            }
                            else
                            {
                                continue;
                            }

                            this.Invoke(new Action(delegate
                            {
                                if (image == null)
                                {
                                    image = Image.FromFile(imagePathListTemp[i]);
                                }
                                imageLists.Images.Add(imagePathListTemp[i], image);
                                imageList.Items.Add((numStart + isGoodImage) + "号", imagePathListTemp[i]);
                                isGoodImage += 1;
                                image        = null;
                            }));
                        }


                        //提取人脸特征
                        for (int i = numStart; i < imagePathList.Count; i++)
                        {
                            ASF_SingleFaceInfo singleFaceInfo = new ASF_SingleFaceInfo();
                            IntPtr feature = FaceUtil.ExtractFeature(pEngine, Image.FromFile(imagePathList[i]), out singleFaceInfo);
                            this.Invoke(new Action(delegate
                            {
                                if (singleFaceInfo.faceRect.left == 0 && singleFaceInfo.faceRect.right == 0)
                                {
                                    AppendText(string.Format("{0}号未检测到人脸\r\n", i));
                                }
                                else
                                {
                                    AppendText(string.Format("已提取{0}号人脸特征值,[left:{1},right:{2},top:{3},bottom:{4},orient:{5}]\r\n", i, singleFaceInfo.faceRect.left, singleFaceInfo.faceRect.right, singleFaceInfo.faceRect.top, singleFaceInfo.faceRect.bottom, singleFaceInfo.faceOrient));
                                    imagesFeatureList.Add(feature);
                                }
                            }));
                        }
                        //imagePathList.AddRange(imagePathListTemp);
                        //允许点击按钮
                        Invoke(new Action(delegate
                        {
                            chooseMultiImgBtn.Enabled = true;
                            matchBtn.Enabled          = true;
                            btnClearFaceList.Enabled  = true;
                            chooseImgBtn.Enabled      = true;
                        }));
                    }));
                }
            }
        }
コード例 #18
0
        private void RenderSaveSection(RenderComposer composer)
        {
            // Saving
            ImGui.InputText("Name", ref _saveName, 100);
            ImGui.SameLine();
            if (string.IsNullOrEmpty(_saveName))
            {
                ImGui.TextDisabled("Save");
                ImGui.SameLine();
                ImGui.TextDisabled("SaveToFile");
            }
            else
            {
                ImGui.SameLine();
                if (ImGui.Button("SaveToFile"))
                {
                    string saveName = _saveName.ToLower();
                    if (!saveName.Contains(".anim")) saveName += ".anim";

                    // Fixups
                    if (AnimController?.MirrorXAnchors != null)
                    {
                        var emptyMirrorAnchors = true;
                        for (var i = 0; i < AnimController.MirrorXAnchors.Length; i++)
                        {
                            if (AnimController.MirrorXAnchors[i] == Vector2.Zero) continue;
                            emptyMirrorAnchors = false;
                            break;
                        }

                        if (emptyMirrorAnchors) AnimController.MirrorXAnchors = null;
                    }

                    try
                    {
                        string saveData;
                        // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                        if (AnimController != null)
                            saveData = XMLFormat.To(AnimController);
                        else
                            saveData = XMLFormat.To(Animation);

                        Engine.AssetLoader.Save(Encoding.UTF8.GetBytes(saveData), saveName);
                    }
                    catch (Exception ex)
                    {
                        Engine.Log.Error(ex);
                    }
                }

                if (ImGui.Button("Save Packed Texture"))
                {
                    string saveName = _saveName.ToLower();
                    if (!saveName.Contains(".png")) saveName += ".png";
                    Rectangle[] frames = AnimController != null ? AnimController.AnimTex.Frames : Animation.Frames;
                    var preBinnedFrames = new Rectangle[frames.Length];
                    Array.Copy(frames, preBinnedFrames, frames.Length);
                    Texture spriteSheetTexture = Animation.Texture;

                    var spacing = 2;
                    for (var i = 0; i < frames.Length; i++)
                    {
                        Rectangle frame = frames[i];
                        frames[i] = frame.Inflate(spacing, spacing);
                    }

                    Vector2 totalSize = Binning.FitRectangles(frames, true);
                    FrameBuffer texture = new FrameBuffer(totalSize).WithColor();
                    composer.RenderTo(texture);
                    for (var i = 0; i < frames.Length; i++)
                    {
                        composer.RenderSprite(frames[i].Deflate(spacing, spacing), Color.White, spriteSheetTexture, preBinnedFrames[i]);
                    }

                    composer.RenderTo(null);

                    byte[] pixelsDownload = texture.Sample(new Rectangle(0, 0, totalSize), PixelFormat.Rgba);
                    ImageUtil.FlipImageY(pixelsDownload, (int) totalSize.Y);
                    byte[] pngFile = PngFormat.Encode(pixelsDownload, totalSize, PixelFormat.Rgba);
                    Engine.AssetLoader.Save(pngFile, saveName);
                }
            }
        }
コード例 #19
0
        /// <summary>
        /// “选择识别图片”按钮事件
        /// </summary>
        private void ChooseImg(object sender, EventArgs e)
        {
            lblCompareInfo.Text = "";
            if (pEngine == IntPtr.Zero)
            {
                chooseMultiImgBtn.Enabled = false;
                matchBtn.Enabled          = false;
                btnClearFaceList.Enabled  = false;
                chooseImgBtn.Enabled      = false;
                MessageBox.Show("请先初始化引擎!");
                return;
            }
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Title       = "选择图片";
            openFileDialog.Filter      = "图片文件|*.bmp;*.jpg;*.jpeg;*.png";
            openFileDialog.Multiselect = false;
            openFileDialog.FileName    = string.Empty;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                DateTime detectStartTime = DateTime.Now;
                AppendText(string.Format("------------------------------开始检测,时间:{0}------------------------------\n", detectStartTime.ToString("yyyy-MM-dd HH:mm:ss:ms")));
                image1Path = openFileDialog.FileName;

                //获取文件,拒绝过大的图片
                FileInfo fileInfo = new FileInfo(image1Path);
                long     maxSize  = 1024 * 1024 * 2;
                if (fileInfo.Length > maxSize)
                {
                    MessageBox.Show("图像文件最大为2MB,请压缩后再导入!");
                    AppendText(string.Format("------------------------------检测结束,时间:{0}------------------------------\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ms")));
                    AppendText("\n");
                    return;
                }

                Image srcImage = Image.FromFile(image1Path);
                //调整图像宽度,需要宽度为4的倍数
                srcImage = ImageUtil.ScaleImage(srcImage, picImageCompare.Width, picImageCompare.Height);
                //调整图片数据,非常重要
                ImageInfo imageInfo = ImageUtil.ReadBMP(srcImage);
                //人脸检测
                ASF_MultiFaceInfo multiFaceInfo = FaceUtil.DetectFace(pEngine, imageInfo);
                //年龄检测
                int         retCode_Age = -1;
                ASF_AgeInfo ageInfo     = FaceUtil.AgeEstimation(pEngine, imageInfo, multiFaceInfo, out retCode_Age);
                //性别检测
                int            retCode_Gender = -1;
                ASF_GenderInfo genderInfo     = FaceUtil.GenderEstimation(pEngine, imageInfo, multiFaceInfo, out retCode_Gender);

                //3DAngle检测
                int             retCode_3DAngle = -1;
                ASF_Face3DAngle face3DAngleInfo = FaceUtil.Face3DAngleDetection(pEngine, imageInfo, multiFaceInfo, out retCode_3DAngle);

                MemoryUtil.Free(imageInfo.imgData);

                if (multiFaceInfo.faceNum < 1)
                {
                    image1Feature         = IntPtr.Zero;
                    picImageCompare.Image = srcImage;
                    AppendText(string.Format("{0} - 未检测出人脸!\n\n", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
                    AppendText(string.Format("------------------------------检测结束,时间:{0}------------------------------\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ms")));
                    AppendText("\n");
                    return;
                }

                MRECT temp       = new MRECT();
                int   ageTemp    = 0;
                int   genderTemp = 0;
                int   rectTemp   = 0;

                //标记出检测到的人脸
                for (int i = 0; i < multiFaceInfo.faceNum; i++)
                {
                    MRECT rect   = MemoryUtil.PtrToStructure <MRECT>(multiFaceInfo.faceRects + MemoryUtil.SizeOf <MRECT>() * i);
                    int   orient = MemoryUtil.PtrToStructure <int>(multiFaceInfo.faceOrients + MemoryUtil.SizeOf <int>() * i);
                    int   age    = 0;

                    if (retCode_Age != 0)
                    {
                        AppendText(string.Format("年龄检测失败,返回{0}!\n\n", retCode_Age));
                    }
                    else
                    {
                        age = MemoryUtil.PtrToStructure <int>(ageInfo.ageArray + MemoryUtil.SizeOf <int>() * i);
                    }

                    int gender = -1;
                    if (retCode_Gender != 0)
                    {
                        AppendText(string.Format("性别检测失败,返回{0}!\n\n", retCode_Gender));
                    }
                    else
                    {
                        gender = MemoryUtil.PtrToStructure <int>(genderInfo.genderArray + MemoryUtil.SizeOf <int>() * i);
                    }


                    int   face3DStatus = -1;
                    float roll         = 0f;
                    float pitch        = 0f;
                    float yaw          = 0f;
                    if (retCode_3DAngle != 0)
                    {
                        AppendText(string.Format("3DAngle检测失败,返回{0}!\n\n", retCode_3DAngle));
                    }
                    else
                    {
                        //角度状态 非0表示人脸不可信
                        face3DStatus = MemoryUtil.PtrToStructure <int>(face3DAngleInfo.status + MemoryUtil.SizeOf <int>() * i);
                        //roll为侧倾角,pitch为俯仰角,yaw为偏航角
                        roll  = MemoryUtil.PtrToStructure <float>(face3DAngleInfo.roll + MemoryUtil.SizeOf <float>() * i);
                        pitch = MemoryUtil.PtrToStructure <float>(face3DAngleInfo.pitch + MemoryUtil.SizeOf <float>() * i);
                        yaw   = MemoryUtil.PtrToStructure <float>(face3DAngleInfo.yaw + MemoryUtil.SizeOf <float>() * i);
                    }


                    int rectWidth  = rect.right - rect.left;
                    int rectHeight = rect.bottom - rect.top;

                    //查找最大人脸
                    if (rectWidth * rectHeight > rectTemp)
                    {
                        rectTemp   = rectWidth * rectHeight;
                        temp       = rect;
                        ageTemp    = age;
                        genderTemp = gender;
                    }

                    //srcImage = ImageUtil.MarkRectAndString(srcImage, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, age, gender);
                    AppendText(string.Format("{0} - 人脸坐标:[left:{1},top:{2},right:{3},bottom:{4},orient:{5},roll:{6},pitch:{7},yaw:{8},status:{11}] Age:{9} Gender:{10}\n", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), rect.left, rect.top, rect.right, rect.bottom, orient, roll, pitch, yaw, age, (gender >= 0 ? gender.ToString() : ""), face3DStatus));
                }

                srcImage = ImageUtil.MarkRectAndString(srcImage, temp.left, temp.top, temp.right - temp.left, temp.bottom - temp.top, ageTemp, genderTemp);


                AppendText(string.Format("{0} - 人脸数量:{1}\n\n", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), multiFaceInfo.faceNum));

                //显示标记后的图像
                picImageCompare.Image = srcImage;
                DateTime detectEndTime = DateTime.Now;
                AppendText(string.Format("------------------------------检测结束,时间:{0}------------------------------\n", detectEndTime.ToString("yyyy-MM-dd HH:mm:ss:ms")));
                AppendText("\n");
                ASF_SingleFaceInfo singleFaceInfo = new ASF_SingleFaceInfo();
                //提取人脸特征
                image1Feature = FaceUtil.ExtractFeature(pEngine, srcImage, out singleFaceInfo);

                //清空上次的匹配结果
                for (int i = 0; i < imagesFeatureList.Count; i++)
                {
                    imageList.Items[i].Text = string.Format("{0}号", i);
                }
            }
        }
コード例 #20
0
 public SmallIcon(BinaryReader br)
 {
     Bytes = br.ReadBytes(0x480);
     Icon  = ImageUtil.GetBitmap(Bytes, 24, 24);
 }
コード例 #21
0
 public LargeIcon(BinaryReader br)
 {
     Bytes = br.ReadBytes(0x1200);
     Icon  = ImageUtil.GetBitmap(Bytes, 48, 48);
 }
コード例 #22
0
        public static void Export(
            string filename      //書き込むファイル名
            , uint anime_address)
        {
            string basename = Path.GetFileNameWithoutExtension(filename) + "_";
            string basedir  = Path.GetDirectoryName(filename);


            anime_address = U.toOffset(anime_address);
            if (!U.isSafetyOffset(anime_address))
            {
                return;
            }


            string    programCode;
            AnimeType animeType;
            uint      anime_config_address = SkipCode(anime_address, out programCode, out animeType);

            if (anime_config_address == U.NOT_FOUND)
            {
                return;
            }
            if (anime_config_address + (4 * 5) > Program.ROM.Data.Length)
            {//範囲外
                return;
            }

            //POIN Frames
            //POIN TSAList
            //POIN GraphicsList
            //POIN PalettesList
            //WORD 0x3d1 //sound id
            uint frames      = Program.ROM.p32(anime_config_address + (4 * 0));
            uint tsalist     = Program.ROM.p32(anime_config_address + (4 * 1));
            uint graphiclist = Program.ROM.p32(anime_config_address + (4 * 2));
            uint palettelist = Program.ROM.p32(anime_config_address + (4 * 3));
            uint sound_id    = Program.ROM.u32(anime_config_address + (4 * 4));

            if (!U.isSafetyOffset(frames))
            {
                return;
            }
            if (!U.isSafetyOffset(tsalist))
            {
                return;
            }
            if (!U.isSafetyOffset(graphiclist))
            {
                return;
            }
            if (!U.isSafetyOffset(palettelist))
            {
                return;
            }

            //同じアニメを何度も出力しないように記録する.
            Dictionary <uint, Bitmap> animeHash = new Dictionary <uint, Bitmap>();
            List <string>             lines     = new List <string>();

            if (animeType == AnimeType.D)
            {
                lines.Add("D #is defender anim");
            }
            if (sound_id > 0)
            {
                lines.Add("S" + sound_id.ToString("X04") + " #play sound " + SongTableForm.GetSongName(sound_id));
            }

            //圧縮されていないデータなので、事故防止のため リミッターをかける.
            uint limitter = frames + 1024 * 1024; //1MBサーチしたらもうあきらめる.

            limitter = (uint)Math.Min(limitter, Program.ROM.Data.Length);

            for (uint n = frames; n < limitter; n += 4)
            {
                uint id   = Program.ROM.u16(n + 0);
                uint wait = Program.ROM.u16(n + 2);
                if (id == 0xFFFF)
                {
                    break;
                }

                Bitmap bitmap;
                string imagefilename = basename.Replace(" ", "_") + "g" + id.ToString("000") + ".png";
                if (animeHash.ContainsKey(id))
                {
                    bitmap = animeHash[id];
                }
                else
                {
                    bitmap = DrawFrameImage(n, graphiclist, tsalist, palettelist);

                    int paletteCount = ImageUtil.GetPalette16Count(bitmap);
                    if (paletteCount < 1)
                    {
                        paletteCount = 1;
                    }

                    //利用していないパレットを消す.
                    ImageUtil.BlackOutUnnecessaryColors(bitmap, paletteCount);

                    U.BitmapSave(bitmap, Path.Combine(basedir, imagefilename));
                    animeHash[id] = bitmap;
                }

                string line = wait.ToString() + " " + imagefilename;
                lines.Add(line);
            }

            //まとめて書き込み
            File.WriteAllLines(filename, lines);
        }
コード例 #23
0
        public static string Import(string filename, uint anime_pointer)
        {
            string basename = Path.GetFileNameWithoutExtension(filename) + "_";
            string basedir  = Path.GetDirectoryName(filename);

            //同じアニメを何度も入力しないように記録する.
            List <anime> anime_list = new List <anime>();
            List <byte>  frames     = new List <byte>();

            string[] lines = File.ReadAllLines(filename);

            uint      sound_id  = 0x3d1;
            AnimeType animeType = AnimeType.None;

            for (uint lineCount = 0; lineCount < lines.Length; lineCount++)
            {
                string line = lines[lineCount];
                if (U.IsComment(line) || U.OtherLangLine(line))
                {
                    continue;
                }
                line = U.ClipComment(line);
                if (line.Length <= 0)
                {
                    continue;
                }
                InputFormRef.DoEvents(null, "Line:" + lineCount);

                line = line.Replace("\t", " ");
                string[] sp      = line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                string   command = sp[0];
                if (command.Length <= 0)
                {
                    continue;
                }
                if (command[0] == 'S')
                {
                    sound_id = U.atoh(command.Substring(1));
                    continue;
                }
                if (command[0] == 'D')
                {
                    animeType = AnimeType.D;
                    continue;
                }
                if (!(U.isNumString(command) && sp.Length >= 2))
                {
                    continue;
                }
                if (sp.Length <= 1)
                {
                    Debug.Assert(false);
                    continue;
                }
                uint   wait  = U.atoi(command);
                string image = sp[1];

                uint id = FindImage(anime_list, image);
                if (id == U.NOT_FOUND)
                {
                    id = (uint)anime_list.Count;

                    string fullfilename = Path.Combine(basedir, image);
                    Bitmap bitmap       = ImageUtil.OpenBitmap(fullfilename);
                    if (bitmap == null)
                    {
                        return(R.Error("ファイル名が見つかりませんでした。\r\nFile: {0} line:{1}\r\n\r\nエラー内容:\r\n{2}", filename, lineCount, line));
                    }
                    if (bitmap.Width != SCREEN_WIDTH || bitmap.Height != SCREEN_HEIGHT)
                    {
                        bitmap = ImageUtil.Copy(bitmap, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
                    }

                    anime  a     = new anime();
                    string error = ImageUtil.ImageToBytePackedTSA(bitmap, SCREEN_WIDTH, SCREEN_HEIGHT, 0, out a.image, out a.tsa);
                    if (error != "")
                    {
                        return(R.Error("画像をインポートできません。\r\nFile: {0} line:{1}\r\n\r\nエラー内容:\r\n{2}", filename, lineCount, error));
                    }
                    a.image    = LZ77.compress(a.image);
                    a.tsa      = LZ77.compress(a.tsa);
                    a.pal      = ImageUtil.ImageToPalette(bitmap, 1);
                    a.filename = image;
                    anime_list.Add(a);
                }

                U.append_u16(frames, id);
                U.append_u16(frames, wait);
            }
            //term
            U.append_u16(frames, 0xFFFF);
            U.append_u16(frames, 0xFFFF);

            anime_pointer = U.toOffset(anime_pointer);
            if (!U.isSafetyOffset(anime_pointer))
            {
                return(R._("アドレスが無効です"));
            }
            uint anime_address = Program.ROM.p32(anime_pointer);

            List <Address> recycle = new List <Address>();

            RecycleOldAnime(ref recycle, basename, false, anime_address);
            RecycleAddress ra = new RecycleAddress(recycle);

            Undo.UndoData undodata = Program.Undo.NewUndoData("ImageUtilSkillSystemsAnimeCreator.Import");

            List <byte> image_list = new List <byte>();
            List <byte> tsa_list   = new List <byte>();
            List <byte> pal_list   = new List <byte>();

            for (int i = 0; i < anime_list.Count; i++)
            {
                uint p;
                p = ra.Write(anime_list[i].image, undodata);
                U.append_u32(image_list, U.toPointer(p));

                p = ra.Write(anime_list[i].tsa, undodata);
                U.append_u32(tsa_list, U.toPointer(p));

                p = ra.Write(anime_list[i].pal, undodata);
                U.append_u32(pal_list, U.toPointer(p));
            }

            List <byte> mainData = new List <byte>();

            if (Program.ROM.RomInfo.is_multibyte())
            {//FE8J
             //FE8Jには、スキルごとにプログラムは存在しない.
            }
            else
            {//FE8U
                //信じられないが、スキルアニメ毎にプログラムコードが設定される.
                if (animeType == AnimeType.D)
                {
                    string prog = Path.Combine(Program.BaseDirectory, "config", "patch2", "FE8U", "skill", "skillanimtemplate_defender_2017_01_24.dmp");
                    mainData.AddRange(File.ReadAllBytes(prog));
                }
                else
                {
                    string prog = Path.Combine(Program.BaseDirectory, "config", "patch2", "FE8U", "skill", "skillanimtemplate_2016_11_04.dmp");
                    mainData.AddRange(File.ReadAllBytes(prog));
                }
            }

            //プログラムの下にデータがある.
            {
                uint p;
                p = ra.Write(frames.ToArray(), undodata);
                U.append_u32(mainData, U.toPointer(p));

                p = ra.Write(tsa_list.ToArray(), undodata);
                U.append_u32(mainData, U.toPointer(p));

                p = ra.Write(image_list.ToArray(), undodata);
                U.append_u32(mainData, U.toPointer(p));

                p = ra.Write(pal_list.ToArray(), undodata);
                U.append_u32(mainData, U.toPointer(p));

                U.append_u32(mainData, sound_id);
            }

            //アニメポインタの書き換え.
            ra.WriteAndWritePointer(anime_pointer, mainData.ToArray(), undodata);

            Program.Undo.Push(undodata);
            return("");
        }
コード例 #24
0
ファイル: FontForm.cs プロジェクト: Klokinator/FEBuilderGBA
        //フォントの描画
        void DrawFonts()
        {
            if (SearchChar.Text.Length <= 0)
            {
                return;
            }
            string target = this.SearchChar.Text;

            target = TextForm.ConvertFEditorToEscape(target);

            Bitmap fontSampleBitmap;

            uint  fontlist_pointer = GetFontPointer(this.FontType.SelectedIndex == 0);
            Color bgcolor          = GetFontColor(this.FontType.SelectedIndex == 0);

            fontSampleBitmap = ImageUtil.Blank(FontPictureBox.Width, FontPictureBox.Height);

            PatchUtil.PRIORITY_CODE priorityCode = PatchUtil.SearchPriorityCode();

            int drawwidth = 0;

            for (int i = 0; i < this.FontSample.Text.Length; i++)
            {
                uint search_char;
                if (this.FontSample.Text[i] == '@')
                {
                    search_char = U.ConvertMojiCharToUnitFast(target, priorityCode);
                }
                else
                {
                    search_char = U.ConvertMojiCharToUnitFast(this.FontSample.Text.Substring(i, 1), priorityCode);
                }
                uint fontaddr = FindFontData(fontlist_pointer, search_char, priorityCode);
                if (fontaddr == U.NOT_FOUND)
                {
                    continue;
                }
                int    width;
                byte[] fontbyte;
                if (this.FontSample.Text[i] == '@')
                {
                    width    = (int)this.FontWidth.Value;
                    fontbyte = this.SelectFontBitmapByte;
                }
                else
                {
                    fontbyte = ReadFontData(fontaddr, out width);
                }

                if (width <= 0 || fontbyte == null)
                {
                    continue;
                }
                Bitmap bitmap = ImageUtil.ByteToImage4(16, 16, fontbyte, 0, bgcolor);

                fontSampleBitmap.Palette = bitmap.Palette;
                ImageUtil.BitBlt(fontSampleBitmap, drawwidth, 0, width, 16, bitmap, 0, 0);
                drawwidth += width;
            }
            FontPictureBox.Image = U.Zoom(fontSampleBitmap, ZoomComboBox.SelectedIndex);
        }
コード例 #25
0
        static Bitmap DrawFrameImage(uint frame, uint graphiclist, uint tsalist, uint palettelist)
        {
            if (!U.isSafetyOffset(frame))
            {
                return(ImageUtil.BlankDummy());
            }
            //struct Frames{
            //  ushort id;
            //  ushort wait;
            //}
            uint id = Program.ROM.u16(frame + 0);

            //画像リストなどから、指定ID数、読み飛ばす.
            uint objPointer = graphiclist + (id * 4);
            uint tsaPointer = tsalist + (id * 4);
            uint palPointer = palettelist + (id * 4);

            if (!U.isSafetyOffset(objPointer + 4))
            {
                return(ImageUtil.BlankDummy());
            }
            if (!U.isSafetyOffset(tsaPointer + 4))
            {
                return(ImageUtil.BlankDummy());
            }
            if (!U.isSafetyOffset(palPointer + 4))
            {
                return(ImageUtil.BlankDummy());
            }
            uint objOffset = Program.ROM.p32(objPointer);
            uint tsaOffset = Program.ROM.p32(tsaPointer);
            uint palOffset = Program.ROM.p32(palPointer);

            if (!U.isSafetyOffset(objOffset))
            {
                return(ImageUtil.BlankDummy());
            }
            if (!U.isSafetyOffset(tsaOffset))
            {
                return(ImageUtil.BlankDummy());
            }
            if (!U.isSafetyOffset(palOffset + 0x20))
            {
                return(ImageUtil.BlankDummy());
            }

            //objとtsaは圧縮されている.
            //palは、0x20(16色1パレット)固定.
            byte[] obj = LZ77.decompress(Program.ROM.Data, objOffset);
            byte[] tsa = LZ77.decompress(Program.ROM.Data, tsaOffset);

            int width  = SCREEN_WIDTH;
            int height = ImageUtil.CalcHeightbyTSA(width, tsa.Length);

            if (height < 160)
            {
                height = 160;
            }

            Bitmap retImage = ImageUtil.ByteToImage16Tile(width, height, obj, 0, Program.ROM.Data, (int)palOffset, tsa, 0);

            return(retImage);
        }
コード例 #26
0
        public static void Export(
            bool enableComment  //コメントを出すかどうか
            , string filename   //書き込むファイル名
            , uint frame
            , uint objRightToLeftOAM
            , uint objBGRightToLeftOAM
            )
        {
            objRightToLeftOAM   = U.toOffset(objRightToLeftOAM);
            objBGRightToLeftOAM = U.toOffset(objBGRightToLeftOAM);

            string basename = Path.GetFileNameWithoutExtension(filename) + "_";
            string basedir  = Path.GetDirectoryName(filename);

            //読みやすいようにコメントを入れます.
            Dictionary <uint, string> Comment_85command_Dic = U.LoadDicResource(U.ConfigDataFilename("battleanime_85command_"));

            U.MapMarge(ref Comment_85command_Dic, U.LoadDicResource(U.ConfigDataFilename("magic_command_")));

            List <String> lines = new List <String>();
            string        line;

            if (enableComment)
            {
                lines.Add("#######################################################");
                lines.Add("#");
                lines.Add("#" + R._("CSA_Creatorにインポートする時には各行の#以降を削除してください。"));
                lines.Add("#######################################################");
            }
            //同じアニメを何度も出力しないように記録する.
            List <uint> animeHash = new List <uint>();

            frame = U.toOffset(frame);
            byte[] frameData = Program.ROM.Data;

            //圧縮されていないデータなので、事故防止のため リミッターをかける.
            uint limitter = frame + 1024 * 1024; //1MBサーチしたらもうあきらめる.

            limitter = (uint)Math.Min(limitter, Program.ROM.Data.Length);

            int termCount = 0;

            for (uint n = frame; n < limitter; n += 4)
            {
                if (frameData[n + 3] == 0x80)     //0x80 Term
                {                                 //終端.
                    termCount++;
                    if (frameData[n + 1] == 0x01) //0x00 0x01 0x00 0x80 の場合続くときがある.
                    {
                        line = "~";
                        if (termCount == 1)
                        {
                            if (enableComment)
                            {
                                line += "                               #miss terminator";
                            }
                            lines.Add(line);
                            continue;
                        }
                        else
                        {
                            if (enableComment)
                            {
                                line += "                               #terminator";
                            }
                            lines.Add(line);
                        }
                    }
                    break;
                }
                else if (frameData[n + 3] == 0x85) //0x85 コマンド
                {
                    if (frameData[n] == 0x48)
                    {//音楽再生なのだが魔法ではS命令不可.
                        uint musicid = U.u16(frameData, n + 1);
                        uint id      = U.u24(frameData, n);
                        line = "C" + id.ToString("X06");
                        if (enableComment)
                        {
                            line += "                               #Sound " + musicid + " " + SongTableForm.GetSongName(musicid);
                        }
                        lines.Add(line);
                    }
                    else
                    {//それ以外の 0x85命令
                        uint id = U.u24(frameData, n);
                        line = "C" + id.ToString("X06");
                        if (enableComment)
                        {
                            line += "                               #" + U.at(Comment_85command_Dic, frameData[n]);
                        }
                        lines.Add(line);
                    }
                    continue;
                }
                else if (frameData[n + 3] != 0x86)
                {//不明な命令なので終了
                    break;
                }

                //0x86 画像 pointer
                uint wait = U.u16(frameData, n);

                //OBJの出力
                string obj_framefilename = ImageUtilMagicFEditor.ExportOBjFrameImage(
                    n
                    , frameData
                    , objRightToLeftOAM
                    , objBGRightToLeftOAM
                    , basedir
                    , basename
                    , animeHash
                    );

                //BGの出力
                string bg_framefilename = ExportBGFrameImage(n, frameData
                                                             , basedir
                                                             , basename
                                                             , animeHash
                                                             );
                if (obj_framefilename == "")
                {
                    Log.Error("borken obj frame", n.ToString());
                    obj_framefilename = ImageUtil.SaveDummyImage(basedir, basename + "_broken_obj" + n + ".png"
                                                                 , 480, 160);
                }
                if (bg_framefilename == "")
                {
                    Log.Error("borken bg frame", n.ToString());
                    bg_framefilename = ImageUtil.SaveDummyImage(basedir, basename + "_broken_bg" + n + ".png"
                                                                , 264, 160);
                }

                line = "O " + obj_framefilename;
                lines.Add(line);
                line = "B " + bg_framefilename;
                lines.Add(line);

                //表示時間の出力.
                line = wait.ToString();
                lines.Add(line);

                n += 24 + 4; // 24+4+4 = 32bytes

                lines.Add("");
            }

            line = "/// - End of animation";
            lines.Add(line);

            //まとめて書き込み
            File.WriteAllLines(filename, lines);
        }
コード例 #27
0
        static string ExportBGFrameImage(
            uint frame
            , byte[] frameData
            , string basedir
            , string basename
            , List <uint> animeHash
            )
        {
            basename = basename + "b_";


            //0  frame16 byte1 x86
            //4  objImagePointer
            //8  OAMAbsoStart
            //12 OAMBGAbsoStart
            //16 bgImagePointer
            //20 objPalettePointer
            //24 bgPalettePointer
            //CSA_Creater 28 TSA
            uint bgPointer        = U.u32(frameData, frame + 16);
            uint bgPalettePointer = U.u32(frameData, frame + 24);
            uint bgTSAPointer     = U.u32(frameData, frame + 28);

            uint   imageHash     = (bgPointer + bgTSAPointer);
            string framefilename = "";
            int    seatnumber    = animeHash.IndexOf(imageHash);

            if (seatnumber >= 0)
            {//すでに出力しているのでカットする.
                framefilename = basename + seatnumber.ToString("000") + ".png";
                return(framefilename);
            }

            byte[] bgPalette = Program.ROM.getBinaryData(U.toOffset(bgPalettePointer), 0x20);
            byte[] bg_UZ     = LZ77.decompress(Program.ROM.Data, U.toOffset(bgPointer));
            byte[] bgTSA_UZ  = LZ77.decompress(Program.ROM.Data, U.toOffset(bgTSAPointer));
            if (bg_UZ.Length <= 0 || bgTSA_UZ.Length <= 0)
            {
                Log.Error("bg_UZ", U.ToHexString(bgPointer), "or bgTSA_UZ", U.ToHexString(bgTSAPointer), "is null. broken frame.");
                return("");
            }

            //まだ出力していない画像なので作成します.
            seatnumber = animeHash.Count;
            animeHash.Add(imageHash);

            //int width = 264; //FEditorAdv
            //int height = 64;
            int width  = 256 - 8 - 8;
            int height = ImageUtil.CalcHeightbyTSA(width, bgTSA_UZ.Length);

            if (height >= 160)
            {
                height = 160;
            }
            else
            {
                height = 64;
            }
            Bitmap retImage = ImageUtil.Blank(width, height, bgPalette, 0);

            Bitmap bg = ImageUtil.ByteToImage16Tile(width, height, bg_UZ, 0, bgPalette, 0, bgTSA_UZ, 0, 0);

            ImageUtil.BitBlt(retImage, 0, 0, bg.Width, bg.Height, bg, 0, 0);


            ////パレットマークを右上に描画 CSA_Creator では不要らしい.
            ////ImageUtil.AppendPaletteMark(retImage);
            //利用していないパレットを消す.
            ImageUtil.BlackOutUnnecessaryColors(retImage, 1);

            framefilename = basename + seatnumber.ToString("000") + ".png";
            if (!U.BitmapSave(retImage, Path.Combine(basedir, framefilename)))
            {
                return("");
            }
            retImage.Dispose();

            return(framefilename);
        }
コード例 #28
0
        static Bitmap DrawFrameImage(uint frame
                                     , byte[] frameData
                                     , uint objRightToLeftOAM
                                     , uint objBGRightToLeftOAM
                                     , bool bgExpands)
        {
            //0  frame16 byte1 x86
            //4  objImagePointer
            //8  OAMAbsoStart
            //12 OAMBGAbsoStart
            //16 bgImagePointer
            //20 objPalettePointer
            //24 bgPalettePointer
            //CSA_Creater 28 TSA

            uint objPalettePointer = U.u32(frameData, frame + 20);

            if (!U.isSafetyPointer(objPalettePointer))
            {
                return(ImageUtil.BlankDummy());
            }
            byte[] objPalette = Program.ROM.getBinaryData(U.toOffset(objPalettePointer), 0x20);

            uint bgPalettePointer = U.u32(frameData, frame + 24);

            if (!U.isSafetyPointer(bgPalettePointer))
            {
                return(ImageUtil.BlankDummy());
            }
            byte[] bgPalette = Program.ROM.getBinaryData(U.toOffset(bgPalettePointer), 0x20);


            Bitmap retImage = ImageUtil.Blank((ImageUtilOAM.SEAT_TILE_WIDTH - 2) * 8, ImageUtilOAM.SEAT_TILE_HEIGHT * 8 * 2, objPalette, 0);

            uint bgPointer = U.u32(frameData, frame + 16);

            if (!U.isSafetyPointer(bgPointer))
            {
                return(ImageUtil.BlankDummy());
            }
            byte[] bg_UZ = LZ77.decompress(Program.ROM.Data, U.toOffset(bgPointer));

            uint bgTSAPointer = U.u32(frameData, frame + 28);

            if (!U.isSafetyPointer(bgTSAPointer))
            {
                return(ImageUtil.BlankDummy());
            }
            byte[] bgTSA_UZ = LZ77.decompress(Program.ROM.Data, U.toOffset(bgTSAPointer));

            int width  = 256 - 8 - 8;
            int height = ImageUtil.CalcHeightbyTSA(width, bgTSA_UZ.Length);

            if (height < 160)
            {
                height = 160;
            }
            Bitmap bg = ImageUtil.ByteToImage16Tile(width, height, bg_UZ, 0, bgPalette, 0, bgTSA_UZ, 0);

            ImageUtil.AppendPalette(retImage, bg, 1);
            if (bgExpands)
            {
                Bitmap tempbg = ImageUtil.Blank(width, height, bg);
                ImageUtil.Scale(tempbg, 0, 0, width, 160 - 32, bg, 0, 0, width, 64);
                bg = tempbg;
            }
            ImageUtil.BitBlt(retImage, 0, 0, bg.Width, bg.Height, bg, 0, 0, 1);

            uint objImagePointer = U.u32(frameData, frame + 4);

            if (!U.isSafetyPointer(objImagePointer))
            {
                return(ImageUtil.BlankDummy());
            }
            byte[] obj_UZ = LZ77.decompress(Program.ROM.Data, U.toOffset(objImagePointer));
            if (obj_UZ.Length > 0)
            {
                width  = 256;
                height = ImageUtil.CalcHeight(width, obj_UZ.Length);
                if (height < 64)
                {
                    height = 64;
                }
                Bitmap obj = ImageUtil.ByteToImage16Tile(width, height, obj_UZ, 0, objPalette, 0);

                {
                    //利用するOAMデータの開始位置
                    //OAMは 12byte で 最初の1バイト目が 1になるまで続きます.
                    uint OAMBGAbsoStart      = U.u32(frameData, frame + 12);
                    ImageUtilOAM.DrawOAM oam = new ImageUtilOAM.DrawOAM();
                    oam.SetIsMagicOAM(true);
                    oam.Parse(Program.ROM.Data, objBGRightToLeftOAM + OAMBGAbsoStart);
                    Bitmap tempCanvas = ImageUtil.Blank((ImageUtilOAM.SEAT_TILE_WIDTH - 2) * 8, ImageUtilOAM.SEAT_TILE_HEIGHT * 8 * 2, objPalette, 0);
                    tempCanvas = oam.Draw(tempCanvas, obj);

                    ImageUtil.BitBlt(retImage, 0, 0, tempCanvas.Width, tempCanvas.Height, tempCanvas, 0, 0, 0, 0);
                    tempCanvas.Dispose();
                }
                {
                    //利用するOAMデータの開始位置
                    //OAMは 12byte で 最初の1バイト目が 1になるまで続きます.
                    uint OAMAbsoStart        = U.u32(frameData, frame + 8);
                    ImageUtilOAM.DrawOAM oam = new ImageUtilOAM.DrawOAM();
                    oam.SetIsMagicOAM(true);
                    oam.Parse(Program.ROM.Data, objRightToLeftOAM + OAMAbsoStart);
                    Bitmap tempCanvas = ImageUtil.Blank((ImageUtilOAM.SEAT_TILE_WIDTH - 2) * 8, ImageUtilOAM.SEAT_TILE_HEIGHT * 8 * 2, objPalette, 0);
                    tempCanvas = oam.Draw(tempCanvas, obj);

                    ImageUtil.BitBlt(retImage, 0, 0, tempCanvas.Width, tempCanvas.Height, tempCanvas, 0, 0, 0, 0);
                    tempCanvas.Dispose();
                }
            }
            return(retImage);
        }
コード例 #29
0
        static ImageUtilOAM.animedata ImportBGImageToData(string imagefilename
                                                          , string basedir
                                                          , Dictionary <string, ImageUtilOAM.animedata> animeDic
                                                          , List <ImageUtilOAM.image_data> imagesData
                                                          , out string errormessage
                                                          )
        {
            string key = "BG" + imagefilename;

            ImageUtilOAM.animedata magic_animedata;
            if (animeDic.ContainsKey(key))
            {
                errormessage    = "";
                magic_animedata = animeDic[key];
                return(magic_animedata);
            }

            string hash = ImageUtil.HashBitmap(imagefilename, basedir);

            magic_animedata = ImageUtilOAM.FindHash(hash, animeDic);
            if (magic_animedata != null)
            {
                errormessage = "";
                return(magic_animedata);
            }

            magic_animedata = new ImageUtilOAM.animedata();
            string bgfilename = ImageUtilMagicFEditor.GetFullPath(imagefilename, basedir);
            Bitmap loadbitmap = ImageUtil.OpenBitmap(bgfilename, null, out errormessage);

            if (loadbitmap == null)
            {
                return(null);
            }

//            int width = ImageUtilMagicFEditor.SRC_BG_SEAT_TILE_WIDTH * 8;
//            int height = ImageUtilMagicFEditor.SRC_BG_SEAT_TILE_HEIGHT * 8;
            int width  = 240;
            int height = 160;

            if (loadbitmap.Width < width || loadbitmap.Height < height)
            {
                if ((loadbitmap.Width >= 240 && loadbitmap.Width <= 264) &&
                    (loadbitmap.Height >= 64 && loadbitmap.Height < 160))
                {
                    height = 64;
                    //FEditor Magic
                    Log.Notify("これはFEditorの小さいBG形式です。");
                }
                else if ((loadbitmap.Width >= 240 && loadbitmap.Width <= 264) &&
                         loadbitmap.Height == 160)
                {//CSA Creator
                }
                else
                {
                    errormessage = R.Error("画像サイズが正しくありません。\r\n{4}\r\nWidth:{2} Height:{3} でなければなりません。\r\n\r\n選択された画像のサイズ Width:{0} Height:{1}", loadbitmap.Width, loadbitmap.Height, width, height, imagefilename);
                    loadbitmap.Dispose();
                    return(null);
                }
            }

            Bitmap savebitmap = ImageUtil.Copy(loadbitmap, 0, 0, width, height);

            byte[] image; //画像
            byte[] tsa;   //TSA
            string error_string = ImageUtil.ImageToBytePackedTSA(savebitmap, savebitmap.Width, savebitmap.Height, 0, out image, out tsa);

            if (error_string != "")
            {
                errormessage = error_string;
                loadbitmap.Dispose();
                return(null);
            }

            //画像の高さを記録. BGは、FEditor=64   Scale Creator=160 と、違う.
            magic_animedata.height = height;
            //ハッシュ値
            magic_animedata.imageHash = hash;

            //画像
            magic_animedata.image_pointer = (uint)imagesData.Count;
            ImageUtilOAM.image_data image_data = new ImageUtilOAM.image_data();
            image_data.data = image;
            image_data.data = LZ77.compress(image_data.data);
            imagesData.Add(image_data);

            //パレット
            magic_animedata.palette_pointer = (uint)imagesData.Count;
            ImageUtilOAM.image_data palette_data = new ImageUtilOAM.image_data();
            palette_data.data = ImageUtil.ImageToPalette(savebitmap);
            imagesData.Add(palette_data);

            //TSA
            magic_animedata.tsa_pointer = (uint)imagesData.Count;
            ImageUtilOAM.image_data tsa_data = new ImageUtilOAM.image_data();
            tsa_data.data = tsa;
            tsa_data.data = LZ77.compress(tsa_data.data);
            imagesData.Add(tsa_data);


            animeDic[key] = magic_animedata;
            errormessage  = "";
            loadbitmap.Dispose();
            return(magic_animedata);
        }
コード例 #30
0
        void SlotRenamed(object sender, EventArgs e)
        {
            var slot = sender as LayoutSlot;

            if (slot == null)
            {
                return;
            }

            // Back to original if not valid
            if (string.IsNullOrEmpty(slot.Name) ||
                LayoutSlot.IsValidName(slot.Name) != null)
            {
                slot.Name = slot.OldName;
            }
            else
            {
                m_renamedLayouts[slot.OldName] = slot.Name;

                if (m_screenshots.Contains(slot))
                {
                    m_screenshots.Remove(slot);
                }

                //
                // Try and remove existing screenshot on disk
                //
                string sourceFile =
                    Path.Combine(
                        m_screenshotDirectory.FullName + Path.DirectorySeparatorChar,
                        slot.OldName + WindowLayoutServiceCommandsBase.ScreenshotExtension);

                if (!File.Exists(sourceFile))
                {
                    return;
                }

                string destFile =
                    Path.Combine(
                        m_screenshotDirectory.FullName + Path.DirectorySeparatorChar,
                        slot.Name + WindowLayoutServiceCommandsBase.ScreenshotExtension);

                if (!sourceFile.Equals(destFile))
                {
                    slot.Image = null;

                    try
                    {
                        File.Copy(sourceFile, destFile);

                        if (File.Exists(destFile))
                        {
                            m_screenshots.Add(slot);
                        }

                        File.Delete(sourceFile);
                    }
                    catch (IOException)
                    {
                    }

                    slot.Image = ImageUtil.CreateFromFile(destFile);
                }
            }
        }