Пример #1
0
        /// <summary>
        /// This should result in %BARCODE-%WELL-%DROP-R%R%RTP%P-%IT[%II]-z%Z-%DATE-%TIME, eg:
        /// 441312000010-A01-2-R0DRP1-EF-z20-20100316-083621
        /// 441312000010-A01-2-R0DRP1-FL1-z20-20100316-083621
        /// </summary>
        /// <param name="imageInfo"></param>
        /// <param name="processingInfo"></param>
        /// <param name="plateInfo"></param>
        /// <param name="plateType"></param>
        /// <returns></returns>
        public static string GetFilename(IImageInfo imageInfo, IProcessingInfo processingInfo, IPlateInfo plateInfo, IPlateType plateType)
        {
            string filename = "";

            filename += processingInfo.PlateID + "-";
            filename += OPPF.Integrations.ImagerLink.PlateType.WellNumberToString(plateType, processingInfo.WellNumber) + "-";
            filename += processingInfo.DropNumber + "-";

            filename += "R" + processingInfo.RegionID; // Usually 0

            switch (processingInfo.RegionType)         // Usually Drop
            {
            case RegionType.Drop:
                filename += "DR";
                break;

            case RegionType.Overview:
                filename += "OV";
                break;

            case RegionType.RegionOfInterest:
                filename += "RI";
                break;
            }

            filename += "P" + processingInfo.ProfileID + "-"; // Usually 1

            switch (imageInfo.ImageType)
            {
            case ImageType.BestFocus:
                filename += "BF";
                break;

            case ImageType.DropLocation:
                filename += "DL";
                break;

            case ImageType.ExtendedFocus:
                filename += "EF";
                break;

            case ImageType.FocusLevel:
                filename += "FL" + imageInfo.ImageIndex;
                break;
            }

            if (imageInfo.IsZNull)
            {
                filename += "-zN-";
            }
            else
            {
                filename += "-z" + System.Convert.ToInt32(imageInfo.Z) + "-";
            }

            // Assuming ImagingID is plateID-DATE-TIME format.... (with no dashes in the plateID!)
            filename += processingInfo.ImagingID.Remove(0, processingInfo.ImagingID.IndexOf("-") + 1);

            return(filename);
        }
Пример #2
0
 protected static void AssertEqual(IImageInfo actual, IImageInfo expected)
 {
     actual.Credits.ShouldBe(expected.Credits);
     actual.Height.ShouldBe(expected.Height);
     actual.Width.ShouldBe(expected.Width);
     actual.Link.ShouldBe(expected.Link);
 }
Пример #3
0
        /// <inheritdoc />
        public (int width, int height) GetImageDimensions(string path)
        {
            IImageInfo imageInfo  = null;
            FileStream fileStream = null;

            try
            {
                fileStream = _fileService.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                imageInfo  = Image.Identify(fileStream);
            }
            catch (Exception exception)
            {
                // From the source code, Identify throws a NotSupportedException if fileStream.CanRead is false.
                // File.Open may throw too, so just catch any exception and add context.
                throw new InvalidOperationException(string.Format(Strings.InvalidOperationsException_ImageService_ExceptionThrownWhileAttemptingToReadDimensionsFromLocalImageFile,
                                                                  path),
                                                    exception);
            }
            finally
            {
                fileStream?.Dispose();
            }

            if (imageInfo == null)
            {
                // Identify returns null if no "suitable detector found" - https://docs.sixlabors.com/api/ImageSharp/SixLabors.ImageSharp.Image.html#SixLabors_ImageSharp_Image_Identify_Stream_
                throw new InvalidOperationException(string.Format(Strings.InvalidOperationException_ImageService_UnableToReadDimensionsFromImageFile, path));
            }

            return(imageInfo.Width, imageInfo.Height);
        }
Пример #4
0
            public void FromStream_CustomConfiguration()
            {
                IImageInfo info = Image.Identify(this.LocalConfiguration, this.DataStream, out IImageFormat type);

                Assert.Equal(this.LocalImageInfo, info);
                Assert.Equal(this.LocalImageFormat, type);
            }
Пример #5
0
        /// <summary>
        /// 获得字体大小
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        private int GetFontSize(IImageInfo image)
        {
            var random   = new Random();
            int fontSize = random.Next(image.Height / 2, image.Height);

            return(fontSize);
        }
Пример #6
0
        protected void ButtonPhoto_Click(object sender, EventArgs e)
        {
            if (FileUploadPicture.HasFile)
            {
                string filePath = "~/Files/Temp/" + FileUploadPicture.FileName;
                if (Path.GetExtension(filePath).ToLower() == ".jpg" || Path.GetExtension(filePath).ToLower() == ".jpeg")
                {
                    string fileName     = Session["UserId"] + Path.GetExtension(filePath).ToLower();
                    string relativePath = @"~\Files\Temp\" + fileName;
                    FileUploadPicture.SaveAs(Server.MapPath(relativePath));

                    //use WebManager to get the file, and save it
                    IImageInfo img = WebManager.GetImageInfo(FileUploadPicture);
                    img.Path     = Server.MapPath("~") + "\\Files\\Temp\\";
                    img.FileName = Session["UserId"] + ".jpg";

                    //now create resized versions, and save them
                    IImageInfo img160 = img.ResizeMe(160, 160);
                    img160.Save("~/Files/" + ConfigurationManager.AppSettings["folderName"].ToString() + "/ProfilesPhotos/");

                    LabelPhotoMessage.Visible = true;
                    LabelPhotoMessage.Text    = "You have successfully uploaded your picture.";

                    HiddenFieldPhotoUrl.Value = "Files/" + ConfigurationManager.AppSettings["folderName"].ToString() + "/ProfilesPhotos/" + Session["UserId"].ToString() + ".jpg";

                    File.Delete(Server.MapPath("~") + "\\Files\\Temp\\" + fileName);

                    SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString);
                    SqlCommand    sqlCmd  = new SqlCommand("sp_settingsPhotoEdit", sqlConn);
                    sqlCmd.CommandType = CommandType.StoredProcedure;
                    sqlCmd.Parameters.Add("@UserId", SqlDbType.Int).Value   = Convert.ToInt32(Session["UserId"]);
                    sqlCmd.Parameters.Add("@HasPhoto", SqlDbType.Bit).Value = true;

                    try
                    {
                        sqlConn.Open();
                        sqlCmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                    }
                    finally
                    {
                        sqlConn.Close();
                        sqlCmd.Dispose();
                        sqlConn.Dispose();
                    }
                }
                else
                {
                    LabelPhotoMessage.Visible = true;
                    LabelPhotoMessage.Text    = "Select a picture with JPG extenstion.";
                }
            }
            else
            {
                LabelPhotoMessage.Visible = true;
                LabelPhotoMessage.Text    = "Select a picture file.";
            }
        }
Пример #7
0
            public void FromBytes_GlobalConfiguration()
            {
                IImageInfo info = Image.Identify(this.ActualImageBytes, out IImageFormat type);

                Assert.Equal(ExpectedImageSize, info.Size());
                Assert.Equal(ExpectedGlobalFormat, type);
            }
Пример #8
0
        /// <summary>
        /// For more information, see:
        /// http://www.w3.org/html/wg/drafts/html/master/embedded-content.html#update-the-image-data
        /// </summary>
        void GetImage(Url source)
        {
            if (source.IsInvalid)
            {
                source = null;
            }
            else if (_lastSource != null && source.Equals(_lastSource))
            {
                return;
            }

            this.CancelTasks();
            _lastSource = source;

            if (source == null)
            {
                return;
            }

            var request = this.CreateRequestFor(source);

            this.LoadResource <IImageInfo>(request).ContinueWith(m =>
            {
                if (m.IsFaulted == false)
                {
                    _img = m.Result;
                }

                this.FireLoadOrErrorEvent(m);
            });
        }
Пример #9
0
        public ImageInputType(IHtmlInputElement input, String name)
            : base(input, name, validate: true)
        {
            var inp = input as HtmlInputElement;
            var src = input.Source;

            if (src != null && inp != null)
            {
                var url = inp.HyperReference(src);
                var request = inp.CreateRequestFor(url);
                var document = inp.Owner;

                if (document != null)
                {
                    var loader = document.Loader;

                    if (loader != null)
                    {
                        var download = loader.DownloadAsync(request);
                        var task = inp.ProcessResource<IImageInfo>(download, result => _img = result);
                        document.DelayLoad(task);
                    }
                }
            }
        }
Пример #10
0
            public void FromBytes_CustomConfiguration()
            {
                IImageInfo info = Image.Identify(this.LocalConfiguration, this.ByteArray, out IImageFormat type);

                Assert.Equal(this.LocalImageInfo, info);
                Assert.Equal(this.LocalImageFormat, type);
            }
Пример #11
0
        private static ImageInfo GetImageInfo(IImageInfo image, IImageFormat?detectedFormat)
        {
            var orientation = (ImageOrientation)(image.Metadata.ExifProfile?.GetValue(ExifTag.Orientation)?.Value ?? 0);

            var format = ImageFormat.PNG;

            switch (detectedFormat)
            {
            case BmpFormat:
                format = ImageFormat.BMP;
                break;

            case JpegFormat:
                format = ImageFormat.JPEG;
                break;

            case TgaFormat:
                format = ImageFormat.TGA;
                break;

            case GifFormat:
                format = ImageFormat.GIF;
                break;
            }

            return(new ImageInfo(image.Width, image.Height, orientation, format)
            {
                Format = format
            });
        }
Пример #12
0
        /// <summary>
        /// Executes a given test for a specified shader.
        /// </summary>
        /// <typeparam name="T">The type of shader to test.</typeparam>
        /// <param name="device">The device to use.</param>
        /// <param name="factory">A producer to create an instance of the shader to run.</param>
        /// <param name="delta">The comparison delta.</param>
        private static void RunAndCompareShader <T>(Device device, Func <ReadWriteTexture2D <Rgba32, Float4>, T> factory, float delta)
            where T : struct, IComputeShader
        {
            _ = device.Get();

            string expectedPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) !, "Assets", $"{typeof(T).Name}.png");

            IImageInfo imageInfo = Image.Identify(expectedPath);

            using Image <ImageSharpRgba32> image = new(imageInfo.Width, imageInfo.Height);

            using (ReadWriteTexture2D <Rgba32, Float4> texture = device.Get().AllocateReadWriteTexture2D <Rgba32, Float4>(imageInfo.Width, imageInfo.Height))
            {
                device.Get().For(texture.Width, texture.Height, factory(texture));

                _ = image.TryGetSinglePixelSpan(out Span <ImageSharpRgba32> span);

                texture.CopyTo(MemoryMarshal.Cast <ImageSharpRgba32, Rgba32>(span));
            }

            string actualPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) !, "Shaders", $"{typeof(T).Name}.png");

            _ = Directory.CreateDirectory(Path.GetDirectoryName(actualPath) !);

            image.SaveAsPng(actualPath, new PngEncoder()
            {
                CompressionLevel = PngCompressionLevel.BestCompression, ColorType = PngColorType.Rgb
            });

            ImagingTests.TolerantImageComparer.AssertEqual(expectedPath, actualPath, delta);
        }
Пример #13
0
            public async Task FromStreamAsync_ZeroLength_ReturnsNull()
            {
                // https://github.com/SixLabors/ImageSharp/issues/1903
                using var zipFile = new ZipArchive(new MemoryStream(
                                                       new byte[]
                {
                    0x50, 0x4B, 0x03, 0x04, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x77, 0xAF,
                    0x94, 0x53, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x6D, 0x79, 0x73, 0x74, 0x65, 0x72,
                    0x79, 0x50, 0x4B, 0x01, 0x02, 0x3F, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x77, 0xAF, 0x94, 0x53, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6D,
                    0x79, 0x73, 0x74, 0x65, 0x72, 0x79, 0x0A, 0x00, 0x20, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x01, 0x00, 0x18, 0x00, 0x46, 0x82, 0xFF, 0x91, 0x27, 0xF6,
                    0xD7, 0x01, 0x55, 0xA1, 0xF9, 0x91, 0x27, 0xF6, 0xD7, 0x01, 0x55, 0xA1,
                    0xF9, 0x91, 0x27, 0xF6, 0xD7, 0x01, 0x50, 0x4B, 0x05, 0x06, 0x00, 0x00,
                    0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x59, 0x00, 0x00, 0x00, 0x25, 0x00,
                    0x00, 0x00, 0x00, 0x00
                }));
                using Stream stream = zipFile.Entries[0].Open();
                IImageInfo info = await Image.IdentifyAsync(stream);

                Assert.Null(info);
            }
Пример #14
0
        public IImageInfo GenerateImageInfo()
        {
            IImageInfo imginfo = imgList.First(img => (int)img.storageType != (int)ME3Texture2D.storage.empty);

            imginfo.GameVersion = 3;
            return(imginfo);
        }
Пример #15
0
            public void FromFileSystemPath_GlobalConfiguration()
            {
                IImageInfo info = Image.Identify(ActualImagePath, out IImageFormat type);

                Assert.NotNull(info);
                Assert.Equal(ExpectedGlobalFormat, type);
            }
Пример #16
0
        void IImageProcessor.SetImageInfo(IImageInfo imageInfo)
        {
            _imageInfo = imageInfo;
            try
            {
                _log.Debug("Starting setImageInfo.");
                //Get the required format to save the image...
                string imageFormat = OPPF.Utilities.OPPFConfigXML.GetImageFormat();
                _log.Debug("ImageFormat read.");
                //Then create the filename from the information from the imager.
                string filename = OPPF.Utilities.FileUtils.GetFilename(imageInfo, _processingInfo, OPPF.Utilities.Imaging.ImageUtils.GetImageFormat(imageFormat));
                _log.Debug("Filename successfully read generated.");
                string directory = OPPF.Utilities.FileUtils.GetDirectory(imageInfo, _processingInfo, _robot);

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

                //and then simply save the image!
                imageInfo.Image.Save(directory + filename, OPPF.Utilities.Imaging.ImageUtils.GetImageFormat(imageFormat));
                _log.Debug("Image successfully saved.");
            }
            catch (Exception e)
            {
                _log.Error("Error saving image from Formulatrix: " + imageInfo.ImageType + " for drop " + _processingInfo.DropNumber + " in plate " + _processingInfo.PlateID + ", imaging id " + _processingInfo.ImagingID, e);
                throw e;
            }
        }
Пример #17
0
            public void WhenNoMatchingFormatFound_ReturnsNull()
            {
                IImageInfo info = Image.Identify(new Configuration(), this.DataStream, out IImageFormat type);

                Assert.Null(info);
                Assert.Null(type);
            }
Пример #18
0
        public void Identify_ReadsLegacyExifData(string imagePath)
        {
            var testFile = TestFile.Create(imagePath);

            using (var stream = new MemoryStream(testFile.Bytes, false))
            {
                IImageInfo imageInfo = Image.Identify(stream);
                Assert.NotNull(imageInfo);
                Assert.NotNull(imageInfo.Metadata.ExifProfile);

                PngMetadata meta = imageInfo.Metadata.GetFormatMetadata(PngFormat.Instance);
                Assert.DoesNotContain(meta.TextData, t => t.Keyword.Equals("Raw profile type exif", StringComparison.OrdinalIgnoreCase));

                ExifProfile exif = imageInfo.Metadata.ExifProfile;
                Assert.Equal(0, exif.InvalidTags.Count);
                Assert.Equal(3, exif.Values.Count);

                Assert.Equal(
                    "A colorful tiling of blue, red, yellow, and green 4x4 pixel blocks.",
                    exif.GetValue(ExifTag.ImageDescription).Value);
                Assert.Equal(
                    "Duplicated from basn3p02.png, then image metadata modified with exiv2",
                    exif.GetValue(ExifTag.ImageHistory).Value);

                Assert.Equal(42, (int)exif.GetValue(ExifTag.ImageNumber).Value);
            }
        }
Пример #19
0
            public void FromFileSystemPath_CustomConfiguration()
            {
                IImageInfo info = Image.Identify(this.LocalConfiguration, this.MockFilePath, out IImageFormat type);

                Assert.Equal(this.LocalImageInfo, info);
                Assert.Equal(this.LocalImageFormat, type);
            }
Пример #20
0
 /// <summary>
 /// Reads the raw image information from the specified stream.
 /// </summary>
 /// <param name="decoder">The decoder.</param>
 /// <param name="configuration">The configuration for the image.</param>
 /// <param name="stream">The <see cref="Stream"/> containing image data.</param>
 /// <param name="tooLargeImageExceptionFactory">Factory method to handle <see cref="InvalidMemoryOperationException"/> as <see cref="InvalidImageContentException"/>.</param>
 /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
 /// <exception cref="ArgumentNullException"><paramref name="stream"/> is null.</exception>
 /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
 public static Task <IImageInfo> IdentifyAsync(
     this IImageDecoderInternals decoder,
     Configuration configuration,
     Stream stream,
     Func <InvalidMemoryOperationException, Size, InvalidImageContentException> tooLargeImageExceptionFactory,
     CancellationToken cancellationToken)
 {
     try
     {
         using var bufferedReadStream = new BufferedReadStream(configuration, stream);
         IImageInfo imageInfo = decoder.Identify(bufferedReadStream, cancellationToken);
         return(Task.FromResult(imageInfo));
     }
     catch (InvalidMemoryOperationException ex)
     {
         InvalidImageContentException invalidImageContentException = tooLargeImageExceptionFactory(ex, decoder.Dimensions);
         return(Task.FromException <IImageInfo>(invalidImageContentException));
     }
     catch (OperationCanceledException)
     {
         return(Task.FromCanceled <IImageInfo>(cancellationToken));
     }
     catch (Exception ex)
     {
         return(Task.FromException <IImageInfo>(ex));
     }
 }
Пример #21
0
        /// <summary>
        /// Build a directory from the specified directoryTemplate, imageInfo and processingInfo.
        /// Special substrings %date% and %plateid% will be replaced with the values from the
        /// specified processingInfo.
        /// </summary>
        /// <param name="directoryTemplate">The template for the directory</param>
        /// <param name="imageInfo">The imageInfo (currently unused)</param>
        /// <param name="processingInfo">The processingInfo from which to obtain %date% and %plateid%</param>
        /// <returns>The directory name</returns>
        public static string GetDirectory(string directoryTemplate, IImageInfo imageInfo, IProcessingInfo processingInfo, IRobot robot)
        {
            string directory = directoryTemplate;
            string imagingID = processingInfo.ImagingID;
            string dateTime  = imagingID.Remove(0, imagingID.IndexOf("-") + 1);
            string date      = dateTime.Remove(dateTime.IndexOf("-"), dateTime.Length - dateTime.IndexOf("-"));

            if (directory.IndexOf("%date%") >= 0)
            {
                directory = directory.Replace("%date%", date);
            }
            if (directory.IndexOf("%plateid%") >= 0)
            {
                directory = directory.Replace("%plateid%", processingInfo.PlateID);
            }
            if (directory.IndexOf("%robot%") >= 0)
            {
                directory = directory.Replace("%robot%", robot.Name);
            }
            if (!((directory.EndsWith("/") || (directory.EndsWith("\\")))))
            {
                directory += "/";
            }

            return(directory);
        }
Пример #22
0
        public void WriteOldReadNew(ContextFixtureBase fixture)
        {
            IImageInfo expected = CreateTestObject();

            var actual = MsgPackSerializer.Deserialize <IImageInfo>(MsgPackSerializer.Serialize(expected, fixture.OldContext), fixture.NewContext);

            AssertEqual(actual, expected);
        }
        public static IImageInfo GetImageInfoByByte(byte[] byteArr, string fileName, string type)
        {
            IImageInfo info = GetImageInfo(byteArr);

            info.FileName    = fileName;
            info.ContentType = type;
            return(info);
        }
        public static IImageInfo GetImageInfoV2(HttpPostedFile file)
        {
            IImageInfo info = GetImageInfo(file.InputStream, file.ContentLength);

            info.FileName    = file.FileName;
            info.ContentType = file.ContentType;
            return(info);
        }
Пример #25
0
 /// <summary>
 /// This method is intended to cause any resources that are no
 /// longer necessary to be released
 /// </summary>
 void IDisposable.Dispose()
 {
     _regionName     = null;
     _profileName    = null;
     _captureInfo    = null;
     _imageInfo      = null;
     _robot          = null;
     _processingInfo = null;
 }
Пример #26
0
        void FinishLoading(Task<IImageInfo> m)
        {
            var inp = (HtmlInputElement)Input;

            if (m.IsCompleted && !m.IsFaulted)
                _img = m.Result;

            inp.FireLoadOrErrorEvent(m);
        }
Пример #27
0
        public void DescendantConverterCanUseAscendant(ContextFixtureBase fixture)
        {
            IImageInfo expected = CreateTestObject();

            var actual = MsgPackSerializer.Deserialize <IMegaImageInfo>(MsgPackSerializer.Serialize(expected, fixture.OldContext), fixture.NewContext);

            actual.ShouldBeAssignableTo <IMegaImageInfo>();
            AssertEqual(actual, expected);
        }
Пример #28
0
            public void FromNonSeekableStream_GlobalConfiguration_NoFormat()
            {
                using var stream            = new MemoryStream(ActualImageBytes);
                using var nonSeekableStream = new NonSeekableStream(stream);

                IImageInfo info = Image.Identify(nonSeekableStream);

                Assert.NotNull(info);
            }
Пример #29
0
        void FinishLoading(Task <IImageInfo> task)
        {
            if (task.IsCompleted && !task.IsFaulted)
            {
                _img = task.Result;
            }

            this.FireLoadOrErrorEvent(task);
        }
Пример #30
0
            public void FromStream_GlobalConfiguration_NoFormat()
            {
                using (var stream = new MemoryStream(this.ActualImageBytes))
                {
                    IImageInfo info = Image.Identify(stream);

                    Assert.NotNull(info);
                }
            }
Пример #31
0
            public async Task FromStreamAsync_GlobalConfiguration_NoFormat()
            {
                using (var stream = new MemoryStream(this.ActualImageBytes))
                {
                    var        asyncStream = new AsyncStreamWrapper(stream, () => false);
                    IImageInfo info        = await Image.IdentifyAsync(asyncStream);

                    Assert.NotNull(info);
                }
            }
Пример #32
0
            public void FromStream_GlobalConfiguration()
            {
                using (var stream = new MemoryStream(this.ActualImageBytes))
                {
                    IImageInfo info = Image.Identify(stream, out IImageFormat type);

                    Assert.NotNull(info);
                    Assert.Equal(ExpectedGlobalFormat, type);
                }
            }
Пример #33
0
        public ImageInputType(IHtmlInputElement input, String name)
            : base(input, name, validate: true)
        {
            var inp = input as HtmlInputElement;
            var src = input.Source;

            if (src != null && inp != null)
            {
                var url = inp.HyperReference(src);
                var request = inp.CreateRequestFor(url);
                inp.LoadResource<IImageInfo>(request).ContinueWith(m =>
                {
                    if (m.IsFaulted == false)
                        _img = m.Result;

                    inp.FireLoadOrErrorEvent(m);
                });
            }
        }
Пример #34
0
        /// <summary>
        /// For more information, see:
        /// http://www.w3.org/html/wg/drafts/html/master/embedded-content.html#update-the-image-data
        /// </summary>
        void GetImage(Url source)
        {
            if (source.IsInvalid)
            {
                source = null;
            }
            else if (_img != null && source.Equals(_img.Source))
            {
                return;
            }

            if (_download != null && !_download.IsCompleted)
            {
                _download.Cancel();
            }

            var document = Owner;

            if (source != null && document != null)
            {
                var loader = document.Loader;

                if (loader != null)
                {
                    var request = this.CreateRequestFor(source);
                    var download = loader.DownloadAsync(request);
                    var task = this.ProcessResource<IImageInfo>(download, result => _img = result);
                    document.DelayLoad(task);
                    _download = download;
                }
            }
        }
Пример #35
0
        /// <summary>
        /// For more information, see:
        /// http://www.w3.org/html/wg/drafts/html/master/embedded-content.html#update-the-image-data
        /// </summary>
        void GetImage(Url source)
        {
            if (source.IsInvalid)
                source = null;
            else if (_lastSource != null && source.Equals(_lastSource))
                return;

            this.CancelTasks();
            _lastSource = source;

            if (source == null)
                return;

            var request = this.CreateRequestFor(source);
            this.LoadResource<IImageInfo>(request).ContinueWith(m =>
            {
                if (m.IsFaulted == false)
                    _img = m.Result;

                this.FireLoadOrErrorEvent(m);
            });
        }
Пример #36
0
        void FinishLoading(Task<IImageInfo> task)
        {
            if (task.IsCompleted && !task.IsFaulted)
                _img = task.Result;

            this.FireLoadOrErrorEvent(task);
        }
Пример #37
0
        void UpdateSource(String value)
        {
            this.CancelTasks();

            if (!String.IsNullOrEmpty(value))
            {
                var request = this.CreateRequestFor(Url);
                //TODO Implement with srcset etc. --> see:
                //http://www.w3.org/html/wg/drafts/html/master/embedded-content.html#update-the-image-data
                this.LoadResource<IImageInfo>(request).ContinueWith(m =>
                {
                    if (m.IsFaulted == false)
                        _img = m.Result;

                    this.FireLoadOrErrorEvent(m);
                });
            }
        }
Пример #38
0
 public MappedImageInfo(int x, int y, IImageInfo imageInfo)
 {
     X = x;
     Y = y;
     ImageInfo = imageInfo;
 }
Пример #39
0
 public void ValidateImageInfo(IImageInfo ii, IAtlasDescriptor descriptor)
 {
     if (ii.Image != null && (ii.Image.Width > descriptor.MaxSize || ii.Image.Height > descriptor.MaxSize))
     {
         throw new Exception("Image too large for sheet");
     }
 }