public static async Task <GenerationReturn> CopyCleanResizeImage(ImageContent dbEntry,
                                                                         IProgress <string> progress)
        {
            if (dbEntry == null)
            {
                return(await GenerationReturn.Error("Null Image Content submitted to Copy Clean and Resize"));
            }

            progress?.Report($"Starting Copy, Clean and Resize for {dbEntry.Title}");

            if (string.IsNullOrWhiteSpace(dbEntry.OriginalFileName))
            {
                return(await GenerationReturn.Error($"Image {dbEntry.Title} has no Original File", dbEntry.ContentId));
            }

            var imageDirectory = UserSettingsSingleton.CurrentSettings().LocalSiteImageContentDirectory(dbEntry);

            var syncCopyResults = await FileManagement.CheckImageFileIsInMediaAndContentDirectories(dbEntry, progress);

            if (!syncCopyResults.HasError)
            {
                return(syncCopyResults);
            }

            CleanDisplayAndSrcSetFilesInImageDirectory(dbEntry, true, progress);

            ResizeForDisplayAndSrcset(new FileInfo(Path.Combine(imageDirectory.FullName, dbEntry.OriginalFileName)),
                                      false, progress);

            return(await GenerationReturn.Success($"{dbEntry.Title} Copied, Cleaned, Resized", dbEntry.ContentId));
        }
Example #2
0
        public void GetTags(ImageContent CurrentImage)
        {
            string apiKey    = "acc_fdcae2250dc93ab";
            string apiSecret = "1dd2c07fff743949a6e68f47cfadf5e9";
            string image     = CurrentImage.ImagePath;

            string basicAuthValue = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}", apiKey, apiSecret)));

            var client = new RestClient("https://api.imagga.com/v2/tags");

            client.Timeout = -1;

            var request = new RestRequest(Method.POST);

            request.AddHeader("Authorization", String.Format("Basic {0}", basicAuthValue));
            request.AddFile("image", image);

            IRestResponse response = client.Execute(request);
            Root          TagList  = JsonConvert.DeserializeObject <Root>(response.Content);

            foreach (var item in TagList.result.tags)
            {
                CurrentImage.Details.Add(item.tag.en, item.confidence);
            }
        }
Example #3
0
        public void GetDescribtions(ImageContent current)
        {
            string apiKey    = "acc_24c272f71461e5c";
            string apiSecret = "e530b13cdad750e7b0b20de12304b34a";
            string image     = current.imagePath;

            string basicAuthValue = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}", apiKey, apiSecret)));
            var    client         = new RestClient("https://api.imagga.com/v2/tags");

            client.Timeout = -1;

            var request = new RestRequest(Method.POST);

            request.AddHeader("Authorization", String.Format("Basic {0}", basicAuthValue));
            request.AddFile("image", image);

            IRestResponse response = client.Execute(request);

            Root DetailsTree = JsonConvert.DeserializeObject <Root>(response.Content);

            foreach (var item in DetailsTree.result.tags)
            {
                current.ImageDetails.Add(item.tag.en, item.confidence);
            }
        }
Example #4
0
        public static async Task WriteImageFromMediaArchiveToLocalSite(ImageContent imageContent,
                                                                       bool forcedResizeOverwriteExistingFiles, IProgress <string> progress)
        {
            var userSettings = UserSettingsSingleton.CurrentSettings();

            var sourceFile = new FileInfo(Path.Combine(userSettings.LocalMediaArchiveImageDirectory().FullName,
                                                       imageContent.OriginalFileName));

            var targetFile = new FileInfo(Path.Combine(
                                              userSettings.LocalSiteImageContentDirectory(imageContent).FullName, imageContent.OriginalFileName));

            if (targetFile.Exists && forcedResizeOverwriteExistingFiles)
            {
                targetFile.Delete();
                targetFile.Refresh();
            }

            if (!targetFile.Exists)
            {
                await sourceFile.CopyToAndLogAsync(targetFile.FullName);
            }

            PictureResizing.DeleteSupportedPictureFilesInDirectoryOtherThanOriginalFile(imageContent, progress);

            PictureResizing.CleanDisplayAndSrcSetFilesInImageDirectory(imageContent, forcedResizeOverwriteExistingFiles,
                                                                       progress);

            await PictureResizing.ResizeForDisplayAndSrcset(imageContent, forcedResizeOverwriteExistingFiles, progress);
        }
Example #5
0
        public HtmlTag ImageFigureTag(ImageContent dbEntry, string sizes)
        {
            var figureTag = new HtmlTag("figure").AddClass("single-image-container");

            figureTag.Children.Add(Tags.PictureImgTag(Pictures, sizes, true));
            return(figureTag);
        }
Example #6
0
        public List <string> GetTags(string path)
        {
            List <string> Result = new List <string>();

            ImageContent DrugImage = new ImageContent(path);

            ImageAnalysis dal = new ImageAnalysis();

            dal.GetTags(DrugImage);

            var Threshold = 50.0;

            foreach (var item in DrugImage.Details)
            {
                if (item.Value > Threshold)
                {
                    Result.Add(item.Key);
                }
                else
                {
                    break;
                }
            }

            return(Result);
        }
    IEnumerator LoadContent(ImageContent content)
    {
        switch (LoadMode)
        {
        case ContentLoadMode.Online:
            print("Fetching Content from: " + content.WebURL);
            string    webURL = content.WebURL;
            Texture2D tex    = new Texture2D(4, 4, TextureFormat.DXT1, false);
            WWW       www    = new WWW(webURL);
            yield return(www);

            www.LoadImageIntoTexture(tex);
            content.Tex           = tex;
            content.Image.texture = tex;
            break;

        case ContentLoadMode.Offline:
            print("Fetching Content from: " + content.LocalURL);
            string localURL = content.LocalURL;

            break;
        }


        itemsLoaded++;
        Core.BroadcastEvent("OnUpdateProgress", this, Progress);
    }
Example #8
0
        /// <summary>
        /// Creates a resource view from cubic image content
        /// </summary>
        /// <param name="imageContent">Image content</param>
        /// <param name="mipAutogen">Try to generate texture mips</param>
        /// <returns>Returns the created resource view</returns>
        private EngineShaderResourceView CreateResourceCubic(ImageContent imageContent, bool mipAutogen = true)
        {
            if (imageContent.IsArray)
            {
                if (imageContent.Paths.Any())
                {
                    return(this.Get(imageContent.Paths, mipAutogen));
                }
                else if (imageContent.Streams.Any())
                {
                    return(this.Get(imageContent.Streams, mipAutogen));
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(imageContent.Path))
                {
                    return(this.Get(imageContent.Path, mipAutogen));
                }
                else if (imageContent.Stream != null)
                {
                    return(this.Get(imageContent.Stream, mipAutogen));
                }
            }

            return(null);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string urlId = Request.QueryString["Id"];

            if (urlId != null)
            {
                imageList = new List <string>();
                photoId   = Int32.Parse(urlId);
                Models.Image choosenImage = ImageContent.GetImage(photoId);

                if (choosenImage != null)
                {
                    System.Web.UI.WebControls.Image mainImg = new System.Web.UI.WebControls.Image();
                    mainImg.ImageUrl = choosenImage.path.Trim();
                    MainPhoto.Controls.Add(mainImg);

                    imageList = ImageContent.GetSimilarImages(choosenImage.dph);
                }

                Panel p = new Panel();
                p.CssClass = "ImageClass";

                if (imageList.Count > 0)
                {
                    for (int i = 0; i < imageList.Count; i++)
                    {
                        System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
                        img.CssClass = "img-thumbnail";
                        img.ImageUrl = imageList[i].Trim();
                        p.Controls.Add(img);
                    }
                }
                SimilarPhoto.Controls.Add(p);
            }
        }
Example #10
0
 public bool Equals(PocketItem other)
 {
     if (ReferenceEquals(null, other))
     {
         return(false);
     }
     if (ReferenceEquals(this, other))
     {
         return(true);
     }
     return(Id.Equals(other.Id) &&
            ResolvedId.Equals(other.ResolvedId) &&
            Equals(GivenUrl, other.GivenUrl) &&
            Equals(GivenTitle, other.GivenTitle) &&
            IsFavorite.Equals(other.IsFavorite) &&
            Status.Equals(other.Status) &&
            TimeAdded.Equals(other.TimeAdded) &&
            TimeUpdated.Equals(other.TimeUpdated) &&
            TimeRead.Equals(other.TimeRead) &&
            TimeFavorited.Equals(other.TimeFavorited) &&
            TimeSyncDatabaseAdded.Equals(other.TimeSyncDatabaseAdded) &&
            TimeSyncDatabaseUpdated.Equals(other.TimeSyncDatabaseUpdated) &&
            Equals(ResolvedTitle, other.ResolvedTitle) &&
            Equals(ResolvedUrl, other.ResolvedUrl) &&
            Equals(Excerpt, other.Excerpt) &&
            IsArticle.Equals(other.IsArticle) &&
            IsIndex.Equals(other.IsIndex) &&
            ImageContent.Equals(other.ImageContent) &&
            VideoContent.Equals(other.VideoContent) &&
            WordCount.Equals(other.WordCount) &&
            Equals(AmpUrl, other.AmpUrl) &&
            Equals(Encoding, other.Encoding) &&
            Equals(MimeType, other.MimeType) &&
            Equals(LeadImage, other.LeadImage));
 }
Example #11
0
        public void Base64StringToBitmap(ImageContent imageContent)
        {
            try
            {
                Console.WriteLine($"Uploading image.");

                byte[] imgBytes = Convert.FromBase64String(imageContent.Image);

                var path     = @"C:\gotomarket";
                var filePath = Path.Combine(path, imageContent.Name + ".png");

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

                using (var imageFileStream = new FileStream(filePath, FileMode.Create))
                {
                    imageFileStream.Write(imgBytes, 0, imgBytes.Length);
                    imageFileStream.Flush();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error on trying save image. Please check if : {ex.Message}");
            }
        }
Example #12
0
        public static async Task <(GenerationReturn generationReturn, ImageContent imageContent)> SaveAndGenerateHtml(
            ImageContent toSave, FileInfo selectedFile, bool overwriteExistingFiles, DateTime?generationVersion,
            IProgress <string> progress)
        {
            var validationReturn = await Validate(toSave, selectedFile);

            if (validationReturn.HasError)
            {
                return(validationReturn, null);
            }

            Db.DefaultPropertyCleanup(toSave);
            toSave.Tags = Db.TagListCleanup(toSave.Tags);

            toSave.OriginalFileName = selectedFile.Name;
            FileManagement.WriteSelectedImageContentFileToMediaArchive(selectedFile);
            await Db.SaveImageContent(toSave);

            await WriteImageFromMediaArchiveToLocalSite(toSave, overwriteExistingFiles, progress);

            GenerateHtml(toSave, generationVersion, progress);
            await Export.WriteLocalDbJson(toSave);

            DataNotifications.PublishDataNotification("Image Generator", DataNotificationContentType.Image,
                                                      DataNotificationUpdateType.LocalContent, new List <Guid> {
                toSave.ContentId
            });

            return(await GenerationReturn.Success($"Saved and Generated Content And Html for {toSave.Title}"), toSave);
        }
        public static MySqlCommand AddImageContentCommand(ImageContent content)
        {
            var cmd = new MySqlCommand("prInsContent")
            {
                CommandType = CommandType.StoredProcedure
            };

            cmd.Parameters.AddWithValue("ContentId", content.ContentId);
            cmd.Parameters["ContentId"].Direction = ParameterDirection.Input;
            cmd.Parameters.AddWithValue("ImageId", content.ImageId);
            cmd.Parameters["ImageId"].Direction = ParameterDirection.Input;
            cmd.Parameters.AddWithValue("X", content.X);
            cmd.Parameters["X"].Direction = ParameterDirection.Input;
            cmd.Parameters.AddWithValue("Y", content.Y);
            cmd.Parameters["Y"].Direction = ParameterDirection.Input;
            cmd.Parameters.AddWithValue("Width", content.Width);
            cmd.Parameters["Width"].Direction = ParameterDirection.Input;
            cmd.Parameters.AddWithValue("Height", content.Height);
            cmd.Parameters["Height"].Direction = ParameterDirection.Input;
            cmd.Parameters.AddWithValue("ContentDescription", content.ContentDescription);
            cmd.Parameters["ContentDescription"].Direction = ParameterDirection.Input;
            cmd.Parameters.AddWithValue("ContentData", content.ContentData);
            cmd.Parameters["ContentData"].Direction = ParameterDirection.Input;
            cmd.Parameters.AddWithValue("Source", content.Source);
            cmd.Parameters["Source"].Direction = ParameterDirection.Input;

            return(cmd);
        }
        public static PictureAsset ProcessImageDirectory(ImageContent dbEntry)
        {
            var settings         = UserSettingsSingleton.CurrentSettings();
            var contentDirectory = settings.LocalSiteImageContentDirectory(dbEntry);

            return(ProcessImageDirectory(dbEntry, contentDirectory, settings.SiteUrl));
        }
Example #15
0
        private ImageContent CreateImageElementFromXml(XElement source)
        {
            ImageContent element = new ImageContent(source.Value.Trim(), new Vector2((float)source.Attribute("x-position"), (float)source.Attribute("y-position")));

            if (source.Attribute("scale") != null)
            {
                element.Scale = (float)source.Attribute("scale");
            }

            if (source.Element("frame") != null)
            {
                element.Frame = new Rectangle((int)source.Element("frame").Attribute("x"), (int)source.Element("frame").Attribute("y"),
                                              (int)source.Element("frame").Attribute("width"), (int)source.Element("frame").Attribute("height"));
            }

            if (source.Element("origin") != null)
            {
                element.Origin = new Vector2((float)source.Element("origin").Attribute("x"), (float)source.Element("origin").Attribute("y"));
            }

            element.RenderDepth = Element_Render_Depth;

            RegisterGameObject(element);

            return(element);
        }
 public static ImageContentDto ToDto(this ImageContent imageContent)
 {
     return(new()
     {
         ImageContentId = imageContent.ImageContentId
     });
 }
        static void GenFile()
        {
            var templateFileName = "template.docx";
            var tableContent     = new TableContent("row");

            tableContent.AddRow(new FieldContent("subject", "數學"), new FieldContent("score", "90"));
            tableContent.AddRow(new FieldContent("subject", "物理"), new FieldContent("score", "80"));

            var listContent = new ListContent("Team Members List")
                              .AddItem(
                new FieldContent("Name", "Eric"),
                new FieldContent("Role", "Program Manager"))
                              .AddItem(
                new FieldContent("Name", "Bob"),
                new FieldContent("Role", "Developer"));

            var nestLiest = new ListContent("NestedList")
                            .AddItem(new ListItemContent("Role", "Program Manager")
                                     .AddNestedItem(new FieldContent("Name", "Eric"))
                                     .AddNestedItem(new FieldContent("Name", "Ann")))
                            .AddItem(new ListItemContent("Role", "Developer")
                                     .AddNestedItem(new FieldContent("Name", "Bob"))
                                     .AddNestedItem(new FieldContent("Name", "Richard")));

            var imageContent = new ImageContent("Image", File.ReadAllBytes("cat.jpg"));

            var valuesToFill = new Content(new FieldContent("name", "王大明"), new FieldContent("avg", "85"), tableContent, listContent, nestLiest, imageContent);

            using var file             = new FileStream(templateFileName, FileMode.Open, FileAccess.Read);
            using var outputFileStream = new FileStream("output.docx", FileMode.OpenOrCreate, FileAccess.ReadWrite);
            file.CopyTo(outputFileStream);
            using var ouputDocument = new TemplateProcessor(outputFileStream).SetRemoveContentControls(true);
            ouputDocument.FillContent(valuesToFill);
            ouputDocument.SaveChanges();
        }
Example #18
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="game">Game</param>
        /// <param name="name">Name</param>
        /// <param name="description">Particle system description</param>
        /// <param name="emitter">Particle emitter</param>
        public ParticleSystemCpu(Game game, string name, ParticleSystemDescription description, ParticleEmitter emitter)
        {
            this.Game = game;
            this.Name = name;

            this.parameters = new ParticleSystemParams(description) * emitter.Scale;

            var imgContent = new ImageContent()
            {
                Streams = ContentManager.FindContent(description.ContentPath, description.TextureName),
            };

            this.Texture      = game.ResourceManager.CreateResource(imgContent);
            this.TextureCount = (uint)imgContent.Count;

            this.Emitter = emitter;
            this.Emitter.UpdateBounds(this.parameters);
            this.MaxConcurrentParticles = this.Emitter.GetMaximumConcurrentParticles(description.MaxDuration);

            this.particles = new VertexCpuParticle[this.MaxConcurrentParticles];

            this.buffer = new EngineBuffer <VertexCpuParticle>(game.Graphics, description.Name, this.particles, true);
            buffer.AddInputLayout(game.Graphics.CreateInputLayout(DrawerPool.EffectDefaultCPUParticles.RotationDraw.GetSignature(), VertexCpuParticle.Input(BufferSlot)));
            buffer.AddInputLayout(game.Graphics.CreateInputLayout(DrawerPool.EffectDefaultCPUParticles.NonRotationDraw.GetSignature(), VertexCpuParticle.Input(BufferSlot)));

            this.TimeToEnd = this.Emitter.Duration + this.parameters.MaxDuration;
        }
        /// <summary>
        ///     This deletes Image Directory jpeg files that match this programs generated sizing naming conventions. If deleteAll
        ///     is true then all
        ///     files will be deleted - otherwise only files where the width does not match one of the generated widths will be
        ///     deleted.
        /// </summary>
        /// <param name="dbEntry"></param>
        /// <param name="deleteAll"></param>
        /// <param name="progress"></param>
        public static void CleanDisplayAndSrcSetFilesInImageDirectory(ImageContent dbEntry, bool deleteAll,
                                                                      IProgress <string> progress)
        {
            var currentSizes = SrcSetSizeAndQualityList().Select(x => x.size).ToList();

            progress?.Report($"Starting SrcSet Image Cleaning... Current Size List {string.Join(", ", currentSizes)}");

            var currentFiles = PictureAssetProcessing.ProcessImageDirectory(dbEntry);

            foreach (var loopFiles in currentFiles.SrcsetImages)
            {
                if (!currentSizes.Contains(loopFiles.Width) || deleteAll)
                {
                    progress?.Report($"  Deleting {loopFiles.FileName}");
                    loopFiles.File.Delete();
                }
            }

            var sourceFileReference =
                UserSettingsSingleton.CurrentSettings().LocalMediaArchiveImageContentFile(dbEntry);
            var expectedDisplayWidth = DisplayPictureWidth(sourceFileReference, progress);

            if (currentFiles.DisplayPicture != null && currentFiles.DisplayPicture.Width != expectedDisplayWidth ||
                deleteAll)
            {
                currentFiles.DisplayPicture?.File?.Delete();
            }
        }
Example #20
0
        public static async Task <GenerationReturn> Validate(ImageContent imageContent, FileInfo selectedFile)
        {
            var rootDirectoryCheck = UserSettingsUtilities.ValidateLocalSiteRootDirectory();

            if (!rootDirectoryCheck.Item1)
            {
                return(await GenerationReturn.Error($"Problem with Root Directory: {rootDirectoryCheck.Item2}",
                                                    imageContent.ContentId));
            }

            var mediaArchiveCheck = UserSettingsUtilities.ValidateLocalMediaArchive();

            if (!mediaArchiveCheck.Item1)
            {
                return(await GenerationReturn.Error($"Problem with Media Archive: {mediaArchiveCheck.Item2}",
                                                    imageContent.ContentId));
            }

            var commonContentCheck = await CommonContentValidation.ValidateContentCommon(imageContent);

            if (!commonContentCheck.valid)
            {
                return(await GenerationReturn.Error(commonContentCheck.explanation, imageContent.ContentId));
            }

            var updateFormatCheck = CommonContentValidation.ValidateUpdateContentFormat(imageContent.UpdateNotesFormat);

            if (!updateFormatCheck.isValid)
            {
                return(await GenerationReturn.Error(updateFormatCheck.explanation, imageContent.ContentId));
            }

            selectedFile.Refresh();

            if (!selectedFile.Exists)
            {
                return(await GenerationReturn.Error("Selected File doesn't exist?", imageContent.ContentId));
            }

            if (!FolderFileUtility.IsNoUrlEncodingNeeded(Path.GetFileNameWithoutExtension(selectedFile.Name)))
            {
                return(await GenerationReturn.Error("Limit File Names to A-Z a-z - . _", imageContent.ContentId));
            }

            if (!FolderFileUtility.PictureFileTypeIsSupported(selectedFile))
            {
                return(await GenerationReturn.Error("The file doesn't appear to be a supported file type.",
                                                    imageContent.ContentId));
            }

            if (await(await Db.Context()).ImageFilenameExistsInDatabase(selectedFile.Name, imageContent.ContentId))
            {
                return(await GenerationReturn.Error(
                           "This filename already exists in the database - image file names must be unique.",
                           imageContent.ContentId));
            }

            return(await GenerationReturn.Success("Image Content Validation Successful"));
        }
Example #21
0
        protected override MaterialContent Convert(SharpGLTF.Schema2.Material srcMaterial)
        {
            var dstMaterial = new MaterialContent();

            dstMaterial.Name = srcMaterial.Name;
            dstMaterial.Tag  = _TagConverter?.Invoke(srcMaterial);

            dstMaterial.DoubleSided = srcMaterial.DoubleSided;

            dstMaterial.AlphaCutoff = srcMaterial.AlphaCutoff;
            switch (srcMaterial.Alpha)
            {
            case SharpGLTF.Schema2.AlphaMode.OPAQUE: dstMaterial.Mode = MaterialBlendMode.Opaque; break;

            case SharpGLTF.Schema2.AlphaMode.MASK: dstMaterial.Mode = MaterialBlendMode.Mask; break;

            case SharpGLTF.Schema2.AlphaMode.BLEND: dstMaterial.Mode = MaterialBlendMode.Blend; break;
            }

            if (srcMaterial.Unlit)
            {
                dstMaterial.PreferredShading = "Unlit";
            }
            else if (srcMaterial.FindChannel("SpecularGlossiness") != null)
            {
                dstMaterial.PreferredShading = "SpecularGlossiness";
            }
            else if (srcMaterial.FindChannel("MetallicRoughness") != null)
            {
                dstMaterial.PreferredShading = "MetallicRoughness";
            }

            foreach (var srcChannel in srcMaterial.Channels)
            {
                var dstChannel = dstMaterial.UseChannel(srcChannel.Key);

                dstChannel.Value = ParamToArray(srcChannel);

                if (srcChannel.Texture != null)
                {
                    var imgData = srcChannel.Texture.PrimaryImage.Content.Content.ToArray();

                    var texContent = new ImageContent(imgData);

                    dstChannel.TextureIndex = UseTexture(texContent);
                    dstChannel.Sampler      = ToXna(srcChannel.Texture.Sampler);
                }
                else
                {
                    dstChannel.Sampler = SamplerStateContent.CreateDefault();
                }


                dstChannel.VertexIndexSet = srcChannel.TextureCoordinate;
                dstChannel.Transform      = (srcChannel.TextureTransform?.Matrix ?? System.Numerics.Matrix3x2.Identity).ToXna();
            }

            return(dstMaterial);
        }
Example #22
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = 47;
         hashCode = (hashCode * 53) ^ Id.GetHashCode();
         hashCode = (hashCode * 53) ^ ResolvedId.GetHashCode();
         if (GivenUrl != null)
         {
             hashCode = (hashCode * 53) ^ GivenUrl.GetHashCode();
         }
         if (GivenTitle != null)
         {
             hashCode = (hashCode * 53) ^ GivenTitle.GetHashCode();
         }
         hashCode = (hashCode * 53) ^ IsFavorite.GetHashCode();
         hashCode = (hashCode * 53) ^ (int)Status;
         hashCode = (hashCode * 53) ^ TimeAdded.GetHashCode();
         hashCode = (hashCode * 53) ^ TimeUpdated.GetHashCode();
         hashCode = (hashCode * 53) ^ TimeRead.GetHashCode();
         hashCode = (hashCode * 53) ^ TimeFavorited.GetHashCode();
         hashCode = (hashCode * 53) ^ TimeSyncDatabaseAdded.GetHashCode();
         hashCode = (hashCode * 53) ^ TimeSyncDatabaseUpdated.GetHashCode();
         if (ResolvedTitle != null)
         {
             hashCode = (hashCode * 53) ^ ResolvedTitle.GetHashCode();
         }
         if (ResolvedUrl != null)
         {
             hashCode = (hashCode * 53) ^ ResolvedUrl.GetHashCode();
         }
         if (Excerpt != null)
         {
             hashCode = (hashCode * 53) ^ Excerpt.GetHashCode();
         }
         hashCode = (hashCode * 53) ^ IsArticle.GetHashCode();
         hashCode = (hashCode * 53) ^ IsIndex.GetHashCode();
         hashCode = (hashCode * 53) ^ ImageContent.GetHashCode();
         hashCode = (hashCode * 53) ^ VideoContent.GetHashCode();
         hashCode = (hashCode * 53) ^ WordCount.GetHashCode();
         if (AmpUrl != null)
         {
             hashCode = (hashCode * 53) ^ AmpUrl.GetHashCode();
         }
         if (Encoding != null)
         {
             hashCode = (hashCode * 53) ^ Encoding.GetHashCode();
         }
         if (MimeType != null)
         {
             hashCode = (hashCode * 53) ^ MimeType.GetHashCode();
         }
         if (LeadImage != null)
         {
             hashCode = (hashCode * 53) ^ LeadImage.GetHashCode();
         }
         return(hashCode);
     }
 }
Example #23
0
 public static PdfResult CreateSuccesResult(TimeSpan processTime, ImageContent imageContent)
 {
     if (imageContent == null)
     {
         throw new ArgumentNullException(nameof(imageContent));
     }
     return(new PdfResult(processTime, imageContent, null));
 }
Example #24
0
        private HtmlTag LocalImageFigureTag(ImageContent dbEntry)
        {
            var figureTag = new HtmlTag("figure").AddClass("single-photo-container");

            figureTag.Children.Add(LocalDisplayPhotoImageTag());
            figureTag.Children.Add(Tags.ImageFigCaptionTag(dbEntry));
            return(figureTag);
        }
        /// <summary>Function to open a content object from this plugin.</summary>
        /// <param name="file">The file that contains the content.</param>
        /// <param name = "fileManager" > The file manager used to access other content files.</param>
        /// <param name="injector">Parameters for injecting dependency objects.</param>
        /// <param name="scratchArea">The file system for the scratch area used to write transitory information.</param>
        /// <param name="undoService">The undo service for the plug in.</param>
        /// <returns>A new IEditorContent object.</returns>
        /// <remarks>
        /// The <paramref name="scratchArea" /> parameter is the file system where temporary files to store transitory information for the plug in is stored. This file system is destroyed when the
        /// application or plug in is shut down, and is not stored with the project.
        /// </remarks>
        protected async override Task <IEditorContent> OnOpenContentAsync(IContentFile file, IContentFileManager fileManager, IGorgonFileSystemWriter <Stream> scratchArea, IUndoService undoService)
        {
            FileInfo          texConvExe = GetTexConvExe();
            TexConvCompressor compressor = null;

            if (texConvExe.Exists)
            {
                compressor = new TexConvCompressor(texConvExe, scratchArea, _ddsCodec);
            }

            var imageIO = new ImageIOService(_ddsCodec,
                                             _codecs,
                                             new ExportImageDialogService(_settings),
                                             new ImportImageDialogService(_settings, _codecs),
                                             CommonServices.BusyService,
                                             scratchArea,
                                             compressor,
                                             CommonServices.Log);

            (IGorgonImage image, IGorgonVirtualFile workingFile, BufferFormat originalFormat)imageData = await Task.Run(() => {
                using (Stream inStream = file.OpenRead())
                {
                    return(imageIO.LoadImageFile(inStream, file.Name));
                }
            });

            var services = new ImageEditorServices
            {
                CommonServices        = CommonServices,
                ImageIO               = imageIO,
                UndoService           = undoService,
                ImageUpdater          = new ImageUpdaterService(),
                ExternalEditorService = new ImageExternalEditService(CommonServices.Log)
            };

            var cropResizeSettings = new CropResizeSettings();
            var dimensionSettings  = new DimensionSettings();
            var mipSettings        = new MipMapSettings();

            cropResizeSettings.Initialize(CommonServices);
            dimensionSettings.Initialize(new DimensionSettingsParameters(GraphicsContext.Graphics.VideoAdapter, CommonServices));
            mipSettings.Initialize(CommonServices);


            var content = new ImageContent();

            content.Initialize(new ImageContentParameters(file,
                                                          _settings,
                                                          cropResizeSettings,
                                                          dimensionSettings,
                                                          mipSettings,
                                                          imageData,
                                                          GraphicsContext.Graphics.VideoAdapter,
                                                          GraphicsContext.Graphics.FormatSupport,
                                                          services));

            return(content);
        }
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            ImageContent imageContent = await db.ImageContents.FindAsync(id);

            db.ImageContents.Remove(imageContent);
            await db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
Example #27
0
        public HtmlTag ImageFigureWithLinkToPageTag(ImageContent dbEntry, string sizes)
        {
            var figureTag = new HtmlTag("figure").AddClass("single-image-container");
            var linkTag   = new LinkTag(string.Empty, PageUrl);

            linkTag.Children.Add(Tags.PictureImgTag(Pictures, sizes, true));
            figureTag.Children.Add(linkTag);
            return(figureTag);
        }
        public static PictureAsset ProcessImageDirectory(ImageContent dbEntry, DirectoryInfo directoryInfo,
                                                         string siteUrl)
        {
            var toReturn = new PictureAsset {
                DbEntry = dbEntry
            };

            var baseFileNameList = dbEntry.OriginalFileName.Split(".").ToList();
            var baseFileName     = string.Join("", baseFileNameList.Take(baseFileNameList.Count - 1));

            var fileVariants = directoryInfo.GetFiles().Where(x => x.Name.StartsWith($"{baseFileName}--")).ToList();

            var displayImageFile = fileVariants.SingleOrDefault(x => x.Name.Contains("--For-Display"));

            if (displayImageFile != null && displayImageFile.Exists)
            {
                toReturn.DisplayPicture = new PictureFile
                {
                    FileName = displayImageFile.Name,
                    SiteUrl  = $@"//{siteUrl}/Images/{dbEntry.Folder}/{dbEntry.Slug}/{displayImageFile.Name}",
                    File     = displayImageFile,
                    AltText  = dbEntry.AltText ?? string.Empty,
                    Height   =
                        int.Parse(Regex
                                  .Match(displayImageFile.Name, @".*--(?<height>\d*)h.*", RegexOptions.Singleline)
                                  .Groups["height"].Value),
                    Width = int.Parse(Regex
                                      .Match(displayImageFile.Name, @".*--(?<width>\d*)w.*", RegexOptions.Singleline)
                                      .Groups["width"].Value)
                }
            }
            ;

            var srcsetImageFiles = fileVariants.Where(x => x.Name.Contains("--Sized")).ToList();

            toReturn.SrcsetImages = srcsetImageFiles.Select(x => new PictureFile
            {
                FileName = x.Name,
                Height   =
                    int.Parse(Regex.Match(x.Name, @".*--(?<height>\d*)h.*", RegexOptions.Singleline)
                              .Groups["height"].Value),
                Width = int.Parse(Regex.Match(x.Name, @".*--(?<width>\d*)w.*", RegexOptions.Singleline)
                                  .Groups["width"].Value),
                SiteUrl = $@"//{siteUrl}/Images/{dbEntry.Folder}/{dbEntry.Slug}/{x.Name}",
                AltText = dbEntry.AltText ?? string.Empty,
                File    = x
            }).ToList();

            if (srcsetImageFiles.Any())
            {
                toReturn.LargePicture =
                    toReturn.SrcsetImages.OrderByDescending(x => Math.Max(x.Height, x.Width)).First();
                toReturn.SmallPicture = toReturn.SrcsetImages.OrderBy(x => Math.Max(x.Height, x.Width)).First();
            }

            return(toReturn);
        }
        public void Phase0(LineViewModel line)
        {
            var iv = LayoutRoot;

            ImageContent.Opacity     = 0;
            ImageContent.Height      = double.NaN;
            CommentIndicator.Opacity = 0;
            ProgressBar.Opacity      = 0;
            TextContent.Opacity      = 1;
            if (ImageContent.Source != null)
            {
                var bitmap = ImageContent.Source as BitmapImage;
                bitmap.DownloadProgress -= Image_DownloadProgress;
                ImageContent.ClearValue(Image.SourceProperty);
            }

            if (line.IsImage)
            {
                if (!AppGlobal.ShouldAutoLoadImage)
                {
                    TextContent.Text = ImageTapToLoadPlaceholder;
                }
                else
                {
                    TextContent.Text = ImageLoadingTextPlaceholder;
                }

                double aspect = line.ImageWidth <= 0? .0 : (double)line.ImageHeight / (double)line.ImageWidth;
                double ih     = iv.Width * aspect;

                if (ih > 1.0)
                {
                    ImageContent.Height     = ih;
                    ImagePlaceHolder.Height = ih;
                }
                else
                {
                    ImagePlaceHolder.Height = double.NaN;
                }

                ProgressBar.Visibility      = Visibility.Visible;
                ImageContent.Visibility     = Visibility.Visible;
                ImagePlaceHolder.Visibility = Visibility.Visible;
                TextContent.TextAlignment   = TextAlignment.Center;
            }
            else
            {
                TextContent.Text = " " + line.Content;
                //textContent.Height = double.NaN;
                TextContent.TextAlignment = TextAlignment.Left;

                ImagePlaceHolder.Visibility = Visibility.Collapsed;
                ImageContent.Visibility     = Visibility.Collapsed;
                ImageContent.DataContext    = null;
            }
        }
Example #30
0
        private void CreateContentForLockedArea()
        {
            Rectangle    iconFrame  = TextureManager.Textures["icon-locked"].Bounds;
            Vector2      iconOrigin = new Vector2(iconFrame.Width, iconFrame.Height) / 2.0f;
            ImageContent icon       = CreateImageElement("icon-locked", Definitions.Back_Buffer_Center, iconFrame, iconOrigin, 5.0f);

            icon.RenderDepth = 0.6f;

            CreateTextElement(Translator.Translation("Locked"), Definitions.Back_Buffer_Center, TextWriter.Alignment.Center, 1.0f);
        }
Example #31
0
 /// <summary>
 /// Create a new ImageContent object.
 /// </summary>
 /// <param name="id">Initial value of Id.</param>
 /// <param name="fileName">Initial value of FileName.</param>
 /// <param name="language">Initial value of Language.</param>
 public static ImageContent CreateImageContent(int id, string fileName, string language)
 {
     ImageContent imageContent = new ImageContent();
     imageContent.Id = id;
     imageContent.FileName = fileName;
     imageContent.Language = language;
     return imageContent;
 }
Example #32
0
 /// <summary>
 /// There are no comments for ImageContent in the schema.
 /// </summary>
 public void AddToImageContent(ImageContent imageContent)
 {
     base.AddObject("ImageContent", imageContent);
 }
        private ImageContent GenerateImageContent(HttpPostedFileBase fileBase)
        {
            var result = new ImageContent();
            using (var memoryStream = new MemoryStream(fileBase.ContentLength))
            {
                fileBase.InputStream.CopyTo(memoryStream);
                result.Content = memoryStream.ToArray();
            }

            return result;
        }