コード例 #1
0
 public CompositionModelProcessorFactory(ImageProcessor imageProcessor,ImageUtils imageUtils)
 {
     _imageProcessor = imageProcessor;
     _imageUtils = imageUtils;
 }
コード例 #2
0
 public Image GetPicture()
 {
     return(CarImage == null ? null : ImageUtils.ByteArrayToImage(CarImage));
 }
コード例 #3
0
ファイル: ShokoServer.cs プロジェクト: Pizz001/ShokoServer
        public bool StartUpServer()
        {
            DepProvider = BuildDi();

            try
            {
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(ServerSettings.Instance.Culture);

                // Check if any of the DLL are blocked, common issue with daily builds
                if (!CheckBlockedFiles())
                {
                    Utils.ShowErrorMessage(Resources.ErrorBlockedDll);
                    Environment.Exit(1);
                }

                // Migrate programdata folder from JMMServer to ShokoServer
                // this needs to run before UnhandledExceptionManager.AddHandler(), because that will probably lock the log file
                if (!MigrateProgramDataLocation())
                {
                    Utils.ShowErrorMessage(Resources.Migration_LoadError, Resources.ShokoServer);
                    Environment.Exit(1);
                }

                // First check if we have a settings.json in case migration had issues as otherwise might clear out existing old configurations
                string path = Path.Combine(ServerSettings.ApplicationPath, "settings.json");
                if (File.Exists(path))
                {
                    Thread t = new Thread(UninstallJMMServer)
                    {
                        IsBackground = true
                    };
                    t.Start();
                }

                //HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();

                try
                {
                    UnhandledExceptionManager.AddHandler();
                }
                catch (Exception e)
                {
                    logger.Log(NLog.LogLevel.Error, e);
                }

                try
                {
                    Mutex.OpenExisting(ServerSettings.DefaultInstance + "Mutex");
                    //since it hasn't thrown an exception, then we already have one copy of the app open.
                    return(false);
                    //MessageBox.Show(Shoko.Commons.Properties.Resources.Server_Running,
                    //    Shoko.Commons.Properties.Resources.ShokoServer, MessageBoxButton.OK, MessageBoxImage.Error);
                    //Environment.Exit(0);
                }
                catch (Exception Ex)
                {
                    //since we didn't find a mutex with that name, create one
                    Debug.WriteLine("Exception thrown:" + Ex.Message + " Creating a new mutex...");
                    var _ = new Mutex(true, ServerSettings.DefaultInstance + "Mutex");
                }

                ServerSettings.Instance.DebugSettingsToLog();
                RenameFileHelper.InitialiseRenamers();


                ServerState.Instance.DatabaseAvailable    = false;
                ServerState.Instance.ServerOnline         = false;
                ServerState.Instance.ServerStarting       = false;
                ServerState.Instance.StartupFailed        = false;
                ServerState.Instance.StartupFailedMessage = string.Empty;
                ServerState.Instance.BaseImagePath        = ImageUtils.GetBaseImagesPath();


                workerSetupDB.WorkerReportsProgress = true;
                workerSetupDB.ProgressChanged      += (sender, args) => WorkerSetupDB_ReportProgress();
                workerSetupDB.DoWork             += WorkerSetupDB_DoWork;
                workerSetupDB.RunWorkerCompleted += WorkerSetupDB_RunWorkerCompleted;

#if false
                #region LoggingConfig
                LogManager.Configuration = new NLog.Config.LoggingConfiguration();
                ColoredConsoleTarget conTarget = new ColoredConsoleTarget("console")
                {
                    Layout = "${date:format=HH\\:mm\\:ss}| --- ${message}"
                };
                FileTarget fileTarget = new FileTarget("file")
                {
                    Layout   = "[${shortdate} ${date:format=HH\\:mm\\:ss\\:fff}] ${level}|${stacktrace} ${message}",
                    FileName = "${basedir}/logs/${shortdate}.txt"
                };
                LogManager.Configuration.AddTarget(conTarget);
                LogManager.Configuration.AddTarget(fileTarget);
                LogManager.Configuration.AddRuleForAllLevels(conTarget);

                LogManager.Configuration.AddRule(ServerSettings.Instance.TraceLog ? LogLevel.Trace : LogLevel.Info, LogLevel.Fatal, fileTarget);
                #endregion
#endif

                ServerState.Instance.LoadSettings();

                InitCulture();
                Instance = this;


                SetupNetHosts();

                return(true);
            }
            catch (Exception e)
            {
                logger.Error(e);
                return(false);
            }
        }
コード例 #4
0
        static void Main(string[] args)
        {
            Workspace workspace = new Workspace("Financial Risk System", "A simple example C4 model based upon the financial risk system architecture kata, created using Structurizr for .NET");
            Model     model     = workspace.Model;

            // create the basic model
            SoftwareSystem financialRiskSystem = model.AddSoftwareSystem(Location.Internal, "Financial Risk System", "Calculates the bank's exposure to risk for product X");

            Person businessUser = model.AddPerson(Location.Internal, "Business User", "A regular business user");

            businessUser.Uses(financialRiskSystem, "Views reports using");

            Person configurationUser = model.AddPerson(Location.Internal, "Configuration User", "A regular business user who can also configure the parameters used in the risk calculations");

            configurationUser.Uses(financialRiskSystem, "Configures parameters using");

            SoftwareSystem tradeDataSystem = model.AddSoftwareSystem(Location.Internal, "Trade Data System", "The system of record for trades of type X");

            financialRiskSystem.Uses(tradeDataSystem, "Gets trade data from");

            SoftwareSystem referenceDataSystem = model.AddSoftwareSystem(Location.Internal, "Reference Data System", "Manages reference data for all counterparties the bank interacts with");

            financialRiskSystem.Uses(referenceDataSystem, "Gets counterparty data from");

            SoftwareSystem emailSystem = model.AddSoftwareSystem(Location.Internal, "E-mail system", "Microsoft Exchange");

            financialRiskSystem.Uses(emailSystem, "Sends a notification that a report is ready to");
            emailSystem.Delivers(businessUser, "Sends a notification that a report is ready to", "E-mail message", InteractionStyle.Asynchronous);

            SoftwareSystem centralMonitoringService = model.AddSoftwareSystem(Location.Internal, "Central Monitoring Service", "The bank-wide monitoring and alerting dashboard");

            financialRiskSystem.Uses(centralMonitoringService, "Sends critical failure alerts to", "SNMP", InteractionStyle.Asynchronous).AddTags(AlertTag);

            SoftwareSystem activeDirectory = model.AddSoftwareSystem(Location.Internal, "Active Directory", "Manages users and security roles across the bank");

            financialRiskSystem.Uses(activeDirectory, "Uses for authentication and authorisation");

            Container webApplication = financialRiskSystem.AddContainer("Web Application", "Allows users to view reports and modify risk calculation parameters", "ASP.NET MVC");

            businessUser.Uses(webApplication, "Views reports using");
            configurationUser.Uses(webApplication, "Modifies risk calculation parameters using");
            webApplication.Uses(activeDirectory, "Uses for authentication and authorisation");

            Container batchProcess = financialRiskSystem.AddContainer("Batch Process", "Calculates the risk", "Windows Service");

            batchProcess.Uses(emailSystem, "Sends a notification that a report is ready to");
            batchProcess.Uses(tradeDataSystem, "Gets trade data from");
            batchProcess.Uses(referenceDataSystem, "Gets counterparty data from");
            batchProcess.Uses(centralMonitoringService, "Sends critical failure alerts to", "SNMP", InteractionStyle.Asynchronous).AddTags(AlertTag);

            Container fileSystem = financialRiskSystem.AddContainer("File System", "Stores risk reports", "Network File Share");

            webApplication.Uses(fileSystem, "Consumes risk reports from");
            batchProcess.Uses(fileSystem, "Publishes risk reports to");

            Component scheduler             = batchProcess.AddComponent("Scheduler", "Starts the risk calculation process at 5pm New York time", "Quartz.NET");
            Component orchestrator          = batchProcess.AddComponent("Orchestrator", "Orchestrates the risk calculation process", "C#");
            Component tradeDataImporter     = batchProcess.AddComponent("Trade data importer", "Imports data from the Trade Data System", "C#");
            Component referenceDataImporter = batchProcess.AddComponent("Reference data importer", "Imports data from the Reference Data System", "C#");
            Component riskCalculator        = batchProcess.AddComponent("Risk calculator", "Calculates risk", "C#");
            Component reportGenerator       = batchProcess.AddComponent("Report generator", "Generates a Microsoft Excel compatible risk report", "C# and Microsoft.Office.Interop.Excel");
            Component reportPublisher       = batchProcess.AddComponent("Report distributor", "Publishes the report to the web application", "C#");
            Component emailComponent        = batchProcess.AddComponent("E-mail component", "Sends e-mails", "C#");
            Component reportChecker         = batchProcess.AddComponent("Report checker", "Checks that the report has been generated by 9am singapore time", "C#");
            Component alertComponent        = batchProcess.AddComponent("Alert component", "Sends SNMP alerts", "C# and #SNMP Library");

            scheduler.Uses(orchestrator, "Starts");
            scheduler.Uses(reportChecker, "Starts");
            orchestrator.Uses(tradeDataImporter, "Imports data using");
            tradeDataImporter.Uses(tradeDataSystem, "Imports data from");
            orchestrator.Uses(referenceDataImporter, "Imports data using");
            referenceDataImporter.Uses(referenceDataSystem, "Imports data from");
            orchestrator.Uses(riskCalculator, "Calculates the risk using");
            orchestrator.Uses(reportGenerator, "Generates the risk report using");
            orchestrator.Uses(reportPublisher, "Publishes the risk report using");
            reportPublisher.Uses(fileSystem, "Publishes the risk report to");
            orchestrator.Uses(emailComponent, "Sends e-mail using");
            emailComponent.Uses(emailSystem, "Sends a notification that a report is ready to");
            reportChecker.Uses(alertComponent, "Sends alerts using");
            alertComponent.Uses(centralMonitoringService, "Sends alerts using", "SNMP", InteractionStyle.Asynchronous).AddTags(AlertTag);

            // create some views
            ViewSet           viewSet     = workspace.Views;
            SystemContextView contextView = viewSet.CreateSystemContextView(financialRiskSystem, "Context", "");

            contextView.PaperSize = PaperSize.A4_Landscape;
            contextView.AddAllSoftwareSystems();
            contextView.AddAllPeople();

            ContainerView containerView = viewSet.CreateContainerView(financialRiskSystem, "Containers", "");

            contextView.PaperSize = PaperSize.A4_Landscape;
            containerView.AddAllElements();

            ComponentView componentViewForBatchProcess = viewSet.CreateComponentView(batchProcess, "Components", "");

            contextView.PaperSize = PaperSize.A3_Landscape;
            componentViewForBatchProcess.AddAllElements();
            componentViewForBatchProcess.Remove(configurationUser);
            componentViewForBatchProcess.Remove(webApplication);
            componentViewForBatchProcess.Remove(activeDirectory);

            // tag and style some elements
            Styles styles = viewSet.Configuration.Styles;

            financialRiskSystem.AddTags("Risk System");

            styles.Add(new ElementStyle(Tags.Element)
            {
                Color = "#ffffff", FontSize = 34
            });
            styles.Add(new ElementStyle("Risk System")
            {
                Background = "#8a458a"
            });
            styles.Add(new ElementStyle(Tags.SoftwareSystem)
            {
                Width = 650, Height = 400, Background = "#510d51", Shape = Shape.Box
            });
            styles.Add(new ElementStyle(Tags.Person)
            {
                Width = 550, Background = "#62256e", Shape = Shape.Person
            });
            styles.Add(new ElementStyle(Tags.Container)
            {
                Width = 650, Height = 400, Background = "#a46ba4", Shape = Shape.Box
            });
            styles.Add(new ElementStyle(Tags.Component)
            {
                Width = 550, Background = "#c9a1c9", Shape = Shape.Box
            });

            styles.Add(new RelationshipStyle(Tags.Relationship)
            {
                Thickness = 4, Dashed = false, FontSize = 32, Width = 400
            });
            styles.Add(new RelationshipStyle(Tags.Synchronous)
            {
                Dashed = false
            });
            styles.Add(new RelationshipStyle(Tags.Asynchronous)
            {
                Dashed = true
            });
            styles.Add(new RelationshipStyle(AlertTag)
            {
                Color = "#ff0000"
            });

            Documentation documentation     = workspace.Documentation;
            FileInfo      documentationRoot = new FileInfo(@"..\..\FinancialRiskSystem");

            documentation.Add(financialRiskSystem, SectionType.Context, DocumentationFormat.Markdown, new FileInfo(Path.Combine(documentationRoot.FullName, "context.md")));
            documentation.Add(financialRiskSystem, SectionType.FunctionalOverview, DocumentationFormat.Markdown, new FileInfo(Path.Combine(documentationRoot.FullName, "functional-overview.md")));
            documentation.Add(financialRiskSystem, SectionType.QualityAttributes, DocumentationFormat.Markdown, new FileInfo(Path.Combine(documentationRoot.FullName, "quality-attributes.md")));
            documentation.AddImages(documentationRoot);

            // add some example corporate branding
            Branding branding = viewSet.Configuration.Branding;

            branding.Font   = new Font("Trebuchet MS");
            branding.Color1 = new ColorPair("#510d51", "#ffffff");
            branding.Color2 = new ColorPair("#62256e", "#ffffff");
            branding.Color3 = new ColorPair("#a46ba4", "#ffffff");
            branding.Color4 = new ColorPair("#c9a1c9", "#ffffff");
            branding.Color5 = new ColorPair("#c9a1c9", "#ffffff");
            branding.Logo   = ImageUtils.GetImageAsDataUri(new FileInfo(Path.Combine(documentationRoot.FullName, "codingthearchitecture.png")));

            // and upload the model to structurizr.com
            StructurizrClient structurizrClient = new StructurizrClient("key", "secret");

            structurizrClient.PutWorkspace(9481, workspace);
        }
コード例 #5
0
 private void ChangeSelectedItem()
 {
     ImageUtils.UpdateItemImageOnPanelAsync(this.selectedItemDescription, this.ItemImageBox);
     UpdateItemDescriptionTextBox(this.ItemDescriptionTextBox, this.ItemNameLable, this.selectedItemDescription);
 }
コード例 #6
0
        internal void LoadParameters(bool loadFromFile, string visualElementsManifestPath,
                                     string mediumImageResizeMetadataPath, string smallImageResizeMetadataPath, string targetFolderPath)
        {
            if (loadFromFile)
            {
                var xmlDoc = XDocument.Load(visualElementsManifestPath);

                try
                {
                    ShortcutItemImage mediumImage = null;
                    ShortcutItemImage smallImage  = null;
                    if (File.Exists(mediumImageResizeMetadataPath))
                    {
                        mediumImage = ShortcutItemImage.Load(mediumImageResizeMetadataPath);
                    }
                    if (File.Exists(smallImageResizeMetadataPath))
                    {
                        smallImage = ShortcutItemImage.Load(smallImageResizeMetadataPath);
                    }

                    var parameters = from b in xmlDoc.Descendants("VisualElements")
                                     select new ShortcutItemState
                    {
                        TileIconifierMetadataCreatedWithUpgrade = b.Attribute("TileIconifierCreatedWithUpgrade")?.Value,
                        TileIconifierMetadataColorSelection     = b.Attribute("TileIconifierColorSelection")?.Value,
                        BackgroundColor             = b.Attribute("BackgroundColor")?.Value,
                        ForegroundText              = b.Attribute("ForegroundText")?.Value,
                        ShowNameOnSquare150X150Logo = b.Attribute("ShowNameOnSquare150x150Logo")?.Value == "on",
                        MediumImage =
                            mediumImage ?? new ShortcutItemImage(ShortcutConstantsAndEnums.MediumShortcutOutputSize)
                        {
                            Bytes =
                                ImageUtils.LoadFileToByteArray(targetFolderPath +
                                                               b.Attribute("Square150x150Logo")?.Value),
                            X = 0,
                            Y = 0
                        },
                        SmallImage =
                            smallImage ?? new ShortcutItemImage(ShortcutConstantsAndEnums.SmallShortcutOutputSize)
                        {
                            Bytes =
                                ImageUtils.LoadFileToByteArray(targetFolderPath +
                                                               b.Attribute("Square70x70Logo")?.Value),
                            X = 0,
                            Y = 0
                        }
                    };

                    OldState     = parameters.Single();
                    CurrentState = OldState.Clone();
                    if (Config.StartMenuUpgradeEnabled)
                    {
                        CurrentState.TileIconifierMetadataCreatedWithUpgrade = true.ToString();
                    }
                }
                catch
                {
                    ResetParameters();
                }
            }
            else
            {
                ResetParameters();
            }
        }
コード例 #7
0
 protected override Sprite GetItemSprite()
 {
     return(ImageUtils.LoadSpriteFromFile(Path.Combine(_assetFolder, $"{_iconFileName}.png")));
 }
コード例 #8
0
ファイル: Image.cs プロジェクト: professorlust/ShokoServer
        private string GetRandomImagePath(int type)
        {
            ImageEntityType imageType = (ImageEntityType)type;
            string          path;

            switch (imageType)
            {
            // 1
            case ImageEntityType.AniDB_Cover:
                SVR_AniDB_Anime anime = Repo.Instance.AniDB_Anime.GetAll()
                                        .Where(a => a?.PosterPath != null && !a.GetAllTags().Contains("18 restricted"))
                                        .GetRandomElement();
                if (anime == null)
                {
                    return(null);
                }
                path = anime.PosterPath;
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find AniDB_Cover image: {0}", anime.PosterPath);
                }
                break;

            // 2
            case ImageEntityType.AniDB_Character:
                var chr = Repo.Instance.AniDB_Anime.GetAll()
                          .Where(a => a != null && !a.GetAllTags().Contains("18 restricted"))
                          .SelectMany(a => a.GetAnimeCharacters()).Select(a => a.GetCharacter()).Where(a => a != null)
                          .GetRandomElement();
                if (chr == null)
                {
                    return(null);
                }
                path = chr.GetPosterPath();
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find AniDB_Character image: {0}", chr.GetPosterPath());
                }
                break;

            // 3 -- this will likely be slow
            case ImageEntityType.AniDB_Creator:
                var creator = Repo.Instance.AniDB_Anime.GetAll()
                              .Where(a => a != null && !a.GetAllTags().Contains("18 restricted"))
                              .SelectMany(a => a.GetAnimeCharacters())
                              .SelectMany(a => Repo.Instance.AniDB_Character_Seiyuu.GetByCharID(a.CharID))
                              .Select(a => Repo.Instance.AniDB_Seiyuu.GetByID(a.SeiyuuID)).Where(a => a != null)
                              .GetRandomElement();
                if (creator == null)
                {
                    return(null);
                }
                path = creator.GetPosterPath();
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find AniDB_Creator image: {0}", creator.GetPosterPath());
                }
                break;

            // 4
            case ImageEntityType.TvDB_Banner:
                // TvDB doesn't allow H content, so we get to skip the check!
                TvDB_ImageWideBanner wideBanner = Repo.Instance.TvDB_ImageWideBanner.GetAll().GetRandomElement();
                if (wideBanner == null)
                {
                    return(null);
                }
                path = wideBanner.GetFullImagePath();
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find TvDB_Banner image: {0}", wideBanner.GetFullImagePath());
                }
                break;

            // 5
            case ImageEntityType.TvDB_Cover:
                // TvDB doesn't allow H content, so we get to skip the check!
                TvDB_ImagePoster poster = Repo.Instance.TvDB_ImagePoster.GetAll().GetRandomElement();
                if (poster == null)
                {
                    return(null);
                }
                path = poster.GetFullImagePath();
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find TvDB_Cover image: {0}", poster.GetFullImagePath());
                }
                break;

            // 6
            case ImageEntityType.TvDB_Episode:
                // TvDB doesn't allow H content, so we get to skip the check!
                TvDB_Episode ep = Repo.Instance.TvDB_Episode.GetAll().GetRandomElement();
                if (ep == null)
                {
                    return(null);
                }
                path = ep.GetFullImagePath();
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find TvDB_Episode image: {0}", ep.GetFullImagePath());
                }
                break;

            // 7
            case ImageEntityType.TvDB_FanArt:
                // TvDB doesn't allow H content, so we get to skip the check!
                TvDB_ImageFanart fanart = Repo.Instance.TvDB_ImageFanart.GetAll().GetRandomElement();
                if (fanart == null)
                {
                    return(null);
                }
                path = fanart.GetFullImagePath();
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                path = string.Empty;
                logger.Trace("Could not find TvDB_FanArt image: {0}", fanart.GetFullImagePath());
                break;

            // 8
            case ImageEntityType.MovieDB_FanArt:
                MovieDB_Fanart mFanart = Repo.Instance.MovieDB_Fanart.GetAll().GetRandomElement();
                if (mFanart == null)
                {
                    return(null);
                }
                path = mFanart.GetFullImagePath();
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find MovieDB_FanArt image: {0}", mFanart.GetFullImagePath());
                }
                break;

            // 9
            case ImageEntityType.MovieDB_Poster:
                MovieDB_Poster mPoster = Repo.Instance.MovieDB_Poster.GetAll().GetRandomElement();
                if (mPoster == null)
                {
                    return(null);
                }
                path = mPoster.GetFullImagePath();
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find MovieDB_Poster image: {0}", mPoster.GetFullImagePath());
                }
                break;

            case ImageEntityType.Character:
                var character = Repo.Instance.AniDB_Anime.GetAll()
                                .Where(a => a != null && !a.GetAllTags().Contains("18 restricted"))
                                .SelectMany(a => Repo.Instance.CrossRef_Anime_Staff.GetByAnimeID(a.AnimeID))
                                .Where(a => a.RoleType == (int)StaffRoleType.Seiyuu && a.RoleID.HasValue)
                                .Select(a => Repo.Instance.AnimeCharacter.GetByID(a.RoleID.Value)).GetRandomElement();
                if (character == null)
                {
                    return(null);
                }
                path = ImageUtils.GetBaseAniDBCharacterImagesPath() + Path.DirectorySeparatorChar + character.ImagePath;
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find Character image: {0}",
                                 ImageUtils.GetBaseAniDBCharacterImagesPath() + Path.DirectorySeparatorChar + character.ImagePath);
                }
                break;

            case ImageEntityType.Staff:
                var staff = Repo.Instance.AniDB_Anime.GetAll()
                            .Where(a => a != null && !a.GetAllTags().Contains("18 restricted"))
                            .SelectMany(a => Repo.Instance.CrossRef_Anime_Staff.GetByAnimeID(a.AnimeID))
                            .Select(a => Repo.Instance.AnimeStaff.GetByID(a.StaffID)).GetRandomElement();
                if (staff == null)
                {
                    return(null);
                }
                path = ImageUtils.GetBaseAniDBCreatorImagesPath() + Path.DirectorySeparatorChar + staff.ImagePath;
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find Staff image: {0}",
                                 ImageUtils.GetBaseAniDBCreatorImagesPath() + Path.DirectorySeparatorChar + staff.ImagePath);
                }
                break;

            default:
                path = string.Empty;
                break;
            }

            return(path);
        }
コード例 #9
0
        public static string CopiaImagemParaPasta(string caminhoImagem)
        {
            CreateDirectoryIfNotExists();
            // Se não é um caminho já está na pasta e o caminho já é o nome
            if (!caminhoImagem.Contains("\\"))
            {
                return(caminhoImagem);
            }

            var nome        = Ambiente.GetNomeArquivo(caminhoImagem);
            var novoCaminho = GetFullPath(nome);

            if (File.Exists(novoCaminho) && ImageUtils.ImageToByteArray(Image.FromFile(novoCaminho)).SequenceEqual(ImageUtils.ImageToByteArray(Image.FromFile(caminhoImagem))))
            {
                return(nome);
            }
            if (File.Exists(novoCaminho))
            {
                throw new Exception($"Já existe uma imagem com o nome {nome}! Por favor, a renomeie");
            }

            File.Copy(caminhoImagem, novoCaminho);
            return(nome);
        }
コード例 #10
0
        public void Decorate(ImageDecoratorContext context)
        {
            bool useOriginalImage = true;
            HtmlImageResizeDecoratorSettings settings = new HtmlImageResizeDecoratorSettings(context.Settings, context.ImgElement);

            if (context.InvocationSource == ImageDecoratorInvocationSource.InitialInsert ||
                context.InvocationSource == ImageDecoratorInvocationSource.Reset)
            {
                // WinLive 96840 - Copying and pasting images within shared canvas should persist source
                // decorator settings.
                // If ImageSizeName is set, then use that instead of default values
                if (settings.IsImageSizeNameSet && context.InvocationSource == ImageDecoratorInvocationSource.InitialInsert)
                {
                    // We must be copying settings from another instance of the same image
                    settings.SetImageSize(settings.ImageSize, settings.ImageSizeName);

                    // WinLive 96840 - Copying and pasting images within shared canvas should persist source
                    // decorator settings.
                    // Also if we are copying settings, then use the image instance from context instead of the
                    // original image. This ensures we use the cropped image (if any) to resize.
                    useOriginalImage = false;
                }
                else
                {
                    //calculate the default image size and rotation.  If the camera has indicated that the
                    //orientation of the photo is rotated (in the EXIF data), shift the rotation appropriately
                    //to insert the image correctly.

                    //Fix the image orientation based on the Exif data (added by digital cameras).
                    RotateFlipType fixedRotation = ImageUtils.GetFixupRotateFlipFromExifOrientation(context.Image);
                    settings.Rotation = fixedRotation;

                    settings.BaseSize = context.Image.Size;

                    //the default size is a scaled version of the image based on the default inline size constraints.
                    Size defaultBoundsSize;
                    if (settings.DefaultBoundsSizeName != ImageSizeName.Full)
                    {
                        defaultBoundsSize = settings.DefaultBoundsSize;
                    }
                    else //original size is default, so we aren't going to scale
                    {
                        defaultBoundsSize = context.Image.Size;
                    }
                    //calculate the base image size to scale from.  If the image is rotated 90 degrees, then switch the height/width
                    Size baseImageSize = context.Image.Size;
                    if (ImageUtils.IsRotated90(settings.Rotation))
                    {
                        baseImageSize = new Size(baseImageSize.Height, baseImageSize.Width);
                    }

                    //calculate and set the scaled default size using the defaultSizeBounds
                    //Note: if the image dimensions are smaller than the default, don't scale that dimension (bug 419446)
                    Size defaultSize =
                        ImageUtils.GetScaledImageSize(Math.Min(baseImageSize.Width, defaultBoundsSize.Width),
                                                      Math.Min(baseImageSize.Height, defaultBoundsSize.Height),
                                                      baseImageSize);
                    if (defaultSize.Width < defaultBoundsSize.Width && defaultSize.Height < defaultBoundsSize.Height)
                    {
                        settings.SetImageSize(defaultSize, ImageSizeName.Full);
                    }
                    else
                    {
                        settings.SetImageSize(defaultSize, settings.DefaultBoundsSizeName);
                    }
                }
            }
            else if (settings.BaseSizeChanged(context.Image))
            {
                Size newBaseSize = context.Image.Size;
                settings.SetImageSize(AdjustImageSizeForNewBaseSize(true, settings, newBaseSize, settings.Rotation, context), null);
                settings.BaseSize = newBaseSize;
            }

            //this decorator only applies to embedded images.
            if (context.ImageEmbedType == ImageEmbedType.Embedded && !ImageHelper2.IsAnimated(context.Image))
            {
                Bitmap imageToResize = null;

                // To make image insertion faster, we've already created an initial resized image on a background thread.
                if (context.InvocationSource == ImageDecoratorInvocationSource.InitialInsert && useOriginalImage)
                {
                    try
                    {
                        string imageSrc = context.ImgElement.getAttribute("src", 2) as string;
                        if (!string.IsNullOrEmpty(imageSrc) && (UrlHelper.IsFileUrl(imageSrc) || File.Exists(new Uri(imageSrc).ToString())))
                        {
                            Uri imageSrcUri = new Uri(imageSrc);
                            imageToResize = (Bitmap)Image.FromFile(imageSrcUri.LocalPath);
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.Write("Failed to load pre-created initial image: " + e);
                    }
                }

                if (imageToResize == null)
                {
                    imageToResize = context.Image;
                }

                // Figure the desired image size by taking the size of the img element
                // and calculate what borderless image size we'd need to start with
                // to end up at that size. This is different than simply subtracting
                // the existing border size, since borders can be relative to the
                // size of the base image.
                Size desiredImageSize = settings.BorderMargin.ReverseCalculateImageSize(settings.ImageSizeWithBorder);

                //resize the image and update the image used by the context.
                if (desiredImageSize != imageToResize.Size || settings.Rotation != RotateFlipType.RotateNoneFlipNone)
                {
                    context.Image = ResizeImage(imageToResize, desiredImageSize, settings.Rotation);
                }
                else
                {
                    context.Image = imageToResize;
                }

                if (settings.ImageSize != context.Image.Size)
                {
                    settings.SetImageSize(context.Image.Size, settings.ImageSizeName);
                }
            }
        }
コード例 #11
0
ファイル: Image.cs プロジェクト: professorlust/ShokoServer
        /// <summary>
        /// Internal function that return valid image file path on server that exist
        /// </summary>
        /// <param name="id">image id</param>
        /// <param name="type">image type</param>
        /// <param name="thumb">thumb mode</param>
        /// <returns>string</returns>
        internal string GetImagePath(int type, int id, bool thumb)
        {
            ImageEntityType imageType = (ImageEntityType)type;
            string          path;

            switch (imageType)
            {
            // 1
            case ImageEntityType.AniDB_Cover:
                SVR_AniDB_Anime anime = Repo.Instance.AniDB_Anime.GetByID(id);
                if (anime == null)
                {
                    return(null);
                }
                path = anime.PosterPath;
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find AniDB_Cover image: {0}", anime.PosterPath);
                }
                break;

            // 2
            case ImageEntityType.AniDB_Character:
                AniDB_Character chr = Repo.Instance.AniDB_Character.GetByID(id);
                if (chr == null)
                {
                    return(null);
                }
                path = chr.GetPosterPath();
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find AniDB_Character image: {0}", chr.GetPosterPath());
                }
                break;

            // 3
            case ImageEntityType.AniDB_Creator:
                AniDB_Seiyuu creator = Repo.Instance.AniDB_Seiyuu.GetByID(id);
                if (creator == null)
                {
                    return(null);
                }
                path = creator.GetPosterPath();
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find AniDB_Creator image: {0}", creator.GetPosterPath());
                }
                break;

            // 4
            case ImageEntityType.TvDB_Banner:
                TvDB_ImageWideBanner wideBanner = Repo.Instance.TvDB_ImageWideBanner.GetByID(id);
                if (wideBanner == null)
                {
                    return(null);
                }
                path = wideBanner.GetFullImagePath();
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find TvDB_Banner image: {0}", wideBanner.GetFullImagePath());
                }
                break;

            // 5
            case ImageEntityType.TvDB_Cover:
                TvDB_ImagePoster poster = Repo.Instance.TvDB_ImagePoster.GetByID(id);
                if (poster == null)
                {
                    return(null);
                }
                path = poster.GetFullImagePath();
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find TvDB_Cover image: {0}", poster.GetFullImagePath());
                }
                break;

            // 6
            case ImageEntityType.TvDB_Episode:
                TvDB_Episode ep = Repo.Instance.TvDB_Episode.GetByID(id);
                if (ep == null)
                {
                    return(null);
                }
                path = ep.GetFullImagePath();
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find TvDB_Episode image: {0}", ep.GetFullImagePath());
                }
                break;

            // 7
            case ImageEntityType.TvDB_FanArt:
                TvDB_ImageFanart fanart = Repo.Instance.TvDB_ImageFanart.GetByID(id);
                if (fanart == null)
                {
                    return(null);
                }
                if (thumb)
                {
                    //ratio
                    path = fanart.GetFullThumbnailPath();
                    if (System.IO.File.Exists(path))
                    {
                        return(path);
                    }
                    path = string.Empty;
                    logger.Trace("Could not find TvDB_FanArt image: {0}", fanart.GetFullThumbnailPath());
                }
                else
                {
                    path = fanart.GetFullImagePath();
                    if (System.IO.File.Exists(path))
                    {
                        return(path);
                    }
                    path = string.Empty;
                    logger.Trace("Could not find TvDB_FanArt image: {0}", fanart.GetFullImagePath());
                }
                break;

            // 8
            case ImageEntityType.MovieDB_FanArt:
                MovieDB_Fanart mFanart = Repo.Instance.MovieDB_Fanart.GetByID(id);
                if (mFanart == null)
                {
                    return(null);
                }
                mFanart = Repo.Instance.MovieDB_Fanart.GetByOnlineID(mFanart.URL);
                if (mFanart == null)
                {
                    return(null);
                }
                path = mFanart.GetFullImagePath();
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find MovieDB_FanArt image: {0}", mFanart.GetFullImagePath());
                }
                break;

            // 9
            case ImageEntityType.MovieDB_Poster:
                MovieDB_Poster mPoster = Repo.Instance.MovieDB_Poster.GetByID(id);
                if (mPoster == null)
                {
                    return(null);
                }
                mPoster = Repo.Instance.MovieDB_Poster.GetByOnlineID(mPoster.URL);
                if (mPoster == null)
                {
                    return(null);
                }
                path = mPoster.GetFullImagePath();
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find MovieDB_Poster image: {0}", mPoster.GetFullImagePath());
                }
                break;

            case ImageEntityType.Character:
                AnimeCharacter character = Repo.Instance.AnimeCharacter.GetByID(id);
                if (character == null)
                {
                    return(null);
                }
                path = ImageUtils.GetBaseAniDBCharacterImagesPath() + Path.DirectorySeparatorChar + character.ImagePath;
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find Character image: {0}",
                                 ImageUtils.GetBaseAniDBCharacterImagesPath() + Path.DirectorySeparatorChar + character.ImagePath);
                }
                break;

            case ImageEntityType.Staff:
                var staff = Repo.Instance.AnimeStaff.GetByID(id);
                if (staff == null)
                {
                    return(null);
                }
                path = ImageUtils.GetBaseAniDBCreatorImagesPath() + Path.DirectorySeparatorChar + staff.ImagePath;
                if (System.IO.File.Exists(path))
                {
                    return(path);
                }
                else
                {
                    path = string.Empty;
                    logger.Trace("Could not find Staff image: {0}",
                                 ImageUtils.GetBaseAniDBCreatorImagesPath() + Path.DirectorySeparatorChar + staff.ImagePath);
                }
                break;

            default:
                path = string.Empty;
                break;
            }

            return(path);
        }
コード例 #12
0
        internal static Size AdjustImageSizeForNewBaseSize(bool allowEnlargement, IResizeDecoratorSettings s, Size newBaseSize, RotateFlipType rotation, ImageDecoratorContext context)
        {
            Size rotatedBaseSize = ImageUtils.IsRotated90(rotation)
                ? new Size(newBaseSize.Height, newBaseSize.Width)
                : newBaseSize;

            if (s.ImageSizeName != ImageSizeName.Custom)
            {
                // If a standard image size is being used, fit to that

                Size sizeBounds = ImageSizeHelper.GetSizeConstraints(s.ImageSizeName);
                if (!allowEnlargement)
                {
                    sizeBounds.Width  = Math.Min(rotatedBaseSize.Width, sizeBounds.Width);
                    sizeBounds.Height = Math.Min(rotatedBaseSize.Height, sizeBounds.Height);
                }
                return(ImageUtils.GetScaledImageSize(sizeBounds.Width, sizeBounds.Height, rotatedBaseSize));
            }
            else
            {
                // If custom size, but we know the base size, preserve
                // the aspect ratio "skew" (difference in x and y DPI)
                // and pixel area

                Size imageSize = s.ImageSize;
                // Need to get the image size to the non-rotated angle,
                // because s.BaseSize dimensions are always pre-rotation.
                // Although ImageSize has not been fully updated for this
                // decorator yet (that's what we're trying to do here),
                // the width/height gets flipped immediately when a
                // rotation is applied, so rotation is already taken
                // into account.
                if (ImageUtils.IsRotated90(rotation))
                {
                    imageSize = new Size(imageSize.Height, imageSize.Width);
                }

                // If the base size has not been set yet, we have to guess.
                // This basically means the image was inserted using an older
                // build of Writer that did not have the crop feature. Ideally
                // we would use the original image size, but this is expensive
                // to get from here. It just so happens that newBaseSize works
                // for now because the crop dialog defaults to the same aspect
                // ratio as the original image, but if that ever changes this
                // will break.
#if DEBUG
                if (s.BaseSize == null)
                {
                    using (Bitmap bitmap = (Bitmap)Bitmap.FromFile(context.SourceImageUri.LocalPath))
                    {
                        Size size = new Size(Math.Max(1, bitmap.Width / 2),
                                             Math.Max(1, bitmap.Height / 2));
                        Debug.Assert(size.Equals(newBaseSize) || bitmap.Size.Equals(newBaseSize), "Check base size assumptions. Can't use 's.BaseSize ?? newBaseSize', instead must calculate original image size (context.SourceImageUri.LocalPath).");
                    }
                }
#endif
                Size baseSize = s.BaseSize ?? newBaseSize;

                double xFactor = imageSize.Width / (double)baseSize.Width;
                double yFactor = imageSize.Height / (double)baseSize.Height;
                newBaseSize = new Size(
                    (int)Math.Round(xFactor * newBaseSize.Width),
                    (int)Math.Round(yFactor * newBaseSize.Height)
                    );

                // Need to re-apply the rotation if necessary.
                if (ImageUtils.IsRotated90(rotation))
                {
                    newBaseSize = new Size(newBaseSize.Height, newBaseSize.Width);
                }

                // At this point, newBaseSize has the right aspect ratio; we now
                // need to scale it so it uses about the same number of pixels
                // as it did before.

                double factor = (imageSize.Width * imageSize.Height) / (double)(newBaseSize.Width * newBaseSize.Height);
                factor             = Math.Sqrt(factor);
                newBaseSize.Width  = (int)Math.Round(newBaseSize.Width * factor);
                newBaseSize.Height = (int)Math.Round(newBaseSize.Height * factor);

                if (!allowEnlargement)
                {
                    if (newBaseSize.Width > rotatedBaseSize.Width || newBaseSize.Height > rotatedBaseSize.Height)
                    {
                        newBaseSize = ImageUtils.GetScaledImageSize(rotatedBaseSize.Width, rotatedBaseSize.Height, newBaseSize);
                    }
                }

                return(newBaseSize);
            }
        }
コード例 #13
0
        /// <summary>
        /// Handle pasting and handle images
        /// </summary>
        public void PasteOperation()
        {
            if (Clipboard.ContainsImage())
            {
                string imagePath = null;

                using (var bitMap = System.Windows.Forms.Clipboard.GetImage())
                {
                    imagePath = AddinManager.Current.RaiseOnSaveImage(bitMap);

                    if (!string.IsNullOrEmpty(imagePath))
                    {
                        SetSelection($"![]({imagePath})");
                        PreviewMarkdownCallback(); // force a preview refresh
                        return;
                    }

                    string initialFolder = null;
                    if (!string.IsNullOrEmpty(MarkdownDocument.Filename) && MarkdownDocument.Filename != "untitled")
                    {
                        initialFolder = Path.GetDirectoryName(MarkdownDocument.Filename);
                    }

                    var sd = new SaveFileDialog
                    {
                        Filter           = "Image files (*.png;*.jpg;*.gif;)|*.png;*.jpg;*.jpeg;*.gif|All Files (*.*)|*.*",
                        FilterIndex      = 1,
                        Title            = "Save Image from Clipboard as",
                        InitialDirectory = initialFolder,
                        CheckFileExists  = false,
                        OverwritePrompt  = true,
                        CheckPathExists  = true,
                        RestoreDirectory = true
                    };
                    var result = sd.ShowDialog();
                    if (result != null && result.Value)
                    {
                        imagePath = sd.FileName;
                        var ext = Path.GetExtension(imagePath)?.ToLower();

                        try
                        {
                            File.Delete(imagePath);

                            var format = ImageUtils.GetImageFormatFromFilename(imagePath);
                            bitMap.Save(imagePath, format);
                            bitMap.Dispose();


                            if (ext == ".png")
                            {
                                mmFileUtils.OptimizePngImage(sd.FileName, 5); // async
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Couldn't copy file to new location: \r\n" + ex.Message,
                                            mmApp.ApplicationName);
                            return;
                        }

                        string relPath = Path.GetDirectoryName(sd.FileName);
                        if (initialFolder != null)
                        {
                            try
                            {
                                relPath = FileUtils.GetRelativePath(sd.FileName, initialFolder);
                            }
                            catch (Exception ex)
                            {
                                mmApp.Log($"Failed to get relative path.\r\nFile: {sd.FileName}, Path: {imagePath}", ex);
                            }
                            imagePath = relPath;
                        }

                        if (imagePath.Contains(":\\"))
                        {
                            imagePath = "file:///" + imagePath;
                        }
                        else
                        {
                            imagePath = imagePath.Replace("\\", "/");
                        }

                        SetSelection($"![]({imagePath})");
                        PreviewMarkdownCallback(); // force a preview refresh
                    }
                }
            }
            else if (Clipboard.ContainsText())
            {
                // just paste as is at cursor or selection
                SetSelection(Clipboard.GetText());
            }
        }
コード例 #14
0
        private static void Init(UIComponent component, bool b)
        {
            component.eventVisibilityChanged -= new PropertyChangedEventHandler <bool>(Init);

            try
            {
                if (component.objectUserData is PrefabInfo prefab)
                {
                    string name = Asset.GetName(prefab);

                    if (AssetTagList.instance.assets.ContainsKey(name))
                    {
                        ImageUtils.FixThumbnails(prefab, component as UIButton);

                        Asset asset = AssetTagList.instance.assets[name];

                        component.eventVisibilityChanged += (c, p) =>
                        {
                            if (Settings.unlockAll)
                            {
                                c.isEnabled = true;
                            }
                            else
                            {
                                c.isEnabled = ToolsModifierControl.IsUnlocked(prefab.GetUnlockMilestone());
                            }
                        };

                        // Fixing focused texture
                        component.eventClicked += new MouseEventHandler(FixFocusedTexture);

                        // Adding custom tag icon
                        UISprite tagSprite = component.AddUIComponent <UISprite>();
                        tagSprite.size             = new Vector2(20, 16);
                        tagSprite.atlas            = FindIt.atlas;
                        tagSprite.spriteName       = "Tag";
                        tagSprite.opacity          = 0.5f;
                        tagSprite.tooltipBox       = UIView.GetAView().defaultTooltipBox;
                        tagSprite.relativePosition = new Vector3(component.width - tagSprite.width - 5, 5);
                        tagSprite.isVisible        = false;

                        if (CustomTagsLibrary.assetTags.ContainsKey(name))
                        {
                            tagSprite.tooltip = CustomTagsLibrary.assetTags[name];
                        }
                        else
                        {
                            tagSprite.tooltip = null;
                        }

                        tagSprite.eventMouseEnter += (c, p) =>
                        {
                            tagSprite.opacity = 1f;
                        };

                        tagSprite.eventMouseLeave += (c, p) =>
                        {
                            tagSprite.opacity = 0.5f;
                        };

                        tagSprite.eventClick += (c, p) =>
                        {
                            p.Use();

                            UITagsWindow.ShowAt(asset, tagSprite);
                        };

                        component.eventMouseEnter += (c, p) =>
                        {
                            tagSprite.isVisible = true;
                        };

                        component.eventMouseLeave += (c, p) =>
                        {
                            if (asset.tagsCustom.Count == 0)
                            {
                                tagSprite.isVisible = false;
                            }
                        };

                        // Adding steam icon
                        if (asset.steamID != 0)
                        {
                            UISprite steamSprite = component.AddUIComponent <UISprite>();
                            steamSprite.size             = new Vector2(26, 16);
                            steamSprite.atlas            = SamsamTS.UIUtils.GetAtlas("Ingame");
                            steamSprite.spriteName       = "SteamWorkshop";
                            steamSprite.opacity          = 0.05f;
                            steamSprite.tooltipBox       = UIView.GetAView().defaultTooltipBox;
                            steamSprite.relativePosition = new Vector3(component.width - steamSprite.width - 5, component.height - steamSprite.height - 5);
                            steamSprite.eventMouseLeave += (c, p) =>
                            {
                                steamSprite.tooltipBox.Hide();
                            };

                            if (!asset.author.IsNullOrWhiteSpace())
                            {
                                steamSprite.tooltip = "By " + asset.author + "\n" + Translations.Translate("FIF_UIS_WS");
                            }

                            if (PlatformService.IsOverlayEnabled())
                            {
                                steamSprite.eventMouseUp += (c, p) =>
                                {
                                    if (!p.used && p.buttons == UIMouseButton.Right)
                                    {
                                        PublishedFileId publishedFileId = new PublishedFileId(asset.steamID);

                                        if (publishedFileId != PublishedFileId.invalid)
                                        {
                                            PlatformService.ActivateGameOverlayToWorkshopItem(publishedFileId);
                                            p.Use();
                                        }
                                    }
                                };
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debugging.LogException(e);
            }
        }
コード例 #15
0
ファイル: APEtag.cs プロジェクト: 1143910315/atldotnet
        private bool readFrames(BinaryReader source, TagInfo Tag, MetaDataIO.ReadTagParams readTagParams)
        {
            string frameName;
            string strValue;
            int    frameDataSize;
            long   valuePosition;
            int    frameFlags;

            source.BaseStream.Seek(Tag.FileSize - Tag.DataShift - Tag.Size, SeekOrigin.Begin);
            // Read all stored fields
            for (int iterator = 0; iterator < Tag.FrameCount; iterator++)
            {
                frameDataSize = source.ReadInt32();
                frameFlags    = source.ReadInt32();
                frameName     = StreamUtils.ReadNullTerminatedString(source, Utils.Latin1Encoding); // Slightly more permissive than what APE specs indicate in terms of allowed characters ("Space(0x20), Slash(0x2F), Digits(0x30...0x39), Letters(0x41...0x5A, 0x61...0x7A)")

                valuePosition = source.BaseStream.Position;

                if (frameDataSize < 0 || valuePosition + frameDataSize > Tag.FileSize)
                {
                    LogDelegator.GetLogDelegate()(Log.LV_ERROR, "Invalid value found while reading APEtag frame");
                    return(false);
                }

                if ((frameDataSize > 0) && (frameDataSize <= 500))
                {
                    /*
                     * According to spec : "Items are not zero-terminated like in C / C++.
                     * If there's a zero character, multiple items are stored under the key and the items are separated by zero characters."
                     *
                     * => Values have to be splitted
                     */
                    strValue = Utils.StripEndingZeroChars(Encoding.UTF8.GetString(source.ReadBytes(frameDataSize)));
                    strValue = strValue.Replace('\0', Settings.InternalValueSeparator).Trim();
                    SetMetaField(frameName.Trim().ToUpper(), strValue, readTagParams.ReadAllMetaFrames);
                }
                else if (frameDataSize > 0) // Size > 500 => Probably an embedded picture
                {
                    int picturePosition;
                    PictureInfo.PIC_TYPE picType = decodeAPEPictureType(frameName);

                    if (picType.Equals(PictureInfo.PIC_TYPE.Unsupported))
                    {
                        addPictureToken(getImplementedTagType(), frameName);
                        picturePosition = takePicturePosition(getImplementedTagType(), frameName);
                    }
                    else
                    {
                        addPictureToken(picType);
                        picturePosition = takePicturePosition(picType);
                    }

                    if (readTagParams.ReadPictures || readTagParams.PictureStreamHandler != null)
                    {
                        // Description seems to be a null-terminated ANSI string containing
                        //    * The frame name
                        //    * A byte (0x2E)
                        //    * The picture type (3 characters; similar to the 2nd part of the mime-type)
                        String      description = StreamUtils.ReadNullTerminatedString(source, Utils.Latin1Encoding);
                        ImageFormat imgFormat   = ImageUtils.GetImageFormatFromMimeType(description.Substring(description.Length - 3, 3));

                        PictureInfo picInfo = new PictureInfo(imgFormat, picType, getImplementedTagType(), frameName, picturePosition);
                        picInfo.Description = description;
                        picInfo.PictureData = new byte[frameDataSize - description.Length - 1];
                        source.BaseStream.Read(picInfo.PictureData, 0, frameDataSize - description.Length - 1);

                        tagData.Pictures.Add(picInfo);

                        if (readTagParams.PictureStreamHandler != null)
                        {
                            MemoryStream mem = new MemoryStream(picInfo.PictureData);
                            readTagParams.PictureStreamHandler(ref mem, picInfo.PicType, picInfo.NativeFormat, picInfo.TagType, picInfo.NativePicCode, picInfo.Position);
                            mem.Close();
                        }
                    }
                }
                source.BaseStream.Seek(valuePosition + frameDataSize, SeekOrigin.Begin);
            }

            return(true);
        }
コード例 #16
0
        /// <summary>
        /// Resizes an image from a bitmap either based on the width or height depending on mode.
        /// Note image will resize to the larger of the two sides
        /// </summary>
        /// <param name="bmp">Bitmap to resize</param>
        /// <param name="width">new width</param>
        /// <param name="height">new height</param>
        /// <returns>resized or original bitmap. Be sure to Dispose this bitmap</returns>
        public static Bitmap ResizeImageByMode(Bitmap bmp, int width, int height, ResizeModes resizeMode,
                                               InterpolationMode mode = InterpolationMode.HighQualityBicubic)
        {
#if NETFULL
            if (resizeMode == ResizeModes.Auto)
            {
                return(ImageUtils.ResizeImage(bmp, width, height, mode));
            }
#endif

            Bitmap bmpOut = null;

            try
            {
                decimal ratio;
                int     newWidth  = 0;
                int     newHeight = 0;

                // If the image is smaller than a thumbnail just return original size
                if (resizeMode == ResizeModes.DontKeepAspectRatio)
                {
                    newWidth  = width;
                    newHeight = height;
                }
                else if (bmp.Width < width && bmp.Height < height)
                {
                    newWidth  = bmp.Width;
                    newHeight = bmp.Height;
                }
                else
                {
                    if (resizeMode == ResizeModes.Auto)
                    {
                        if (width > height)
                        {
                            resizeMode = ResizeModes.ByWidth;
                        }
                        else
                        {
                            resizeMode = ResizeModes.ByHeight;
                        }
                    }

                    if (resizeMode == ResizeModes.ByWidth)
                    {
                        ratio    = (decimal)width / bmp.Width;
                        newWidth = width;
                        decimal lnTemp = bmp.Height * ratio;
                        newHeight = (int)lnTemp;
                    }
                    else
                    {
                        ratio     = (decimal)height / bmp.Height;
                        newHeight = height;
                        decimal lnTemp = bmp.Width * ratio;
                        newWidth = (int)lnTemp;
                    }
                }

                bmpOut = new Bitmap(newWidth, newHeight);
                bmpOut.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);

                using (Graphics g = Graphics.FromImage(bmpOut))
                {
                    g.InterpolationMode = mode;
                    g.SmoothingMode     = SmoothingMode.HighQuality;
                    g.PixelOffsetMode   = PixelOffsetMode.HighQuality;

                    g.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight);
                    g.DrawImage(bmp, 0, 0, newWidth, newHeight);
                }
            }
            catch
            {
                return(null);
            }

            return(bmpOut);
        }
コード例 #17
0
        public static void PatchSMLHelper()
        {
            if (!Singleton.GetPrefabs())
            {
                throw new FileNotFoundException($"Failed to retrieve the {Singleton.FriendlyName} prefab from the asset bundle");
            }
            Singleton.Patch();
            CraftDataHandler.SetCraftingTime(Singleton.TechType, 5);
            CraftTreeHandler.AddTabNode(CraftTree.Type.Constructor, "FCStudios", "FCStudios Mods", ImageUtils.LoadSpriteFromFile($"./QMods/AIMarineTurbine/Assets/Default.png"));

            //CraftTreePatcher.customTabs.Add(new CustomCraftTab("FCStudios", "FCStudios Mods", CraftScheme.Constructor, new Atlas.Sprite(ImageUtils.LoadTextureFromFile($"./QMods/AIMarineTurbine/Assets/Default.png"))));

            //CraftTreePatcher.customNodes.Add(new CustomCraftNode(Singleton.TechType, CraftScheme.Constructor, "FCStudios/WindSurferTurbine"));
        }
コード例 #18
0
        public int UpdateVideo(int VideoId, string Title, VideoStatus Status, string Object, string Description, int?CategoryId,
                               int ModifierId, HttpPostedFile Image, bool?AutoResize, bool DeleteOldImage, Languages?lan, HttpPostedFile VideoFile)
        {
            if (lan == null)
            {
                lan = Languages.Default;
            }

            var video = GetVideo(VideoId);

            video.Title        = Title;
            video.Status       = (byte)Status;
            video.Object       = Object;
            video.Description  = Description;
            video.CategoryId   = CategoryId;
            video.DateModified = DateTime.Now;
            video.UniqueName   = StringUtils.ToURL(Title);
            video.ModifierId   = ModifierId;
            video.Language     = (short)lan;

            MediaData.SubmitChanges();

            string path = WebContext.Server.MapPath(Path.Combine(WebContext.StartDir, Folders.VideosFolder));

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var oldImage = video.ThumbImage;

            bool generateThumb = Image != null && Image.ContentLength > 0;


            if (VideoFile != null && VideoFile.ContentLength > 0)
            {
                string videoName = Path.GetFileNameWithoutExtension(VideoFile.FileName);
                videoName = string.Format("{0}_{1}{2}", videoName, video.VideoId,
                                          Path.GetExtension(VideoFile.FileName));


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

                path = Path.Combine(path, videoName);

                VideoFile.SaveAs(path);


                //ShellFile so = ShellFile.FromFilePath(path);


                //decimal nanoseconds;
                //decimal.TryParse(so.Properties.System.Media.Duration.Value.ToString(), out nanoseconds);

                //decimal seconds = nanoseconds * (decimal)0.0000001;

                //video.VideoLength = seconds;

                if (!generateThumb)
                {
                    string imageName = Path.GetFileNameWithoutExtension(videoName) + ".Jpg";

                    string imagePath = Path.Combine(WebContext.Server.MapPath("~/" + Folders.VideoThumbsFolder),
                                                    imageName);

                    //so.Thumbnail.Bitmap.Save(imagePath);

                    VideoCategory cat = GetVideoCategory(CategoryId.Value);
                    if (cat.ThumbWidth > 0 && cat.ThumbHeight > 0)
                    {
                        ImageUtils.CropImage(imagePath, imagePath, (int)cat.ThumbWidth, (int)cat.ThumbHeight, ImageUtils.AnchorPosition.Default);
                    }
                    else
                    {
                        Config    cfg = new Config();
                        Dimension dim = new Dimension(cfg.GetKey(lw.CTE.parameters.VideoThumbSize));

                        if (dim.Width > 0 && dim.Height > 0)
                        {
                            ImageUtils.CropImage(imagePath, imagePath, (int)dim.Width, (int)dim.Height, ImageUtils.AnchorPosition.Default);
                        }
                    }
                    video.ThumbImage = imageName;
                }

                video.VideoFile = videoName;

                MediaData.SubmitChanges();
            }

            DeleteOldImage = DeleteOldImage || (Image != null && Image.ContentLength > 0);

            if (DeleteOldImage && !StringUtils.IsNullOrWhiteSpace(video.ThumbImage))
            {
                if (File.Exists(Path.Combine(path, oldImage)))
                {
                    File.Delete(Path.Combine(path, oldImage));
                }
                video.ThumbImage = "";
            }

            if (AutoResize != null && AutoResize.Value == true)
            {
                VideoCategory cat = GetVideoCategory(CategoryId.Value);
                if (cat.ThumbWidth > 0 && cat.ThumbHeight > 0)
                {
                    //ImageUtils.Resize(path, path, (int)cat.ThumbWidth, (int)cat.ThumbHeight);
                    ImageUtils.CropImage(path, path, (int)cat.ThumbWidth, (int)cat.ThumbHeight, ImageUtils.AnchorPosition.Default);
                }
                else
                {
                    Config    cfg = new Config();
                    Dimension dim = new Dimension(cfg.GetKey(lw.CTE.parameters.VideoThumbSize));

                    if (dim.Width > 0 && dim.Height > 0)
                    {
                        ImageUtils.CropImage(path, path, (int)dim.Width, (int)dim.Height, ImageUtils.AnchorPosition.Default);
                    }
                }
            }

            MediaData.SubmitChanges();
            return(VideoId);
        }
コード例 #19
0
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_DownloadImage: {0}", EntityID);
            string downloadURL = string.Empty;

            try
            {
                ImageDownloadRequest req = null;
                switch (EntityTypeEnum)
                {
                case ImageEntityType.TvDB_Episode:
                    TvDB_Episode ep = RepoFactory.TvDB_Episode.GetByID(EntityID);
                    if (string.IsNullOrEmpty(ep?.Filename))
                    {
                        logger.Warn($"TvDB Episode image failed to download: Can't get episode with ID: {EntityID}");
                        return;
                    }
                    req = new ImageDownloadRequest(EntityTypeEnum, ep, ForceDownload);
                    break;

                case ImageEntityType.TvDB_FanArt:
                    TvDB_ImageFanart fanart = RepoFactory.TvDB_ImageFanart.GetByID(EntityID);
                    if (string.IsNullOrEmpty(fanart?.BannerPath))
                    {
                        logger.Warn($"TvDB Fanart image failed to download: Can't find valid fanart with ID: {EntityID}");
                        RemoveImageRecord();
                        return;
                    }
                    req = new ImageDownloadRequest(EntityTypeEnum, fanart, ForceDownload);
                    break;

                case ImageEntityType.TvDB_Cover:
                    TvDB_ImagePoster poster = RepoFactory.TvDB_ImagePoster.GetByID(EntityID);
                    if (string.IsNullOrEmpty(poster?.BannerPath))
                    {
                        logger.Warn($"TvDB Poster image failed to download: Can't find valid poster with ID: {EntityID}");
                        RemoveImageRecord();
                        return;
                    }
                    req = new ImageDownloadRequest(EntityTypeEnum, poster, ForceDownload);
                    break;

                case ImageEntityType.TvDB_Banner:
                    TvDB_ImageWideBanner wideBanner = RepoFactory.TvDB_ImageWideBanner.GetByID(EntityID);
                    if (string.IsNullOrEmpty(wideBanner?.BannerPath))
                    {
                        logger.Warn($"TvDB Banner image failed to download: Can't find valid banner with ID: {EntityID}");
                        RemoveImageRecord();
                        return;
                    }
                    req = new ImageDownloadRequest(EntityTypeEnum, wideBanner, ForceDownload);
                    break;

                case ImageEntityType.MovieDB_Poster:
                    MovieDB_Poster moviePoster = RepoFactory.MovieDB_Poster.GetByID(EntityID);
                    if (string.IsNullOrEmpty(moviePoster?.URL))
                    {
                        logger.Warn($"MovieDB Poster image failed to download: Can't find valid poster with ID: {EntityID}");
                        RemoveImageRecord();
                        return;
                    }
                    req = new ImageDownloadRequest(EntityTypeEnum, moviePoster, ForceDownload);
                    break;

                case ImageEntityType.MovieDB_FanArt:
                    MovieDB_Fanart movieFanart = RepoFactory.MovieDB_Fanart.GetByID(EntityID);
                    if (string.IsNullOrEmpty(movieFanart?.URL))
                    {
                        logger.Warn($"MovieDB Fanart image failed to download: Can't find valid fanart with ID: {EntityID}");
                        return;
                    }
                    req = new ImageDownloadRequest(EntityTypeEnum, movieFanart, ForceDownload);
                    break;

                case ImageEntityType.AniDB_Cover:
                    SVR_AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(EntityID);
                    if (anime == null)
                    {
                        logger.Warn($"AniDB poster image failed to download: Can't find AniDB_Anime with ID: {EntityID}");
                        return;
                    }
                    AniDbImageRateLimiter.Instance.EnsureRate();
                    req = new ImageDownloadRequest(EntityTypeEnum, anime, ForceDownload);
                    break;

                case ImageEntityType.AniDB_Character:
                    AniDB_Character chr = RepoFactory.AniDB_Character.GetByCharID(EntityID);
                    if (chr == null)
                    {
                        logger.Warn($"AniDB Character image failed to download: Can't find AniDB Character with ID: {EntityID}");
                        return;
                    }
                    AniDbImageRateLimiter.Instance.EnsureRate();
                    req = new ImageDownloadRequest(EntityTypeEnum, chr, ForceDownload);
                    break;

                case ImageEntityType.AniDB_Creator:
                    AniDB_Seiyuu creator = RepoFactory.AniDB_Seiyuu.GetBySeiyuuID(EntityID);
                    if (creator == null)
                    {
                        logger.Warn($"AniDB Seiyuu image failed to download: Can't find Seiyuu with ID: {EntityID}");
                        return;
                    }
                    AniDbImageRateLimiter.Instance.EnsureRate();
                    req = new ImageDownloadRequest(EntityTypeEnum, creator, ForceDownload);
                    break;
                }

                if (req == null)
                {
                    logger.Warn($"Image failed to download: No implementation found for {EntityTypeEnum}");
                    return;
                }

                List <string> fileNames    = new List <string>();
                List <string> downloadURLs = new List <string>();

                string fileNameTemp    = GetFileName(req);
                string downloadURLTemp = GetFileURL(req);

                fileNames.Add(fileNameTemp);
                downloadURLs.Add(downloadURLTemp);

                for (int i = 0; i < fileNames.Count; i++)
                {
                    try
                    {
                        string fileName = fileNames[i];
                        downloadURL = downloadURLs[i];

                        bool downloadImage = true;
                        bool fileExists    = File.Exists(fileName);
                        bool imageValid    = fileExists && Misc.IsImageValid(fileName);

                        if (imageValid && !req.ForceDownload)
                        {
                            downloadImage = false;
                        }

                        if (!downloadImage)
                        {
                            continue;
                        }

                        string tempName = Path.Combine(ImageUtils.GetImagesTempFolder(), Path.GetFileName(fileName));

                        try
                        {
                            if (fileExists)
                            {
                                File.Delete(fileName);
                            }
                        }
                        catch (Exception ex)
                        {
                            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(ServerSettings.Instance.Culture);

                            logger.Warn(Resources.Command_DeleteError, fileName, ex.Message);
                            return;
                        }

                        // If this has any issues, it will throw an exception, so the catch below will handle it
                        RecursivelyRetryDownload(downloadURL, ref tempName, 0, 5);

                        // move the file to it's final location
                        // check that the final folder exists
                        string fullPath = Path.GetDirectoryName(fileName);
                        if (!Directory.Exists(fullPath))
                        {
                            Directory.CreateDirectory(fullPath);
                        }

                        File.Move(tempName, fileName);
                        logger.Info($"Image downloaded: {fileName} from {downloadURL}");
                    }
                    catch (WebException e)
                    {
                        logger.Warn("Error processing CommandRequest_DownloadImage: {0} ({1}) - {2}", downloadURL,
                                    EntityID,
                                    e.Message);
                        // Remove the record if the image doesn't exist or can't download
                        RemoveImageRecord();
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Warn("Error processing CommandRequest_DownloadImage: {0} ({1}) - {2}", downloadURL, EntityID,
                            ex.Message);
            }
        }
コード例 #20
0
        public int UpdateVideoWithImage(int VideoId, string Title, VideoStatus Status, string Object, string Description, int?CategoryId,
                                        int ModifierId, HttpPostedFile Image, bool?AutoResize, bool DeleteOldImage, Languages?lan, bool?Crop)
        {
            if (lan == null)
            {
                lan = Languages.Default;
            }

            var video = GetVideo(VideoId);

            video.Title        = Title;
            video.Status       = (byte)Status;
            video.Object       = Object;
            video.Description  = Description;
            video.CategoryId   = CategoryId;
            video.DateModified = DateTime.Now;
            video.UniqueName   = StringUtils.ToURL(Title);
            video.ModifierId   = ModifierId;
            video.Language     = (short)lan;

            MediaData.SubmitChanges();

            string path = WebContext.Server.MapPath(Path.Combine(WebContext.StartDir, Folders.VideoThumbsFolder));

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var oldImage = video.ThumbImage;

            DeleteOldImage = DeleteOldImage || (Image != null && Image.ContentLength > 0);

            if (DeleteOldImage && !StringUtils.IsNullOrWhiteSpace(video.ThumbImage))
            {
                if (File.Exists(Path.Combine(path, oldImage)))
                {
                    File.Delete(Path.Combine(path, oldImage));
                }
                video.ThumbImage = "";
            }

            if (Image != null && Image.ContentLength > 0)
            {
                string ImageName = Path.GetFileNameWithoutExtension(Image.FileName);
                ImageName = string.Format("{0}_{1}{2}", ImageName, video.VideoId,
                                          Path.GetExtension(Image.FileName));

                string _path = Path.Combine(path, ImageName);

                Image.SaveAs(_path);

                if (AutoResize != null && AutoResize.Value)
                {
                    VideoCategory cat = GetVideoCategory(CategoryId.Value);
                    if (cat.ThumbWidth > 0 && cat.ThumbHeight > 0)
                    {
                        if (Crop != null && Crop == true)
                        {
                            ImageUtils.CropImage(_path, _path, (int)cat.ThumbWidth, (int)cat.ThumbHeight, ImageUtils.AnchorPosition.Default);
                        }
                        else
                        {
                            ImageUtils.Resize(_path, _path, (int)cat.ThumbWidth, (int)cat.ThumbHeight);
                        }
                    }
                    else
                    {
                        Config    cfg = new Config();
                        Dimension dim = new Dimension(cfg.GetKey(lw.CTE.parameters.VideoThumbSize));

                        if (dim.Width > 0 && dim.Height > 0)
                        {
                            ImageUtils.CropImage(_path, _path, (int)dim.Width, (int)dim.Height, ImageUtils.AnchorPosition.Default);
                        }
                    }
                }

                video.ThumbImage = ImageName;
            }

            MediaData.SubmitChanges();
            return(VideoId);
        }
コード例 #21
0
        static async Task <int> Main(string[] args)
        {
            try
            {
                //
                // Parse options
                //

                Options = new AppOptions();

                Options.Parse(args);

                if (Options.ShowList)
                {
                    var devices = await FrameSource.GetSourceNamesAsync();

                    Log.WriteLine("Available cameras:");

                    foreach (var device in devices)
                    {
                        Log.WriteLine(device);
                    }
                }

                if (Options.Exit)
                {
                    return(-1);
                }

                if (!Options.UseImages)
                {
                    if (string.IsNullOrEmpty(Options.DeviceId))
                    {
                        throw new ApplicationException("Please use --device to specify which camera to use");
                    }
                }

                try
                {
                    string sv            = AnalyticsInfo.VersionInfo.DeviceFamilyVersion;
                    ulong  v             = ulong.Parse(sv);
                    ulong  v1            = (v & 0xFFFF000000000000L) >> 48;
                    ulong  v2            = (v & 0x0000FFFF00000000L) >> 32;
                    ulong  v3            = (v & 0x00000000FFFF0000L) >> 16;
                    ulong  v4            = (v & 0x000000000000FFFFL);
                    var    systemVersion = $"{v1}.{v2}.{v3}.{v4}";

                    _stats.CurrentVideoDeviceId = Options.DeviceId;
                    _stats.Platform             = $"{AnalyticsInfo.VersionInfo.DeviceFamily} - {System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE") ?? "Unknown"} - {systemVersion}";
                }
                catch (Exception)
                {
                }


                //
                // Init module client
                //

                if (Options.UseEdge)
                {
                    Log.WriteLine($"{AppOptions.AppName} module starting.");
                    await BlockTimer("Initializing Azure IoT Edge", async() => await InitEdge());
                }

                cts = new CancellationTokenSource();
                AssemblyLoadContext.Default.Unloading += (ctx) => cts.Cancel();
                Console.CancelKeyPress += (sender, cpe) => cts.Cancel();

                //
                // Load model
                //

                ScoringModel model = null;
                await BlockTimer($"Loading modelfile '{Options.ModelPath}' on the {(Options.UseGpu ? "GPU" : "CPU")}",
                                 async() =>
                {
                    var d    = Directory.GetCurrentDirectory();
                    var path = d + "\\" + Options.ModelPath;
                    StorageFile modelFile = await AsAsync(StorageFile.GetFileFromPathAsync(path));
                    model = await ScoringModel.CreateFromStreamAsync(modelFile, Options.UseGpu);
                });

                _stats.OnnxModelLoaded  = true;
                _stats.CurrentOnnxModel = Options.ModelPath;
                _stats.IsGpu            = Options.UseGpu;

                // WebServer Code


                HttpServer httpsv            = null;
                bool       HttpServerStarted = false;

                if (Options.RunForever)
                {
                    try
                    {
                        Log.WriteLine($"Start HTTP Server on port : " + Options.WebServerPort.ToString());
                        httpsv = new HttpServer(Options.WebServerPort);
                        httpsv.Start();
                        httpsv.OnGet += HttpsvOnOnGet;

                        HttpServerStarted = true;
                        Log.WriteLine($"- HTTP Server Started.");
                        Log.WriteLine($"");
                    }
                    catch (Exception e)
                    {
                        HttpServerStarted = false;
                        Log.WriteLine($"Exiting - Websockets Server Failed to start : " + e.Message);
                    }
                }


                //
                // Open camera
                //

                FrameSource     frameSource     = null;
                ImageFileSource imageFileSource = null;

                if (Options.UseImages)
                {
                    imageFileSource = new ImageFileSource();
                    imageFileSource.ScanUpdateQueue(Options.ImagePath);
                }
                else
                {
                    frameSource = new FrameSource();
                    await frameSource.StartAsync(Options.DeviceId, Options.UseGpu);
                }

                _stats.DeviceInitialized = true;
                SetLatestStatsPayload(JsonConvert.SerializeObject(_stats));

                //
                // Main loop
                //
                do
                {
                    ScoringOutput outcome   = null;
                    int           evalticks = 0;
                    Log.WriteLineVerbose("Getting frame...");

                    byte[]      data          = new byte[] { };
                    byte[]      annotatedData = new byte[] { };
                    MessageBody message       = null;

                    //
                    // Use Image File Source or fall back to Webcam Source if not specified
                    //
                    if (Options.UseImages)
                    {
                        var(fileName, sbmp) = await imageFileSource.GetNextImageAsync(Options.ImagePath, cts.Token);

                        using (var vf = VideoFrame.CreateWithSoftwareBitmap(sbmp))
                        {
                            ImageFeatureValue imageTensor = ImageFeatureValue.CreateFromVideoFrame(vf);


                            _stats.TotalFrames = _stats.TotalFrames + 1;

                            //
                            // Evaluate model
                            //

                            var ticksTaken = await BlockTimer($"Running the model",
                                                              async() =>
                            {
                                var input = new ScoringInput()
                                {
                                    data = imageTensor
                                };
                                outcome = await model.EvaluateAsync(input);
                            });

                            evalticks = ticksTaken;

                            message = ResultsToMessage(outcome);
                            message.metrics.evaltimeinms = evalticks;
                            _stats.TotalEvaluations      = _stats.TotalEvaluations + 1;
                            message.imgSrc = fileName;

                            string summaryText = "";

                            if (message.results.Length > 0)
                            {
                                summaryText = $"Matched : {message.results[0].label} - Confidence ={message.results[0].confidence.ToString("P")} - Eval Time {message.metrics.evaltimeinms} ms";
                            }
                            data = await ImageUtils.GetConvertedImage(sbmp);

                            annotatedData = await ImageUtils.AnnotateImage(sbmp, $"Current Image : {fileName ?? "-"}", summaryText);
                        }
                    }
                    else
                    {
                        using (var frame = await frameSource.GetFrameAsync())
                        {
                            var inputImage = frame.VideoMediaFrame.GetVideoFrame();
                            ImageFeatureValue imageTensor = ImageFeatureValue.CreateFromVideoFrame(inputImage);

                            _stats.TotalFrames = _stats.TotalFrames + 1;

                            //
                            // Evaluate model
                            //
                            var ticksTaken = await BlockTimer("Running the model",
                                                              async() =>
                            {
                                var input = new ScoringInput()
                                {
                                    data = imageTensor
                                };
                                outcome = await model.EvaluateAsync(input);
                            });

                            evalticks = ticksTaken;

                            message = ResultsToMessage(outcome);
                            message.metrics.evaltimeinms = evalticks;
                            _stats.TotalEvaluations      = _stats.TotalEvaluations + 1;

                            string summaryText = "";

                            if (message.results.Length > 0)
                            {
                                summaryText = $"Matched : {message.results[0].label} - Confidence ={message.results[0].confidence.ToString("P")} - Eval Time {message.metrics.evaltimeinms} ms";
                            }
                            data = await ImageUtils.GetConvertedImage(inputImage.SoftwareBitmap);

                            annotatedData = await ImageUtils.AnnotateImage(inputImage.SoftwareBitmap, $"Current Webcam : {Options.DeviceId ?? "-"}", summaryText);
                        }
                    }

                    if (message != null)
                    {
                        //
                        // Print results
                        //
                        message.metrics.evaltimeinms = evalticks;
                        var json = JsonConvert.SerializeObject(message,
                                                               new JsonSerializerSettings
                        {
                            //won't print null imgSrc if null
                            NullValueHandling = NullValueHandling.Ignore
                        });
                        Log.WriteLineRaw($"Inferenced: {json}");

                        if (Options.UseWebServer)
                        {
                            //
                            // Update the latest webserver payload snapshots with data from inferencing
                            //
                            UpdateWebServerPayloads(message, data, annotatedData);
                        }

                        //
                        // Send results to Edge
                        //


                        if (Options.UseEdge)
                        {
                            var eventMessage = new Message(Encoding.UTF8.GetBytes(json));
                            await ioTHubModuleClient.SendEventAsync("resultsOutput", eventMessage);

                            // Let's not totally spam Edge :)
                            await Task.Delay(500);
                        }
                        else if (Options.UseImages)
                        {
                            //slow it down a little..
                            await Task.Delay(TimeSpan.FromSeconds(5));
                        }
                    }
                }while (Options.RunForever && !cts.Token.IsCancellationRequested);

                if (frameSource != null)
                {
                    await frameSource.StopAsync();
                }


                if (HttpServerStarted)
                {
                    try
                    {
                        Log.WriteLine($"- Stopping Web Server.");
                        httpsv.OnGet -= HttpsvOnOnGet;
                        httpsv.Stop();
                        httpsv = null;
                        Log.WriteLine($"- Web Server Stopped.");
                    }
                    catch (Exception)
                    {
                    }
                }

                return(0);
            }
            catch (Exception ex)
            {
                Log.WriteLineException(ex);
                return(-1);
            }
        }
コード例 #22
0
        public int AddVideo(string Title, VideoStatus Status, string Object, string Description, int?CategoryId,
                            int?CreatorId, HttpPostedFile Image, bool?AutoResize, Languages?lan, HttpPostedFile VideoFile)
        {
            if (StringUtils.IsNullOrWhiteSpace(Title))
            {
                return(-1);
            }

            if (lan == null)
            {
                lan = Languages.Default;
            }

            Video video = new Video
            {
                Title        = Title,
                Status       = (byte)Status,
                Object       = Object,
                Description  = Description,
                CategoryId   = CategoryId,
                CreatorId    = CreatorId.Value,
                DateCreated  = DateTime.Now,
                DateModified = DateTime.Now,
                UniqueName   = StringUtils.ToURL(Title),
                ModifierId   = CreatorId,
                Language     = (short)lan
            };

            MediaData.Videos.InsertOnSubmit(video);
            MediaData.SubmitChanges();

            bool generateThumb = Image != null && Image.ContentLength > 0;


            if (VideoFile != null && VideoFile.ContentLength > 0)
            {
                string videoName = Path.GetFileNameWithoutExtension(VideoFile.FileName);
                videoName = string.Format("{0}_{1}{2}", videoName, video.VideoId,
                                          Path.GetExtension(VideoFile.FileName));


                string path = WebContext.Server.MapPath("~/" + Folders.VideosFolder);

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

                path = Path.Combine(path, videoName);

                VideoFile.SaveAs(path);


                //ShellFile so = ShellFile.FromFilePath(path);


                //decimal nanoseconds;
                //decimal.TryParse(so.Properties.System.Media.Duration.Value.ToString(), out nanoseconds);

                //decimal seconds = nanoseconds * (decimal)0.0000001;

                //video.VideoLength = seconds;

                //if (!generateThumb)
                //{
                //    string imageName = Path.GetFileNameWithoutExtension(videoName) + ".Jpg";

                //    string thumbImagePath = WebContext.Server.MapPath("~/" + Folders.VideoThumbsFolder);

                //    if (!Directory.Exists(thumbImagePath))
                //    {
                //        Directory.CreateDirectory(thumbImagePath);
                //    }

                //    string imagePath = Path.Combine(thumbImagePath, imageName);

                //    //so.Thumbnail.Bitmap.Save (imagePath);
                //    System.Drawing.Bitmap image;

                //    //force the actual thumbnail, not the icon

                //    //so.Thumbnail.FormatOption = ShellThumbnailFormatOptions.ThumbnailOnly;

                //    //image = so.Thumbnail.ExtraLargeBitmap;
                //    image.Save(imagePath);

                //    VideoCategory cat = GetVideoCategory(CategoryId.Value);
                //    if (cat.ThumbWidth > 0 && cat.ThumbHeight > 0)
                //    {
                //        ImageUtils.CropImage(imagePath, imagePath, (int)cat.ThumbWidth, (int)cat.ThumbHeight, ImageUtils.AnchorPosition.Default);
                //    }
                //    else
                //    {
                //        Config cfg = new Config();
                //        Dimension dim = new Dimension(cfg.GetKey(lw.CTE.parameters.VideoThumbSize));

                //        if (dim.Width > 0 && dim.Height > 0)
                //        {
                //            ImageUtils.CropImage(imagePath, imagePath, (int)dim.Width, (int)dim.Height, ImageUtils.AnchorPosition.Default);
                //        }
                //    }
                //    video.ThumbImage = imageName;
                //}

                video.VideoFile = videoName;

                MediaData.SubmitChanges();
            }


            if (Image != null && Image.ContentLength > 0)
            {
                string ImageName = Path.GetFileNameWithoutExtension(Image.FileName);
                ImageName = string.Format("{0}_{1}{2}", ImageName, video.VideoId,
                                          Path.GetExtension(Image.FileName));


                string path = WebContext.Server.MapPath("~/" + Folders.VideoThumbsFolder);

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

                path = Path.Combine(path, ImageName);

                Image.SaveAs(path);

                if (AutoResize != null && AutoResize.Value == true)
                {
                    VideoCategory cat = GetVideoCategory(CategoryId.Value);
                    if (cat.ThumbWidth > 0 && cat.ThumbHeight > 0)
                    {
                        //ImageUtils.Resize(path, path, (int)cat.ThumbWidth, (int)cat.ThumbHeight);
                        ImageUtils.CropImage(path, path, (int)cat.ThumbWidth, (int)cat.ThumbHeight, ImageUtils.AnchorPosition.Default);
                    }
                    else
                    {
                        Config    cfg = new Config();
                        Dimension dim = new Dimension(cfg.GetKey(lw.CTE.parameters.VideoThumbSize));

                        if (dim.Width > 0 && dim.Height > 0)
                        {
                            ImageUtils.CropImage(path, path, (int)dim.Width, (int)dim.Height, ImageUtils.AnchorPosition.Default);
                        }
                    }
                }

                video.ThumbImage = ImageName;

                MediaData.SubmitChanges();
            }
            return(video.VideoId);
        }
コード例 #23
0
        public void ProcessRequest(HttpContext context)
        {
            SetupCulture();

            var userId = -1;
            var width  = 55;
            var height = 55;
            var size   = "";

            try
            {
                if (!String.IsNullOrEmpty(context.Request.QueryString["userid"]))
                {
                    userId = Convert.ToInt32(context.Request.QueryString["userid"]);
                }

                if (!String.IsNullOrEmpty(context.Request.QueryString["w"]))
                {
                    width = Convert.ToInt32(context.Request.QueryString["w"]);
                }

                if (!String.IsNullOrEmpty(context.Request.QueryString["h"]))
                {
                    height = Convert.ToInt32(context.Request.QueryString["h"]);
                }
                if (!String.IsNullOrEmpty(context.Request.QueryString["size"]))
                {
                    size = context.Request.QueryString["size"];
                }
            }
            catch (Exception)
            {
                Exceptions.Exceptions.ProcessHttpException(context.Request);
            }

            if (height > 128)
            {
                height = 128;
            }
            if (width > 128)
            {
                width = 128;
            }


            CalculateSize(ref height, ref width, ref size);

            PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings();
            var            user     = UserController.Instance.GetUser(settings.PortalId, userId);

            IFileInfo photoFile   = null;
            var       photoLoaded = false;

            if (user != null && TryGetPhotoFile(user, out photoFile))
            {
                if (!IsImageExtension(photoFile.Extension))
                {
                    try
                    {
                        context.Response.End();
                    }
                    catch (ThreadAbortException)                    //if ThreadAbortException will shown, should catch it and do nothing.
                    {
                    }
                }

                var folder     = FolderManager.Instance.GetFolder(photoFile.FolderId);
                var extension  = "." + photoFile.Extension;
                var sizedPhoto = photoFile.FileName.Replace(extension, "_" + size + extension);
                if (!FileManager.Instance.FileExists(folder, sizedPhoto))
                {
                    lock (_locker)
                    {
                        if (!FileManager.Instance.FileExists(folder, sizedPhoto))
                        {
                            using (var fileContent = FileManager.Instance.GetFileContent(photoFile))
                                using (var sizedContent = ImageUtils.CreateImage(fileContent, height, width, extension))
                                {
                                    FileManager.Instance.AddFile(folder, sizedPhoto, sizedContent);
                                }
                        }
                    }
                }

                using (var content = FileManager.Instance.GetFileContent(FileManager.Instance.GetFile(folder, sizedPhoto)))
                {
                    switch (photoFile.Extension.ToLowerInvariant())
                    {
                    case "png":
                        context.Response.ContentType = "image/png";
                        break;

                    case "jpeg":
                    case "jpg":
                        context.Response.ContentType = "image/jpeg";
                        break;

                    case "gif":
                        context.Response.ContentType = "image/gif";
                        break;
                    }

                    using (var memoryStream = new MemoryStream())
                    {
                        content.CopyTo(memoryStream);
                        memoryStream.WriteTo(context.Response.OutputStream);
                    }

                    photoLoaded = true;
                }
            }

            if (!photoLoaded)
            {
                context.Response.ContentType = "image/gif";
                context.Response.WriteFile(context.Request.MapPath("~/images/no_avatar.gif"));
            }

            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetExpires(DateTime.Now.AddMinutes(1));
            context.Response.Cache.SetMaxAge(new TimeSpan(0, 1, 0));
            context.Response.AddHeader("Last-Modified", DateTime.Now.ToString("r"));
            context.ApplicationInstance.CompleteRequest();
        }
コード例 #24
0
        public GameEngine(Game def, string nickname, bool specator, string password = "", bool isLocal = false)
        {
            Spectator = specator;
            Program.GameMess.Clear();
            if (def.ScriptVersion.Equals(new Version(0, 0, 0, 0)))
            {
                Program.GameMess.Warning("This game doesn't have a Script Version specified. Please contact the game developer.\n\n\nYou can get in contact of the game developer here {0}", def.GameUrl);
                def.ScriptVersion = new Version(3, 1, 0, 0);
            }
            if (Versioned.ValidVersion(def.ScriptVersion) == false)
            {
                Program.GameMess.Warning(
                    "Can't find API v{0}. Loading the latest version.\n\nIf you have problems, get in contact of the developer of the game to get an update.\nYou can get in contact of them here {1}",
                    def.ScriptVersion, def.GameUrl);
                def.ScriptVersion = Versioned.LowestVersion;
            }
            else
            {
                var vmeta = Versioned.GetVersion(def.ScriptVersion);
                if (vmeta.DeleteDate <= DateTime.Now)
                {
                    Program.GameMess.Warning("This game requires an API version {0} which is no longer supported by OCTGN.\nYou can still play, however some aspects of the game may no longer function as expected, and it may be removed at any time.\nYou may want to contact the developer of this game and ask for an update.\n\nYou can find more information about this game at {1}."
                                             , def.ScriptVersion, def.GameUrl);
                }
            }
            //Program.ChatLog.ClearEvents();
            IsLocal       = isLocal;
            this.Password = password;
            _definition   = def;
            _table        = new Table(def.Table);
            Variables     = new Dictionary <string, int>();
            foreach (var varDef in def.Variables.Where(v => v.Global))
            {
                Variables.Add(varDef.Name, varDef.Default);
            }
            GlobalVariables = new Dictionary <string, string>();
            foreach (var varDef in def.GlobalVariables)
            {
                GlobalVariables.Add(varDef.Name, varDef.DefaultValue);
            }
            ScriptApi     = Versioned.Get <ScriptApi>(Definition.ScriptVersion);
            this.Nickname = nickname;
            while (String.IsNullOrWhiteSpace(this.Nickname))
            {
                this.Nickname = Prefs.Nickname;
                if (string.IsNullOrWhiteSpace(this.Nickname))
                {
                    this.Nickname = Skylabs.Lobby.Randomness.GrabRandomNounWord() + new Random().Next(30);
                }
                var retNick = this.Nickname;
                Program.Dispatcher.Invoke(new Action(() =>
                {
                    var i   = new InputDlg("Choose a nickname", "Choose a nickname", this.Nickname);
                    retNick = i.GetString();
                }));
                this.Nickname = retNick;
            }
            // Load all game markers
            foreach (DataNew.Entities.Marker m in Definition.GetAllMarkers())
            {
                if (!_markersById.ContainsKey(m.Id))
                {
                    _markersById.Add(m.Id, m);
                }
            }
            // Init fields
            CurrentUniqueId = 1;
            TurnNumber      = 0;
            TurnPlayer      = null;

            foreach (var size in Definition.CardSizes)
            {
                var front = ImageUtils.CreateFrozenBitmap(new Uri(size.Value.Front));
                var back  = ImageUtils.CreateFrozenBitmap(new Uri(size.Value.Back));
                _cardFrontsBacksCache.Add(size.Key, new Tuple <BitmapImage, BitmapImage>(front, back));
            }
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                // clear any existing players
                Play.Player.All.Clear();
                Player.Spectators.Clear();
                // Create the global player, if any
                if (Definition.GlobalPlayer != null)
                {
                    Play.Player.GlobalPlayer = new Play.Player(Definition);
                }
                // Create the local player
                Play.Player.LocalPlayer = new Play.Player(Definition, this.Nickname, 255, Crypto.ModExp(Prefs.PrivateKey), specator, true);
            }));
        }
コード例 #25
0
        public async Task <IActionResult> Register(ArtistRegistrationViewModel model)
        {
            ViewBag.SubsectionPages = _subsectionPages;
            ViewBag.ActiveSubpage   = _subsectionPages[1];

            if (!ModelState.IsValid)
            {
                return(View());
            }

            if (!_signInManager.IsSignedIn(User))
            {
                ModelState.AddModelError(string.Empty,
                                         "You have to be logged in to register an artist!");
                return(View());
            }

            Guid id = Guid.NewGuid();

            ImageFileManager ifmPfp = null, ifmBg = null;
            string           pfp, bg = null;

            try
            {
                // Load images
                ifmPfp = new ImageFileManager("wwwroot/img/profiles/pfps/", model.Pfp.OpenReadStream(),
                                              ImageUtils.ImgExtensionFromContentType(model.Pfp.ContentType));
                if (model.BackgroundImage != null)
                {
                    ifmBg = new ImageFileManager("wwwroot/img/profiles/bgs/",
                                                 model.BackgroundImage.OpenReadStream(),
                                                 ImageUtils.ImgExtensionFromContentType(model.BackgroundImage.ContentType));
                }

                // Save images
                pfp = await ifmPfp.SavePfp(id);

                pfp = pfp.Remove(0, 7);
                if (ifmBg != null)
                {
                    bg = await ifmBg.SaveBg(id);

                    bg = bg.Remove(0, 7);
                }
            }
            catch (InvalidArtDimensionsException e)
            {
                ModelState.AddModelError(string.Empty, "Invalid profile picture or background size! " +
                                         "Profile picture must be at least 400px by 400px and in 1:1 ratio " +
                                         "and background must be at least 1590px by 540px");
                return(View());
            }


            Artist artist = new Artist()
            {
                Id                 = id,
                ArtistName         = model.Name,
                RegisteredAt       = DateTime.Now,
                RegisteredBy       = await _userManager.GetUserAsync(User),
                ProfileViews       = 0,
                BackgroundImageUrl = bg,
                PfpUrl             = pfp,
                Country            = model.Country,
                FacebookProfileUrl = model.FacebookProfileUrl,
                TwitterProfileUrl  = model.TwitterProfileUrl,
                MailAddress        = model.MailAddress,
                Gender             = model.Gender,
            };

            await _db.Artists.AddAsync(artist);

            await _db.SaveChangesAsync();

            return(Redirect("/Artists/List"));
        }
コード例 #26
0
        public void UpdateTexture(Texture texture)
        {
            lock (FLockTexture)
            {
                if (!InputOK)
                {
                    return;
                }

                if (!FNeedsRefresh.ContainsKey(texture))
                {
                    FNeedsTexture = true;
                    return;
                }

                if (!FNeedsRefresh[texture])
                {
                    return;
                }

                if (FInput.ImageAttributesChanged)
                {
                    return;
                }

                bool          ex   = texture.Device is DeviceEx;
                Surface       srf  = texture.GetSurfaceLevel(0);
                DataRectangle rect = srf.LockRectangle(ex ? LockFlags.Discard : LockFlags.None);

                try
                {
                    Size imageSize = FNeedsConversion ? FBufferConverted.ImageAttributes.Size : FInput.ImageAttributes.Size;

                    if (srf.Description.Width != imageSize.Width || srf.Description.Height != imageSize.Height)
                    {
                        throw (new Exception("AsTextureInstance : srf dimensions don't match image dimensions"));
                    }

                    if (!FInput.Image.Allocated)
                    {
                        throw (new Exception("Image not allocated"));
                    }

                    if (FNeedsConversion)
                    {
                        FInput.GetImage(FBufferConverted);
                        FBufferConverted.Swap();
                        FBufferConverted.LockForReading();
                        try
                        {
                            if (!FBufferConverted.FrontImage.Allocated)
                            {
                                throw (new Exception());
                            }

                            rect.Data.WriteRange(FBufferConverted.FrontImage.Data, FBufferConverted.ImageAttributes.BytesPerFrame);
                            FNeedsRefresh[texture] = false;
                        }
                        catch (Exception e)
                        {
                            ImageUtils.Log(e);
                        }
                        finally
                        {
                            FBufferConverted.ReleaseForReading();
                        }
                    }
                    else
                    {
                        FInput.LockForReading();
                        try
                        {
                            rect.Data.WriteRange(FInput.Data, FInput.ImageAttributes.BytesPerFrame);
                            FNeedsRefresh[texture] = false;
                        }
                        catch (Exception e)
                        {
                            ImageUtils.Log(e);
                        }
                        finally
                        {
                            FInput.ReleaseForReading();
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.Log(e);
                }
                finally
                {
                    srf.UnlockRectangle();
                }
            }
        }
コード例 #27
0
ファイル: ScreenCaster.cs プロジェクト: tools-env/Remotely
        public async Task BeginScreenCasting(ScreenCastRequest screenCastRequest)
        {
            try
            {
                var    sendFramesLock = new SemaphoreSlim(1, 1);
                var    refreshTimer   = Stopwatch.StartNew();
                var    refreshNeeded  = false;
                var    currentQuality = _maxQuality;
                Bitmap currentFrame   = null;
                Bitmap previousFrame  = null;

                var viewer = ServiceContainer.Instance.GetRequiredService <Viewer>();
                viewer.Name = screenCastRequest.RequesterName;
                viewer.ViewerConnectionID = screenCastRequest.ViewerID;

                var screenBounds = viewer.Capturer.CurrentScreenBounds;

                Logger.Write($"Starting screen cast.  Requester: {viewer.Name}. " +
                             $"Viewer ID: {viewer.ViewerConnectionID}.  App Mode: {_conductor.Mode}");

                _conductor.Viewers.AddOrUpdate(viewer.ViewerConnectionID, viewer, (id, v) => viewer);

                if (_conductor.Mode == AppMode.Normal)
                {
                    _conductor.InvokeViewerAdded(viewer);
                }

                if (_conductor.Mode == AppMode.Unattended && screenCastRequest.NotifyUser)
                {
                    _sessionIndicator.Show();
                }

                await viewer.SendViewerConnected();

                await viewer.SendMachineName(Environment.MachineName);

                await viewer.SendScreenData(
                    viewer.Capturer.SelectedScreen,
                    viewer.Capturer.GetDisplayNames().ToArray());

                await viewer.SendScreenSize(screenBounds.Width, screenBounds.Height);

                await viewer.SendCursorChange(_cursorIconWatcher.GetCurrentCursor());

                await viewer.SendWindowsSessions();

                viewer.Capturer.ScreenChanged += async(sender, bounds) =>
                {
                    await viewer.SendScreenSize(bounds.Width, bounds.Height);
                };

                using (var initialFrame = viewer.Capturer.GetNextFrame())
                {
                    if (initialFrame != null)
                    {
                        await viewer.SendScreenCapture(new CaptureFrame()
                        {
                            EncodedImageBytes = ImageUtils.EncodeJpeg(initialFrame, _maxQuality),
                            Left   = screenBounds.Left,
                            Top    = screenBounds.Top,
                            Width  = screenBounds.Width,
                            Height = screenBounds.Height
                        });
                    }
                }


                if (EnvironmentHelper.IsWindows && screenCastRequest.UseWebRtc)
                {
                    await viewer.InitializeWebRtc();
                }

                // Wait until the first image is received.
                TaskHelper.DelayUntil(() => !viewer.PendingSentFrames.Any(), TimeSpan.MaxValue);

                while (!viewer.DisconnectRequested && viewer.IsConnected)
                {
                    try
                    {
                        if (viewer.IsUsingWebRtcVideo)
                        {
                            Thread.Sleep(100);
                            continue;
                        }
                        if (viewer.IsStalled)
                        {
                            // Viewer isn't responding.  Abort sending.
                            Logger.Write("Viewer stalled.  Ending send loop.");
                            break;
                        }

                        viewer.ThrottleIfNeeded();

                        if (currentFrame != null)
                        {
                            previousFrame?.Dispose();
                            previousFrame = (Bitmap)currentFrame.Clone();
                        }

                        currentFrame?.Dispose();
                        currentFrame = viewer.Capturer.GetNextFrame();

                        if (currentFrame is null)
                        {
                            continue;
                        }

                        if (refreshTimer.Elapsed.TotalSeconds > 10 ||
                            refreshNeeded && refreshTimer.Elapsed.TotalSeconds > 5)
                        {
                            viewer.Capturer.CaptureFullscreen = true;
                        }


                        var diffArea = ImageUtils.GetDiffArea(currentFrame, previousFrame, viewer.Capturer.CaptureFullscreen);

                        if (diffArea.IsEmpty)
                        {
                            continue;
                        }


                        if (viewer.Capturer.CaptureFullscreen)
                        {
                            refreshTimer.Restart();
                            refreshNeeded = false;
                        }

                        using var clone = currentFrame.Clone(diffArea, currentFrame.PixelFormat);

                        byte[] encodedImageBytes;
                        if (viewer.Capturer.CaptureFullscreen)
                        {
                            // Recalculate Bps.
                            viewer.AverageBytesPerSecond = 0;
                            encodedImageBytes            = ImageUtils.EncodeJpeg(clone, _maxQuality);
                        }
                        else
                        {
                            if (viewer.AverageBytesPerSecond > 0)
                            {
                                var expectedSize = clone.Height * clone.Width * 4 * .1;
                                var timeToSend   = expectedSize / viewer.AverageBytesPerSecond;
                                currentQuality = Math.Max(_minQuality, Math.Min(_maxQuality, (int)(.1 / timeToSend * _maxQuality)));
                                if (currentQuality < _maxQuality - 10)
                                {
                                    refreshNeeded = true;
                                    Debug.WriteLine($"Quality Reduced: {currentQuality}");
                                }
                            }
                            encodedImageBytes = ImageUtils.EncodeJpeg(clone, currentQuality);
                        }

                        viewer.Capturer.CaptureFullscreen = false;

                        await sendFramesLock.WaitAsync();

                        SendFrame(encodedImageBytes, diffArea, viewer, sendFramesLock);
                    }
                    catch (Exception ex)
                    {
                        Logger.Write(ex);
                    }
                }

                Logger.Write($"Ended screen cast.  " +
                             $"Requester: {viewer.Name}. " +
                             $"Viewer ID: {viewer.ViewerConnectionID}. " +
                             $"Viewer WS Connected: {viewer.IsConnected}.  " +
                             $"Viewer Stalled: {viewer.IsStalled}.  " +
                             $"Viewer Disconnected Requested: {viewer.DisconnectRequested}");

                _conductor.Viewers.TryRemove(viewer.ViewerConnectionID, out _);
                viewer.Dispose();
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
            }
            finally
            {
                // Close if no one is viewing.
                if (_conductor.Viewers.IsEmpty && _conductor.Mode == AppMode.Unattended)
                {
                    Logger.Write("No more viewers.  Calling shutdown service.");
                    await _shutdownService.Shutdown();
                }
            }
        }
コード例 #28
0
ファイル: Pixiv.cs プロジェクト: BAKAOLC/Ritsukage-Core
        static async void _GetIllustDetail(int id, Action <object[]> Reply, Action <object[]> SendMessage, bool slient = false)
        {
            try
            {
                var detail = await Illust.Get(id);

                if (detail == null)
                {
                    if (!slient)
                    {
                        Reply?.Invoke(new object[] { $"数据(pid:{id})获取失败,请稍后再试" });
                    }
                    return;
                }
                ArrayList msg = new();
                if (detail.IsUgoira)
                {
                    var ugoira = await detail.GetUgoira();

                    if (ugoira == null)
                    {
                        if (!slient)
                        {
                            Reply?.Invoke(new object[] { $"动图数据(pid:{id})获取失败" });
                        }
                    }
                    else
                    {
                        if (!slient)
                        {
                            Reply?.Invoke(new object[] { $"动图数据(pid:{id})获取成功,正在进行压缩..." });
                        }
                        var img = await ugoira.LimitGifScale(500, 500);

                        var file = await img.SaveGifToTempFile();

                        msg.Add(CQCode.CQImage(file));
                    }
                }
                else
                {
                    foreach (var img in detail.Images)
                    {
                        var cache = await DownloadManager.GetCache(img.Medium);

                        if (string.IsNullOrEmpty(cache))
                        {
                            var url = ImageUrls.ToPixivCat(img.Medium);
                            cache = await DownloadManager.GetCache(url);

                            if (string.IsNullOrEmpty(cache))
                            {
                                cache = await DownloadManager.Download(url);

                                if (string.IsNullOrEmpty(cache))
                                {
                                    cache = await DownloadManager.Download(img.Medium, detail.Url);

                                    if (string.IsNullOrEmpty(cache))
                                    {
                                        msg.Add("[图像缓存失败]");
                                        continue;
                                    }
                                }
                            }
                        }
                        ImageUtils.LimitImageScale(cache, 1500, 1500);
                        msg.Add(CQCode.CQImage(cache));
                    }
                }
                msg.Add(detail.ToString());
                SendMessage?.Invoke(msg.ToArray());
            }
            catch (Exception ex)
            {
                ConsoleLog.Debug("QQ Command - Pixiv", ex.GetFormatString(true));
                if (!slient)
                {
                    Reply?.Invoke(new object[] { $"处理作品(pid:{id})时发生异常错误,任务已终止" });
                }
            }
        }
コード例 #29
0
 protected override Sprite GetItemSprite()
 {
     return(ImageUtils.LoadSpriteFromFile($"{Main.modFolder}/Assets/SeaTruckDepthUpgrade_MK5.png"));
 }
コード例 #30
0
    /// <summary>
    /// Loads an image, checks if it is a PNG containing palette transparency, and if so, ensures it loads correctly.
    /// The theory can be found at http://www.libpng.org/pub/png/book/chapter08.html
    /// </summary>
    /// <param name="data">File data to load</param>
    /// <param name="paletteLength">Palette length in the original image. The palette format of .net is not adjustable in size, so it'll be the max size. This value can be used to adjust that.</param>
    /// <returns>The loaded image</returns>
    public static Bitmap LoadBitmap(Byte[] data, out Int32 paletteLength)
    {
        Bitmap loadedImage;

        if (data.Length > PNG_IDENTIFIER.Length && data.Take(PNG_IDENTIFIER.Length).SequenceEqual(PNG_IDENTIFIER))
        {
            Byte[] transparencyData = null;
            // Check if it contains a palette.
            // I'm sure it can be looked up in the header somehow, but meh.
            Int32 plteOffset = FindChunk(data, "PLTE");
            if (plteOffset != -1)
            {
                // Check if it contains a palette transparency chunk.
                Int32 trnsOffset = FindChunk(data, "tRNS");
                if (trnsOffset != -1)
                {
                    // Get chunk
                    Int32 trnsLength = GetChunkDataLength(data, trnsOffset);
                    transparencyData = new Byte[trnsLength];
                    Array.Copy(data, trnsOffset + 8, transparencyData, 0, trnsLength);
                    // filter out the palette alpha chunk, make new data array
                    Byte[] data2 = new Byte[data.Length - (trnsLength + 12)];
                    Array.Copy(data, 0, data2, 0, trnsOffset);
                    Int32 trnsEnd = trnsOffset + trnsLength + 12;
                    Array.Copy(data, trnsEnd, data2, trnsOffset, data.Length - trnsEnd);
                    data = data2;
                }
            }
            // Open a Stream and decode a PNG image
            using (MemoryStream imageStreamSource = new MemoryStream(data))
            {
                PngBitmapDecoder decoder      = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                BitmapSource     bitmapSource = decoder.Frames[0];
                Int32            width        = bitmapSource.PixelWidth;
                Int32            height       = bitmapSource.PixelHeight;
                Int32            stride       = ImageUtils.GetMinimumStride(width, bitmapSource.Format.BitsPerPixel);
                Byte[]           pixel        = new Byte[height * stride];
                bitmapSource.CopyPixels(pixel, stride, 0);
                WriteableBitmap myBitmap = new WriteableBitmap(width, height, 96, 96, bitmapSource.Format, bitmapSource.Palette);
                myBitmap.WritePixels(new Int32Rect(0, 0, width, height), pixel, stride, 0);
                // Convert WPF BitmapSource to GDI+ Bitmap
                Bitmap newBitmap = BitmapFromSource(myBitmap);
                System.Drawing.Color[] colpal = newBitmap.Palette.Entries;
                Boolean hasTransparency       = false;
                if (colpal.Length != 0 && transparencyData != null)
                {
                    for (Int32 i = 0; i < colpal.Length; i++)
                    {
                        if (i >= transparencyData.Length)
                        {
                            break;
                        }
                        System.Drawing.Color col = colpal[i];
                        colpal[i] = System.Drawing.Color.FromArgb(transparencyData[i], col.R, col.G, col.B);
                        if (!hasTransparency)
                        {
                            hasTransparency = transparencyData[i] == 0;
                        }
                    }
                }
                paletteLength = colpal.Length;
                if (!hasTransparency)
                {
                    return(newBitmap);
                }
                Byte[] imageData = ImageUtils.GetImageData(newBitmap, out stride);
                return(ImageUtils.BuildImage(imageData, newBitmap.Width, newBitmap.Height, stride, newBitmap.PixelFormat, colpal, System.Drawing.Color.Empty));
            }
        }
        using (MemoryStream ms = new MemoryStream(data))
        {
            // Prevents the image from breaking when the underlying stream is disposed.
            loadedImage = ImageUtils.CloneImage(new Bitmap(ms));
            ms.Close();
            paletteLength = loadedImage.Palette.Entries.Length;
        }
        return(loadedImage);
    }
コード例 #31
0
 public CompositionModelProcessor(Template pattern, ImageProcessor imageProcessor, ImageUtils imageUtils)
 {
     _pattern = pattern;
     _imageProcessor = imageProcessor;
     _imageUtils = imageUtils;
 }
コード例 #32
0
        private Task EnsurePosterList(string file, CancellationToken cancellationToken)
        {
            const string url = "https://raw.github.com/MediaBrowser/MediaBrowser.Resources/master/images/imagesbyname/gamegenreposters.txt";

            return(ImageUtils.EnsureList(url, file, _httpClient, _fileSystem, _listResourcePool, cancellationToken));
        }