Ejemplo n.º 1
0
        /// <summary>
        /// Gets the default picture URL
        /// </summary>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <param name="defaultPictureType">Default picture type</param>
        /// <returns>Picture URL</returns>
        public virtual string GetDefaultPictureUrl(int targetSize = 0)
        {
            string filePath = GetPictureLocalPath(DefaultPictureFileName);

            if (!File.Exists(filePath))
            {
                return(string.Empty);
            }

            if (targetSize == 0)
            {
                return(string.Format("{0}{1}/{2}",
                                     _webHelper.GetCurrentLocation(),
                                     PictureFolder,
                                     DefaultPictureFileName));
            }

            string fileExtension = Path.GetExtension(filePath);
            string thumbFileName = string.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(filePath), targetSize, fileExtension);
            string thumbFilePath = GetThumbLocalPath(thumbFileName);

            //the named mutex helps to avoid creating the same files in different threads,
            //and does not decrease performance significantly, because the code is blocked only for the specific file.
            using (var mutex = new Mutex(false, thumbFileName))
            {
                if (!File.Exists(thumbFilePath))
                {
                    mutex.WaitOne();

                    //check, if the file was created, while we were waiting for the release of the mutex.
                    if (!File.Exists(thumbFilePath))
                    {
                        using (Image <Rgba32> b = Image.Load(filePath))
                        {
                            using (var ms = new MemoryStream())
                            {
                                var newSize = CalculateDimensions(new Size(b.Width, b.Height), targetSize);
                                var options = new ResizeOptions
                                {
                                    Size = new SixLabors.Primitives.Size(newSize.Width, newSize.Height),
                                    Mode = ResizeMode.Pad
                                };

                                b.Mutate(x => x.Resize(options));
                                b.Save(ms, ImageFormats.Jpeg);

                                //save to file
                                SaveThumbToFile(thumbFilePath, ms.ToArray());
                            }
                        }
                    }

                    mutex.ReleaseMutex();
                }
            }

            return(string.Format("{0}{1}/{2}",
                                 _webHelper.GetCurrentLocation(),
                                 ThumbFolder,
                                 thumbFileName));
        }