コード例 #1
0
        //public ZImageButton() : base()
        //{

        //}

        protected override void OnPaint(ZPaintContext context)
        {
            base.OnPaint(context);
            Image image = null;

            if (this.isDown && this.PressImage != null)
            {
                image = this.PressImage;
            }
            else if (this.isHover && this.HoverImage != null)
            {
                image = this.HoverImage;
            }
            else if (this.NormalImage != null)
            {
                image = this.NormalImage;
            }
            else
            {
                return;
            }
            if (this.ImageEdgeInset != Padding.Empty)
            {
                image = ImageApi.ImageStretch(image, this.ImageEdgeInset, this.Size, context.ClipRectangle);
            }

            context.Graphics.DrawImage(image, context.ClipRectangle, new RectangleF(Point.Empty, image.Size), GraphicsUnit.Pixel);
        }
コード例 #2
0
        public static string[] GetImageApiSupportedFileExtensions()
        {
            ImageApi apiInstance = new ImageApi(FrameworkGlobals.PassportPdfApiUri);

            Exception e       = null;
            int       pauseMs = 5000;

            for (int i = 0; i < FrameworkGlobals.MAX_RETRYING_REQUESTS; i++)
            {
                try
                {
                    return(apiInstance.ImageGetSupportedFileExtensions().Value.ToArray());
                }
                catch (Exception ex)
                {
                    if (i < FrameworkGlobals.MAX_RETRYING_REQUESTS - 1)
                    {
                        Thread.Sleep(pauseMs); //marking a pause in case of cnx temporarily out and to avoid overhead.
                        pauseMs += 2000;
                    }
                    else
                    {//last iteration
                        e = ex;
                    }
                }
            }

            throw e;
        }
コード例 #3
0
        private ImageLoadResponse HandleLoadImage(ImageApi imageApiInstance, FileToProcess fileToProcess, int workerNumber)
        {
            FileStream inputFileStream = null;

            try
            {
                PassportPDFParametersUtilities.GetLoadImageMultipartParameters(fileToProcess.FileAbsolutePath, out inputFileStream, out string fileName);

                using (FileStream tmpFile = File.Create(Path.GetTempFileName(), 4096, FileOptions.DeleteOnClose))
                {
                    using (GZipStream dataStream = new GZipStream(tmpFile, CompressionLevel.Optimal, true))
                    {
                        inputFileStream.CopyTo(dataStream);
                        inputFileStream.Dispose();
                        inputFileStream = null;
                    }

                    tmpFile.Seek(0, SeekOrigin.Begin);

                    return(PassportPDFRequestsUtilities.SendLoadImageMultipartRequest(imageApiInstance, workerNumber, fileToProcess.FileAbsolutePath, fileName, tmpFile, ContentEncoding.Gzip, UploadOperationStartEventHandler));
                }
            }
            catch
            {
                if (inputFileStream != null)
                {
                    inputFileStream.Dispose();
                }
                throw;
            }
        }
コード例 #4
0
        private bool DownloadAndSaveDocument(PDFApi pdfApi, ImageApi imageApi, string fileId, int workerNumber, OperationsWorkflow.SaveOperationType saveOperationType, object saveOperationConfiguration, ProgressDelegate downloadOperationStartEventHandler, string inputFileAbsolutePath, out string downloadedDocumentFileName)
        {
            downloadedDocumentFileName = Path.GetTempFileName();

            using (FileStream outputFileStream = new FileStream(downloadedDocumentFileName, FileMode.Open))
            {
                try
                {
                    if (saveOperationType == OperationsWorkflow.SaveOperationType.SavePDF)
                    {
                        PassportPDFRequestsUtilities.DownloadPDF(pdfApi, new PdfSaveDocumentParameters(fileId), workerNumber, inputFileAbsolutePath, outputFileStream, downloadOperationStartEventHandler);
                    }
                    else if (saveOperationType == OperationsWorkflow.SaveOperationType.SaveImageAsPDFMRC)
                    {
                        PassportPDFRequestsUtilities.DownloadImageAsPDFMRC(imageApi, PassportPDFParametersUtilities.GetImageSaveAsPDFMRCParameters((ImageSaveAsPDFMRCActionConfiguration)saveOperationConfiguration, fileId),
                                                                           workerNumber, inputFileAbsolutePath, outputFileStream, downloadOperationStartEventHandler);
                    }

                    return(true);
                }
                catch (Exception ex)
                {
                    OnError(LogMessagesUtils.ReplaceMessageSequencesAndReferences(FrameworkGlobals.MessagesLocalizer.GetString("message_output_file_download_failure", FrameworkGlobals.ApplicationLanguage), inputFileAbsolutePath, additionalMessage: ex.Message));
                    return(false);
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// Attempt to get the latest person mask data that corresponds to the current frame
        /// for CPU access. Each pixel represents the confidence of the segmentation result:
        /// 255 represents high confidence that the pixel is part of a person, 0 represents
        /// high confidence that the pixel is not part of a person. If the data is available,
        /// it is copied into the output image buffer.
        /// </summary>
        /// <param name="occlusionManager">The AROcclusionManager instance.</param>
        /// <param name="outputBuffer">
        /// The output image buffer to be filled with raw image data.</param>
        /// <returns>If available, returns a Vector2Int which represents the size of the image.
        /// Otherwise, returns <c>Vector2Int.zero</c> and logs the failure reason, e.g.
        /// Segmentation Mode is Disabled, or current camera configuration s incompatible with
        /// <c><see cref="SegmentationMode"/></c>.<c>People</c>.</returns>
        public static Vector2Int TryAcquirePersonMaskRawData(
            this AROcclusionManager occlusionManager, ref byte[] outputBuffer)
        {
            if (ARCoreExtensions._instance.ARCoreExtensionsConfig.SegmentationMode !=
                SegmentationMode.People)
            {
                Debug.LogWarning(
                    "Person mask data is not available when SegmentationMode is not People.");
                return(Vector2Int.zero);
            }

            if (!TryGetLastFrameFromExtensions(out XRCameraFrame frame))
            {
                return(Vector2Int.zero);
            }

            Vector2Int imageSize     = Vector2Int.zero;
            IntPtr     sessionHandle = ARCoreExtensions._instance.currentARCoreSessionHandle;
            IntPtr     imageHandle   = FrameApi.AcquirePersonMaskImage(
                sessionHandle, frame.FrameHandle());

            if (imageHandle != IntPtr.Zero)
            {
                imageSize = ImageApi.UpdateRawData(
                    sessionHandle, imageHandle, ref outputBuffer);
                ImageApi.Release(imageHandle);
            }

            return(imageSize);
        }
コード例 #6
0
        public static void DownloadImageAsPDFMRC(ImageApi apiInstance, ImageSaveAsPDFMRCParameters saveImageParameters, int workerNumber, string inputFilePath, Stream destinationStream, OperationsManager.ProgressDelegate downloadOperationStartEventHandler)
        {
            Exception e       = null;
            int       pausems = 5000;

            for (int i = 0; i < FrameworkGlobals.MAX_RETRYING_REQUESTS; i++)
            {
                downloadOperationStartEventHandler.Invoke(workerNumber, inputFilePath, i);

                try
                {
                    apiInstance.ImageSaveAsPDFMRCFile(saveImageParameters, destinationStream);
                    return;
                }
                catch (Exception ex)
                {
                    if (i < FrameworkGlobals.MAX_RETRYING_REQUESTS - 1)
                    {
                        Thread.Sleep(pausems); //marking a pause in case of cnx temporarily out and to avoid overhead.
                        pausems += 2000;
                    }
                    else
                    {//last iteration
                        e = ex;
                    }
                }
            }

            throw e;
        }
コード例 #7
0
 public void Setup()
 {
     _selection       = new BookSelection();
     _apiObject       = new ImageApi(_selection);
     _creditsToFormat = new Dictionary <string, List <string> >();
     // Ensure only English UI strings (the default value).
     L10NSharp.LocalizationManager.SetUILanguage("en", false);
 }
コード例 #8
0
 private void Configure()
 {
     configuration = new Configuration
     {
         Username = "******",
         Password = "******",
     };
     imageApi = new ImageApi(configuration);
 }
コード例 #9
0
        public void CollectFormattedCredits_SingleCredit_Works()
        {
            _creditsToFormat.Add("my credit", new List <string> {
                "Front Cover", "2"
            });
            var results = ImageApi.CollectFormattedCredits(_creditsToFormat);

            Assert.That(results.Count(), Is.EqualTo(1));
            Assert.That(results.First(), Is.EqualTo("Images by my credit."), "Single credit should have non-page format.");
        }
コード例 #10
0
 public AdaptationsetsApi(IBitmovinApiClientFactory apiClientFactory)
 {
     _apiClient        = apiClientFactory.CreateClient <IAdaptationsetsApiClient>();
     Type              = new TypeApi(apiClientFactory);
     Audio             = new AudioApi(apiClientFactory);
     Video             = new VideoApi(apiClientFactory);
     Subtitle          = new SubtitleApi(apiClientFactory);
     Image             = new ImageApi(apiClientFactory);
     Representations   = new RepresentationsApi(apiClientFactory);
     Contentprotection = new ContentprotectionApi(apiClientFactory);
 }
コード例 #11
0
        public async Task GetFileNull()
        {
            var preprocessor = Substitute.For <IPreprocessor>();
            var store        = Substitute.For <IDataStore>();

            var api      = new ImageApi(preprocessor, store);
            var response = await api.Get(null);

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.PreconditionFailed, response.StatusCode);
        }
コード例 #12
0
        public async Task GetFileNull()
        {
            var preprocessor = Substitute.For<IPreprocessor>();
            var store = Substitute.For<IDataStore>();

            var api = new ImageApi(preprocessor, store);
            var response = await api.Get(null);

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.PreconditionFailed, response.StatusCode);
        }
コード例 #13
0
        private void Process(PDFApi pdfApi, ImageApi imageApi, int workerNumber, FileProductionRules fileProductionRules, OperationsWorkflow workflow, string destinationFolder, bool fileSizeReductionIsIntended)
        {
            while (PickFile(out FileToProcess fileToProcess))
            {
                if (_cancellationPending)
                {
                    break;
                }

                try
                {
                    long inputFileSize = FileUtils.GetFileSize(fileToProcess.FileAbsolutePath);
                    bool inputIsPDF    = Path.GetExtension(fileToProcess.FileAbsolutePath).ToUpper() == ".PDF";

                    if (!CheckInputFileSizeValidity(inputFileSize, fileToProcess.FileAbsolutePath))
                    {
                        continue;
                    }

                    WorkflowProcessingResult workFlowProcessingResult = ProcessWorkflow(pdfApi, imageApi, workflow, fileToProcess, workerNumber);

                    if (workFlowProcessingResult != null)
                    {
                        string outputFileAbsolutePath = destinationFolder + fileToProcess.FileRelativePath;

                        bool fileSuccesfullyProcessed = HandleOutputFileProduction(fileToProcess, workFlowProcessingResult.FileID, workerNumber, workflow.SaveOperation, workflow.SaveOperationConfiguration, pdfApi, imageApi, fileProductionRules, workFlowProcessingResult, fileSizeReductionIsIntended, inputIsPDF, inputFileSize, outputFileAbsolutePath);

                        TryCloseDocumentAsync(pdfApi, workFlowProcessingResult.FileID);

                        if (fileSuccesfullyProcessed)
                        {
                            OnFileSuccesfullyProcessed(new FileOperationsResult(fileToProcess.FileAbsolutePath, inputFileSize, FileUtils.GetFileSize(outputFileAbsolutePath), !inputIsPDF), workFlowProcessingResult.WarningMessages);
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
                catch (Exception exception)
                {
                    OnError(ErrorManager.GetMessageFromException(exception, fileToProcess.FileAbsolutePath));
                }

                if (_workPaused && !_cancellationPending)
                {
                    // If pause has been requested, wait for resume signal
                    WorkerPauseEventHandler.Invoke(workerNumber);
                    _waitHandle.WaitOne();
                }
            }

            OnWorkerWorkCompletion(workerNumber);
        }
コード例 #14
0
        public BookmarksPage(ServiceContainer container) : base(container)
        {
            InitializeComponent();

            bookmarkController = Container.Get <BookmarkController>("bookmark");
            profileApi         = Container.Get <ProfileApi>("api/profile");
            imageApi           = Container.Get <ImageApi>("api/image");

            Bookmarks  = new ObservableCollection <BookmarkViewModel>();
            _bookmarks = new Dictionary <string, BookmarkViewModel>();

            BindingContext = this;
        }
コード例 #15
0
        public ProfilePage(ServiceContainer container, string profileId) : base(container)
        {
            structureController = Container.Get <StructureController>("structure");
            bookmarkController  = Container.Get <BookmarkController>("bookmark");
            authController      = Container.Get <AuthController>("auth");
            profileApi          = Container.Get <ProfileApi>("api/profile");
            imageApi            = Container.Get <ImageApi>("api/image");
            adventureApi        = Container.Get <AdventureApi>("api/adventure");

            this.profileId = profileId;

            InitializeComponent();
        }
コード例 #16
0
        public HistoryPage(ServiceContainer container) : base(container)
        {
            InitializeComponent();

            historyController = Container.Get <HistoryController>("history");
            profileApi        = Container.Get <ProfileApi>("api/profile");
            imageApi          = Container.Get <ImageApi>("api/image");

            History  = new ObservableCollection <HistoryViewModel>();
            _history = new Dictionary <string, HistoryViewModel>();

            BindingContext = this;
        }
コード例 #17
0
        public void CollectFormattedCredits_MultipleCredits_Works()
        {
            _creditsToFormat.Add("my credit", new List <string> {
                "Front Cover", "2"
            });
            _creditsToFormat.Add("next credit", new List <string> {
                "2", "4", "Outside Back Cover"
            });
            var results = ImageApi.CollectFormattedCredits(_creditsToFormat);

            Assert.That(results.Count(), Is.EqualTo(2));
            Assert.That(results.First(), Is.EqualTo("Images on pages Front Cover, 2 by my credit."));
            Assert.That(results.Last(), Is.EqualTo("Images on pages 2, 4, Outside Back Cover by next credit."));
        }
コード例 #18
0
        public string AddPoster(ImageApi poster, int FilmId)
        {
            var posterData = ApiToData.ImageApiToData(poster, FilmId, true);
            var prevPoster = _dbContext.Image.FirstOrDefault(x => !x.IsDeleted && x.IsPoster && x.FilmId == FilmId);

            if (prevPoster != null)
            {
                prevPoster.IsDeleted = true;
            }

            _dbContext.Image.Add(posterData);
            _dbContext.SaveChanges();
            return(posterData.Name);
        }
コード例 #19
0
ファイル: ZContainer.cs プロジェクト: XiaoHeitu/ZPlayer
        protected override void OnPaint(PaintEventArgs e)
        {
            //base.OnPaint(e);
            if (this.BackgroundImage == null || this.BackgroundImageLayout != ImageLayout.Stretch || this.ClientRectangle == Rectangle.Empty)
            {
                base.OnPaint(e);
                return;
            }

            var image = ImageApi.ImageStretch(this.BackgroundImage, this.BackgroundEdgeInset, this.ClientSize, e.ClipRectangle);

            e.Graphics.DrawImage(image, e.ClipRectangle);
            this.PaintChildren(e);
        }
コード例 #20
0
        public ProfileEditPage(ServiceContainer container, string profileId) : base(container)
        {
            structureController = Container.Get <StructureController>("structure");
            profileApi          = Container.Get <IProfileApi>("api/profile");
            imageApi            = Container.Get <ImageApi>("api/image");

            InitializeComponent();

            viewModel      = new ProfileEditViewModel();
            BindingContext = viewModel;

            cts = new CancellationTokenSource();
            profileApi.Get(profileId).Subscribe(SetModel, cts.Token);
        }
コード例 #21
0
        private void InitializeApiInstances(out PDFApi pdfApiInstance, out ImageApi imageApiInstance, string apiKey)
        {
            pdfApiInstance = new PDFApi(apiKey)
            {
                BasePath = FrameworkGlobals.PassportPdfApiUri
            };

            imageApiInstance = new ImageApi(apiKey)
            {
                BasePath = FrameworkGlobals.PassportPdfApiUri
            };

            PassportPDF.Client.GlobalConfiguration.Timeout = FrameworkGlobals.PassportPDFConfiguration.SuggestedClientTimeout;
        }
コード例 #22
0
        public async Task PostMultiple()
        {
            var random = new Random();
            var count  = random.Next(2, 5);
            var files  = new List <string>(count);

            var preProcessor = Substitute.For <IPreprocessor>();

            var content = new MultipartContent();

            var dir   = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
            var f     = dir.Substring(6, dir.Length - 6) + @"\icon.png";
            var bytes = File.ReadAllBytes(f);

            for (var i = 0; i < count; i++)
            {
                var fileName    = Guid.NewGuid().ToString();
                var fileContent = new ByteArrayContent(bytes);
                fileContent.Headers.ContentType        = new MediaTypeHeaderValue("image/jpeg");
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = fileName
                };
                preProcessor.Process(bytes, "image/jpeg", fileName);

                content.Add(fileContent);
                files.Add(fileName);
            }

            var store = Substitute.For <IDataStore>();

            var api = new ImageApi(preProcessor, store)
            {
                Request = new HttpRequestMessage(),
            };

            api.Request.Content = content;

            var response = await api.Post();

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
            Assert.IsNotNull(response.Content);

            foreach (var file in files)
            {
                preProcessor.Received().Process(bytes, "image/jpeg", file);
            }
        }
コード例 #23
0
        public void CollectFormattedCredits_MultipleCredits_WorksWithEnDash3()
        {
            _creditsToFormat.Add("some credit", new List <string> {
                "1"
            });
            _creditsToFormat.Add("abc credit", new List <string> {
                "5", "7", "8", "9", "10"
            });
            var results = ImageApi.CollectFormattedCredits(_creditsToFormat);

            Assert.That(results.Count(), Is.EqualTo(2));
            // This is an en-dash, not a hyphen!
            Assert.That(results.First(), Is.EqualTo("Image on page 1 by some credit."));
            Assert.That(results.Last(), Is.EqualTo("Images on pages 5, 7–10 by abc credit."));
        }
コード例 #24
0
        public void CollectFormattedCredits_MultipleCredits_WorksWithEnDash()
        {
            _creditsToFormat.Add("my credit", new List <string> {
                "2"
            });
            _creditsToFormat.Add("next credit", new List <string> {
                "2", "3", "4", "Outside Back Cover"
            });
            var results = ImageApi.CollectFormattedCredits(_creditsToFormat);

            Assert.That(results.Count(), Is.EqualTo(2));
            Assert.That(results.First(), Is.EqualTo("Image on page 2 by my credit."));
            // This is an en-dash, not a hyphen!
            Assert.That(results.Last(), Is.EqualTo("Images on pages 2–4, Outside Back Cover by next credit."));
        }
コード例 #25
0
        public async Task Resize()
        {
            var bytes = File.ReadAllBytes(Environment.CurrentDirectory + @"\icon.png");

            var file = Guid.NewGuid().ToString() + "_.png";

            await this.container.Save(file, bytes, "image/png");

            var api = new ImageApi(connectionString);
            var data = await api.Get(file, 10);

            Assert.IsNotNull(data);
            var resized = await data.Content.ReadAsByteArrayAsync();
            Assert.IsTrue(bytes.LongLength > resized.LongLength);
            Assert.AreEqual("image/jpeg", data.Content.Headers.ContentType.MediaType);
        }
コード例 #26
0
        public async Task Get()
        {
            var random = new Random();
            var bytes = new byte[128];
            random.NextBytes(bytes);

            var file = Guid.NewGuid().ToString();

            await this.container.Save(file, bytes, "image/jpeg");

            var api = new ImageApi(connectionString);
            var data = await api.Get(file);

            Assert.IsNotNull(data);
            Assert.AreEqual(bytes, await data.Content.ReadAsByteArrayAsync());
            Assert.AreEqual("image/jpeg", data.Content.Headers.ContentType.MediaType);
        }
コード例 #27
0
        public async Task Get()
        {
            var random = new Random();
            var bytes  = new byte[128];

            random.NextBytes(bytes);

            var file = Guid.NewGuid().ToString();

            await this.container.Save(file, bytes, "image/jpeg");

            var api  = new ImageApi(connectionString);
            var data = await api.Get(file);

            Assert.IsNotNull(data);
            Assert.AreEqual(bytes, await data.Content.ReadAsByteArrayAsync());
            Assert.AreEqual("image/jpeg", data.Content.Headers.ContentType.MediaType);
        }
コード例 #28
0
        public async Task PostEmpty()
        {
            var preProcessor = Substitute.For <IPreprocessor>();
            var imaging      = Substitute.For <IImaging>();
            var store        = Substitute.For <IDataStore>();

            var api = new ImageApi(preProcessor, store)
            {
                Request = new HttpRequestMessage(),
            };

            api.Request.Content = new MultipartContent();

            var response = await api.Post();

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
        }
コード例 #29
0
        /// <summary>
        /// A texture representing the confidence for each pixel in the raw depth for
        /// the current frame. See the <a href="https://developers.google.com/ar/eap/raw-depth">
        /// developer guide</a> for more information about raw depth.
        /// </summary>
        /// <param name="occlusionManager">The AROcclusionManager instance.</param>
        /// <returns>
        /// The environment raw depth confidence texture, if any. Otherwise, null.
        /// </returns>
        public static Texture2D GetEnvironmentRawDepthConfidenceTexture(
            this AROcclusionManager occlusionManager)
        {
            if (occlusionManager.currentEnvironmentDepthMode ==
                EnvironmentDepthMode.Disabled)
            {
                Debug.LogWarning(
                    "Environment raw depth confidence texture is not available" +
                    " when EnvironmentDepthMode is Disabled.");
                return(null);
            }

            if (!TryGetLastFrameFromExtensions(out XRCameraFrame frame))
            {
                return(null);
            }

            if (CachedData.TryGetCachedData(
                    CachedData.RawDepthConfidenceTexture, out Texture2D texture) &&
                CachedData.TryGetCachedData(
                    CachedData.RawDepthConfidenceTimestamp, out long timestamp) &&
                texture != null && timestamp == frame.timestampNs)
            {
                return(texture);
            }

            IntPtr imageHandle = FrameApi.AcquireRawDepthConfidenceImage(
                ARCoreExtensions._instance.currentARCoreSessionHandle,
                frame.FrameHandle());

            if (imageHandle == IntPtr.Zero)
            {
                return(null);
            }

            ImageApi.UpdateTexture(
                ARCoreExtensions._instance.currentARCoreSessionHandle, imageHandle,
                TextureFormat.Alpha8, ref texture);
            ImageApi.Release(imageHandle);
            CachedData.SetCachedData(CachedData.RawDepthConfidenceTexture, texture);
            CachedData.SetCachedData(CachedData.RawDepthConfidenceTimestamp, frame.timestampNs);

            return(texture);
        }
コード例 #30
0
        public async Task Resize()
        {
            var dir   = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
            var f     = dir.Substring(6, dir.Length - 6) + @"\icon.png";
            var bytes = File.ReadAllBytes(f);

            var file = Guid.NewGuid().ToString() + "_.png";

            await this.container.Save(file, bytes, "image/png");

            var api  = new ImageApi(connectionString);
            var data = await api.Get(file, 10);

            Assert.IsNotNull(data);
            var resized = await data.Content.ReadAsByteArrayAsync();

            Assert.IsTrue(bytes.LongLength > resized.LongLength);
            Assert.AreEqual("image/jpeg", data.Content.Headers.ContentType.MediaType);
        }
コード例 #31
0
        /// <summary>
        /// Get the latest person mask texture that corresponds to the current frame in
        /// <a href="https://docs.unity3d.com/ScriptReference/TextureFormat.Alpha8.html">
        /// TextureFormat.Alpha8</a> format where each pixel represents the confidence of
        /// the segmentation result: 255 represents high confidence that the pixel is part of
        /// a person, 0 represents high confidence that the pixel is not part of a person.
        /// </summary>
        /// <param name="occlusionManager">The AROcclusionManager instance.</param>
        /// <returns>If available, the texture containing the person mask.
        /// Otherwise, returns null and logs the failure reason,
        /// e.g. Segmentation Mode is Disabled, or current camera configuration
        /// is incompatible with <c><see cref="SegmentationMode"/></c>.<c>People</c>.</returns>
        public static Texture2D GetPersonMaskTexture(this AROcclusionManager occlusionManager)
        {
            if (ARCoreExtensions._instance.ARCoreExtensionsConfig.SegmentationMode !=
                SegmentationMode.People)
            {
                Debug.LogWarning(
                    "Person mask texture is not available when SegmentationMode is not People.");
                return(null);
            }

            if (!TryGetLastFrameFromExtensions(out XRCameraFrame frame))
            {
                return(null);
            }

            if (CachedData.TryGetCachedData(
                    CachedData.PersonMaskTexture, out Texture2D texture) &&
                CachedData.TryGetCachedData(
                    CachedData.PersonMaskTextureTimestamp, out long timestamp) &&
                texture != null && timestamp == frame.timestampNs)
            {
                return(texture);
            }

            IntPtr sessionHandle = ARCoreExtensions._instance.currentARCoreSessionHandle;
            IntPtr imageHandle   = FrameApi.AcquirePersonMaskImage(
                sessionHandle, frame.FrameHandle());

            if (imageHandle != IntPtr.Zero)
            {
                ImageApi.UpdateTexture(
                    sessionHandle, imageHandle, TextureFormat.Alpha8, ref texture);
                ImageApi.Release(imageHandle);
                CachedData.SetCachedData(CachedData.PersonMaskTexture, texture);
                CachedData.SetCachedData(
                    CachedData.PersonMaskTextureTimestamp, frame.timestampNs);
            }

            return(texture);
        }
コード例 #32
0
        public async Task PostInvalid()
        {
            var random = new Random();
            var bytes  = new byte[128];

            random.NextBytes(bytes);

            var preProcessor = Substitute.For <IPreprocessor>();
            var store        = Substitute.For <IDataStore>();

            var api = new ImageApi(preProcessor, store)
            {
                Request = new HttpRequestMessage(),
            };

            api.Request.Content = new ByteArrayContent(bytes);

            var response = await api.Post();

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.UnsupportedMediaType, response.StatusCode);
        }
コード例 #33
0
        public static ImageLoadResponse SendLoadImageMultipartRequest(ImageApi apiInstance, int workerNumber, string inputFilePath, string fileName, Stream fileStream, ContentEncoding contentEncoding, OperationsManager.ProgressDelegate uploadOperationStartEventHandler)
        {
            Exception e       = null;
            int       pausems = 5000;

            for (int i = 0; i < FrameworkGlobals.MAX_RETRYING_REQUESTS; i++)
            {
                uploadOperationStartEventHandler.Invoke(workerNumber, inputFilePath, i);
                try
                {
                    fileStream.Seek(0, SeekOrigin.Begin);

                    ImageLoadResponse response = apiInstance.ImageLoadMultipart(fileStream,
                                                                                new LoadImageParameters()
                    {
                        ContentEncoding = contentEncoding,
                        FileName        = fileName
                    });

                    return(response);
                }
                catch (Exception ex)
                {
                    if (i < FrameworkGlobals.MAX_RETRYING_REQUESTS - 1)
                    {
                        Thread.Sleep(pausems); //marking a pause in case of cnx temporarily out and to avoid overhead.
                        pausems += 2000;
                    }
                    else
                    {//last iteration
                        e = ex;
                    }
                }
            }

            throw e;
        }
コード例 #34
0
        public async Task Post()
        {
            var bytes = File.ReadAllBytes(Environment.CurrentDirectory + @"\icon.png");
            var fileContent = new ByteArrayContent(bytes);

            fileContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "myFilename.jpg"
            };

            var preProcessor = Substitute.For<IPreprocessor>();
            preProcessor.Process(bytes, "image/jpeg", "myFilename.jpg");

            var store = Substitute.For<IDataStore>();

            var api = new ImageApi(preProcessor, store)
            {
                Request = new HttpRequestMessage(),
            };
            var content = new MultipartContent();
            content.Add(fileContent);
            api.Request.Content = content;

            var response = await api.Post();

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
            Assert.IsNotNull(response.Content);

            preProcessor.Received().Process(bytes, "image/jpeg", "myFilename.jpg");
        }
コード例 #35
0
        public async Task PostEmpty()
        {
            var preProcessor = Substitute.For<IPreprocessor>();
            var imaging = Substitute.For<IImaging>();
            var store = Substitute.For<IDataStore>();

            var api = new ImageApi(preProcessor, store)
            {
                Request = new HttpRequestMessage(),
            };
            api.Request.Content = new MultipartContent();

            var response = await api.Post();

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
        }
コード例 #36
0
        public async Task PostMultiple()
        {
            var random = new Random();
            var count = random.Next(2, 5);
            var files = new List<string>(count);

            var preProcessor = Substitute.For<IPreprocessor>();

            var content = new MultipartContent();

            var bytes = File.ReadAllBytes(Environment.CurrentDirectory + @"\icon.png");
            for (var i = 0; i < count; i++)
            {
                var fileName = Guid.NewGuid().ToString();
                var fileContent = new ByteArrayContent(bytes);
                fileContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = fileName
                };
                preProcessor.Process(bytes, "image/jpeg", fileName);

                content.Add(fileContent);
                files.Add(fileName);
            }

            var store = Substitute.For<IDataStore>();

            var api = new ImageApi(preProcessor, store)
            {
                Request = new HttpRequestMessage(),
            };
            api.Request.Content = content;

            var response = await api.Post();

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
            Assert.IsNotNull(response.Content);

            foreach (var file in files)
            {
                preProcessor.Received().Process(bytes, "image/jpeg", file);
            }
        }
コード例 #37
0
        public async Task PostInvalid()
        {
            var random = new Random();
            var bytes = new byte[128];
            random.NextBytes(bytes);

            var preProcessor = Substitute.For<IPreprocessor>();
            var store = Substitute.For<IDataStore>();

            var api = new ImageApi(preProcessor, store)
            {
                Request = new HttpRequestMessage(),
            };
            api.Request.Content = new ByteArrayContent(bytes);

            var response = await api.Post();

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.UnsupportedMediaType, response.StatusCode);
        }