Example #1
0
        public MemoryStream ResizeImage(Stream imageStream, ImageSizes size)
        {
            var newHeight = size.Size().Height;
            var newWidth = size.Size().Width;

            var oldImage = System.Drawing.Image.FromStream(imageStream);
            double oldHeight = oldImage.Height;
            double oldWidth = oldImage.Width;

            var widthChange = Math.Abs(newWidth - oldWidth);
            var heightChange = Math.Abs(newHeight - oldHeight);

            var greatestChangeDimension = (widthChange > heightChange) ? Dimensions.Width : Dimensions.Height;

            if(greatestChangeDimension == Dimensions.Width)
            {
                var ratio  = (1/(oldWidth/oldHeight));
                newHeight = newWidth * ratio;
            }
            if(greatestChangeDimension == Dimensions.Height)
            {
                var ratio = (1/(oldWidth/oldHeight));
                newWidth = newHeight * ratio;
            }

            var newImage = new Bitmap(oldImage, new Size((int) Math.Floor(newWidth), (int) Math.Floor(newHeight)));
            var newImageMemoryStream = new MemoryStream();
            newImage.Save(newImageMemoryStream, ImageFormat.Png);

            return newImageMemoryStream;
        }
        public EntryThumbForApiContract(IEntryImageInformation image, IAggregatedEntryImageUrlFactory thumbPersister,
                                        ImageSizes sizes = ImageSizes.All)
        {
            ParamIs.NotNull(() => image);
            ParamIs.NotNull(() => thumbPersister);

            Mime = image.Mime;

            if (string.IsNullOrEmpty(image.Mime) && sizes != ImageSizes.Nothing)
            {
                return;
            }

            if (sizes.HasFlag(ImageSizes.Original))
            {
                UrlOriginal = thumbPersister.GetUrlAbsolute(image, ImageSize.Original);
            }

            if (sizes.HasFlag(ImageSizes.SmallThumb))
            {
                UrlSmallThumb = thumbPersister.GetUrlAbsolute(image, ImageSize.SmallThumb);
            }

            if (sizes.HasFlag(ImageSizes.Thumb))
            {
                UrlThumb = thumbPersister.GetUrlAbsolute(image, ImageSize.Thumb);
            }

            if (sizes.HasFlag(ImageSizes.TinyThumb))
            {
                UrlTinyThumb = thumbPersister.GetUrlAbsolute(image, ImageSize.TinyThumb);
            }
        }
        /// <summary>
        /// Gets the image path.
        /// </summary>
        /// <param name="imageType">Type of the image.</param>
        /// <param name="imageSize">Size of the image.</param>
        /// <returns>The image path</returns>
        public string GetImagePath(ImageTypes imageType, ImageSizes imageSize)
        {
            var builder = new StringBuilder();

            builder.Append(_configuration.Images.SecureBaseUrl);

            string sizeValue = string.Empty;

            switch (imageType)
            {
            case ImageTypes.Backdrop:
                sizeValue = GetImageSize(_configuration.Images.BackdropSizes, imageSize);
                break;

            case ImageTypes.Logo:
                sizeValue = GetImageSize(_configuration.Images.LogoSizes, imageSize);
                break;

            case ImageTypes.Poster:
                sizeValue = GetImageSize(_configuration.Images.PosterSizes, imageSize);
                break;

            case ImageTypes.Profile:
                sizeValue = GetImageSize(_configuration.Images.ProfileSizes, imageSize);
                break;

            case ImageTypes.Still:
                sizeValue = sizeValue = GetImageSize(_configuration.Images.StillSizes, imageSize);
                break;
            }

            builder.Append(sizeValue);

            return(builder.ToString());
        }
Example #4
0
        /// <summary>
        /// Initializes image data.
        /// </summary>
        /// <param name="image">Image information. Cannot be null.</param>
        /// <param name="thumbPersister">Thumb persister. Cannot be null.</param>
        /// <param name="ssl">Whether to generate SSL URLs.</param>
        /// <param name="sizes">Sizes to generate. If Nothing, no image URLs will be generated.</param>
        public EntryThumbForApiContract(IEntryImageInformation image, IEntryImagePersister thumbPersister, bool ssl,
                                        ImageSizes sizes = ImageSizes.All)
        {
            ParamIs.NotNull(() => image);
            ParamIs.NotNull(() => thumbPersister);

            if (string.IsNullOrEmpty(image.Mime) && sizes != ImageSizes.Nothing)
            {
                return;
            }

            if (sizes.HasFlag(ImageSizes.SmallThumb))
            {
                UrlSmallThumb = thumbPersister.GetUrlAbsolute(image, ImageSize.SmallThumb, ssl);
            }

            if (sizes.HasFlag(ImageSizes.Thumb))
            {
                UrlThumb = thumbPersister.GetUrlAbsolute(image, ImageSize.Thumb, ssl);
            }

            if (sizes.HasFlag(ImageSizes.TinyThumb))
            {
                UrlTinyThumb = thumbPersister.GetUrlAbsolute(image, ImageSize.TinyThumb, ssl);
            }
        }
Example #5
0
        /// <summary>
        /// Processes the image file.
        /// </summary>
        /// <param name="imageFileInfo"></param>
        protected void ProcessImageFile(FileInfo imageFileInfo)
        {
            if (Canceled)
            {
                return;
            }
            string[] dimensions = ImageSizes.Split(",".ToCharArray()[0]);
            Bitmap   tmpBmp     = new Bitmap(imageFileInfo.FullName);

            foreach (string dimension in dimensions)
            {
                string[] numbers = dimension.Split("x".ToCharArray()[0]);
                int      width;
                int      height;
                if (numbers.Length == 2)
                {
                    if (int.TryParse(numbers[0], out width) &&
                        int.TryParse(numbers[1], out height))
                    {
                        if (tmpBmp.Width > width)
                        {
                            CreateOutputImageFile(imageFileInfo, width, height);
                        }
                    }
                }
            }
        }
 private void SetImageSizes(string id, string dimensions, string path = null, bool isDynamic = false)
 {
     if (dimensions != null && dimensions.Contains("*"))
     {
         var splits = dimensions.Split('*');
         if (splits != null && splits.Length > 1)
         {
             int.TryParse(splits[0], out var width);
             int.TryParse(splits[1], out var height);
             var imageSize = new ImageSize()
             {
                 ImageID   = id,
                 ImageName = path,
                 Height    = height,
                 Width     = width,
                 IsDynamic = isDynamic
             };
             ImageSizes.Add(imageSize);
             if (width == 0 || width == 99 || height == 0 || height == 99)
             {
                 ShowImageMessage(id);
             }
         }
         else
         {
             ShowImageMessage(id);
         }
     }
     else
     {
         ShowImageMessage(id);
     }
 }
        public EntryThumbForApiContract GetIcons(IUserWithEmail user, ImageSizes sizes = ImageSizes.All)
        {
            var contract = new EntryThumbForApiContract();

            if (string.IsNullOrEmpty(user.Email))
            {
                return(contract);
            }

            if (sizes.HasFlag(ImageSizes.Thumb))
            {
                contract.UrlThumb = GetUrl(user, ImageHelper.UserThumbSize);
            }

            if (sizes.HasFlag(ImageSizes.SmallThumb))
            {
                contract.UrlSmallThumb = GetUrl(user, ImageHelper.UserSmallThumbSize);
            }

            if (sizes.HasFlag(ImageSizes.TinyThumb))
            {
                contract.UrlTinyThumb = GetUrl(user, ImageHelper.UserTinyThumbSize);
            }

            return(contract);
        }
 private Image ResizeImage(int oldWidth, int oldHeight, ImageSizes imageSize)
 {
     var image = new Bitmap(oldWidth, oldHeight);
     var memoryStream = new MemoryStream();
     image.Save(memoryStream, ImageFormat.Png);
     memoryStream = _imageService.ResizeImage(memoryStream, imageSize);
     return System.Drawing.Image.FromStream(memoryStream);
 }
Example #9
0
        /// <summary>
        /// Resize to defined size type and return image. x32 is height and weight = 32.
        /// </summary>
        /// <param name="formFile"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static Image ResizeToImage(this IFormFile formFile, ImageSizes size)
        {
            SetSize(size);
            _image = formFile.ToImage();
            SetHeightWidth(_image);
            var resizedImage = _image.GetThumbnailImage((int)_width, (int)_height, () => false, IntPtr.Zero);

            return(resizedImage);
        }
        /// <summary>
        /// Formalizes the image path.
        /// </summary>
        /// <param name="sourcePath">The source path.</param>
        /// <param name="type">The type.</param>
        /// <param name="size">The size.</param>
        /// <returns>The formalized image path</returns>
        private string FormalizeImagePath(string sourcePath, ImageTypes type, ImageSizes size)
        {
            if (!string.IsNullOrWhiteSpace(sourcePath))
            {
                return(_imageHelper.GetImagePath(type, size) + sourcePath);
            }

            return(string.Empty);
        }
        public static EntryThumbForApiContract Create(IEntryImageInformation image, IAggregatedEntryImageUrlFactory thumbPersister,
                                                      ImageSizes sizes = ImageSizes.All)
        {
            if (thumbPersister == null || string.IsNullOrEmpty(image?.Mime))
            {
                return(null);
            }

            return(new EntryThumbForApiContract(image, thumbPersister, sizes));
        }
Example #12
0
        /// <summary>
        /// Resize image to defined size type and return as base64 string. x32 is height and weight = 32.
        /// </summary>
        /// <param name="image"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static string ResizeToBase64(this Image image, ImageSizes size)
        {
            SetSize(size);
            _image = image;
            SetHeightWidth(_image);
            var resizedImage = _image.GetThumbnailImage((int)_width, (int)_height, () => false, IntPtr.Zero);
            var base64       = resizedImage.ToBase64String();

            return(base64);
        }
		private EntryThumbContract CallGenerateThumbsAndMoveImage(ImageSizes sizes) {

			var thumb = new EntryThumbContract {EntryType = EntryType.SongList, FileName = "test.jpg"};

			using (var input = TestImage()) {
				target.GenerateThumbsAndMoveImage(input, thumb, sizes);				
			}
			
			return thumb;

		}
 /// <summary>
 /// Creates a crew result model from an external crew result.
 /// </summary>
 /// <param name="source">The source.</param>
 /// <param name="profileImageSize">Size of the profile image.</param>
 /// <returns>Crew result model</returns>
 public CrewResultModel Create(CrewResult source, ImageSizes profileImageSize = ImageSizes.Small)
 {
     return(new CrewResultModel
     {
         Id = source.Id,
         Job = source.Job,
         Name = source.Name,
         ProfileImageUrl = FormalizeImagePath(source.ProfilePath, ImageTypes.Profile, profileImageSize),
         ProfileImageUrlOriginal = FormalizeImagePath(source.ProfilePath, ImageTypes.Profile, ImageSizes.Original)
     });
 }
 /// <summary>
 /// Creates an image result model from an external image result.
 /// </summary>
 /// <param name="source">The source.</param>
 /// <param name="size">The size.</param>
 /// <returns>Image result model</returns>
 public ImageResultModel Create(ImageResult source, ImageSizes size)
 {
     return(new ImageResultModel
     {
         AspectRatio = source.AspectRatio,
         Height = source.Height,
         Width = source.Width,
         ImageUrl = FormalizeImagePath(source.FilePath, ImageTypes.Profile, size),
         ImageUrlOriginal = FormalizeImagePath(source.FilePath, ImageTypes.Profile, ImageSizes.Original)
     });
 }
 /// <summary>
 /// Creates a cast result model from an external cast result.
 /// </summary>
 /// <param name="source">The source.</param>
 /// <param name="profileImageSize">Size of the profile image.</param>
 /// <returns>Cast result model</returns>
 public CastResultModel Create(CastResult source, ImageSizes profileImageSize = ImageSizes.Small)
 {
     return(new CastResultModel
     {
         Character = source.Character,
         Id = source.Id,
         Name = source.Name,
         Order = source.Order,
         ProfileImageUrl = FormalizeImagePath(source.ProfilePath, ImageTypes.Profile, profileImageSize),
         ProfileImageUrlOriginal = FormalizeImagePath(source.ProfilePath, ImageTypes.Profile, ImageSizes.Original)
     });
 }
Example #17
0
        public static string GetUploadedImagePath(this HtmlHelper html, ImageSizes size, Photo p)
        {
            if (p == null)
            {
                return(String.Empty);
            }

            string folder    = size.ToString();
            string extension = folder.IndexOf("png", StringComparison.OrdinalIgnoreCase) != -1 ? ".png" : ".jpg";

            return("/assets/images/" + folder + "/" + p.FileGuid + extension);
        }
        private EntryThumbContract CallGenerateThumbsAndMoveImage(ImageSizes sizes)
        {
            var thumb = new EntryThumbContract {
                EntryType = EntryType.SongList, FileName = "test.jpg"
            };

            using (var input = TestImage()) {
                target.GenerateThumbsAndMoveImage(input, thumb, sizes);
            }

            return(thumb);
        }
Example #19
0
        static void Main(string[] args)
        {
            if (args.Any(x => x.ToLower() != "repeating"))
            {
                Console.WriteLine("Welcome to image resizer.");
            }
            Console.WriteLine("Please provide the image directory/folder which needs to be resized:");
            var folderLocation = Console.ReadLine();

            if (!Directory.Exists(folderLocation))
            {
                Console.WriteLine("Invalid locatoin.");
                Main(new string[] { "repeating" });
                return;
            }
            Console.WriteLine("Enter comma separated sizes in pixels (desired height of image). e.g. 200, 300, 400, 1080 etc. We will keep the image aspect ratio same.");
            Console.WriteLine("Or choose from one/multiple of below values:");
            Console.WriteLine(string.Join(", ", Enum.GetNames(typeof(ImageSizes))));
            var sizes   = Console.ReadLine();
            var imgTool = new ImgTool();

            if (!string.IsNullOrEmpty(sizes) && sizes.Length > 0)
            {
                var sizeArr        = sizes.Split(new char[] { ',' });
                var files          = Directory.GetFiles(folderLocation, "*.jpg", SearchOption.TopDirectoryOnly);
                var numberOfImages = files.Length;

                Console.WriteLine($"Resizing {files.Length} images from the {folderLocation} folder.");
                foreach (var size in sizeArr)
                {
                    ImageSizes enumHeight = 0;
                    if (int.TryParse(size.Trim(), out int height) || Enum.TryParse(size.Trim(), out enumHeight))
                    {
                        height = enumHeight == 0 ? height : (int)enumHeight;
                        var folderName = enumHeight == 0 ? height.ToString() : Enum.GetName(typeof(ImageSizes), enumHeight);
                        Console.ForegroundColor = ConsoleColor.DarkGreen;
                        Console.WriteLine("Resizing images to " + height);
                        Console.ResetColor();
                        foreach (var file in files)
                        {
                            imgTool.ResizeAndSaveImage(file, height, folderName);
                            Console.WriteLine(file.Substring(file.LastIndexOf('\\') + 1) + " done.");
                        }
                    }
                }
            }
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine("Done resizing. Resized images are placed in folders {0} under directory {1}", sizes, folderLocation);
            Console.ResetColor();
            Console.WriteLine("Enter any key to exit.");
            Console.Read();
        }
Example #20
0
        /// <summary>
        /// Resize to defined size type and return image. x32 is height and weight = 32.
        /// </summary>
        /// <param name="base64"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static Image ResizeToImage(this string base64, ImageSizes size)
        {
            var bytes  = Convert.FromBase64String(base64);
            var stream = new MemoryStream(bytes, 0, bytes.Length);

            SetSize(size);
            _image = Image.FromStream(stream);
            stream.Flush();
            SetHeightWidth(_image);
            var resizedImage = _image.GetThumbnailImage((int)_width, (int)_height, () => false, IntPtr.Zero);

            return(resizedImage);
        }
Example #21
0
        private static string GetImageSuffix(ImageSizes imageSize)
        {
            switch (imageSize)
            {
            case ImageSizes.SmallHorizontal: return("sb.png");

            case ImageSizes.LargeHorizontal: return("lg.png");

            case ImageSizes.FullHorizontal: return("full.png:");

            case ImageSizes.FullVertical: return("vert.jpg");
            }
            return(null);
        }
        private static int GetSizePriority(XElement el)
        {
            var a = el.Attribute("size");

            if (a == null)
            {
                return(999);
            }
            var v = a.Value;

            if (ImageSizes.ContainsKey(v))
            {
                return(ImageSizes[v]);
            }
            return(999);
        }
Example #23
0
        public PartThumbnailWidget(PrintItemWrapper item, string noThumbnailFileName, string buildingThumbnailFileName, ImageSizes size)
        {
            ToolTipText    = "Click to show in 3D View".Localize();
            this.PrintItem = item;

            EnsureCorrectPartExtension();

            // Set Display Attributes
            this.Margin  = new BorderDouble(0);
            this.Padding = new BorderDouble(5);
            Size         = size;
            switch (size)
            {
            case ImageSizes.Size50x50:
                this.Width  = 50 * TextWidget.GlobalPointSizeScaleRatio;
                this.Height = 50 * TextWidget.GlobalPointSizeScaleRatio;
                break;

            case ImageSizes.Size115x115:
                this.Width  = 115 * TextWidget.GlobalPointSizeScaleRatio;
                this.Height = 115 * TextWidget.GlobalPointSizeScaleRatio;
                break;

            default:
                throw new NotImplementedException();
            }
            this.MinimumSize = new Vector2(this.Width, this.Height);

            this.BackgroundColor = normalBackgroundColor;
            this.Cursor          = Cursors.Hand;
            this.ToolTipText     = "Click to show in 3D View".Localize();

            // set background images
            if (noThumbnailImage.Width == 0)
            {
                StaticData.Instance.LoadIcon(noThumbnailFileName, noThumbnailImage);
                StaticData.Instance.LoadIcon(buildingThumbnailFileName, buildingThumbnailImage);
            }
            this.thumbnailImage = new ImageBuffer(buildingThumbnailImage);

            // Add Handlers
            this.Click            += DoOnMouseClick;
            this.MouseEnterBounds += onEnter;
            this.MouseLeaveBounds += onExit;
            ActiveTheme.Instance.ThemeChanged.RegisterEvent(ThemeChanged, ref unregisterEvents);
        }
        /// <summary>
        /// Gets the size of the image.
        /// </summary>
        /// <param name="sizes">The sizes.</param>
        /// <param name="imageSize">Size of the image.</param>
        /// <returns>Image size</returns>
        private string GetImageSize(List <string> sizes, ImageSizes imageSize)
        {
            var middleIndex = (int)Math.Floor((decimal)(sizes.Count / 2));

            var returnIndex = middleIndex + (int)imageSize;

            if (returnIndex < 0)
            {
                returnIndex = 0;
            }
            else if (returnIndex > (sizes.Count - 1))
            {
                returnIndex = sizes.Count - 1;
            }

            return(sizes[returnIndex]);
        }
		public PartThumbnailWidget(PrintItemWrapper item, string noThumbnailFileName, string buildingThumbnailFileName, ImageSizes size)
		{
			ToolTipText = "Click to show in 3D View".Localize();
			this.ItemWrapper = item;

			// Set Display Attributes
			this.Margin = new BorderDouble(0);
			this.Padding = new BorderDouble(5);
			Size = size;
			switch (size)
			{
				case ImageSizes.Size50x50:
					this.Width = 50 * GuiWidget.DeviceScale;
					this.Height = 50 * GuiWidget.DeviceScale;
					break;

				case ImageSizes.Size115x115:
					this.Width = 115 * GuiWidget.DeviceScale;
					this.Height = 115 * GuiWidget.DeviceScale;
					break;

				default:
					throw new NotImplementedException();
			}
			this.MinimumSize = new Vector2(this.Width, this.Height);

			this.BackgroundColor = normalBackgroundColor;
			this.Cursor = Cursors.Hand;
			this.ToolTipText = "Click to show in 3D View".Localize();

			// set background images
			if (noThumbnailImage.Width == 0)
			{
				StaticData.Instance.LoadIcon(noThumbnailFileName, noThumbnailImage);
				noThumbnailImage.InvertLightness();
				StaticData.Instance.LoadIcon(buildingThumbnailFileName, buildingThumbnailImage);
				buildingThumbnailImage.InvertLightness();
			}
			this.thumbnailImage = new ImageBuffer(buildingThumbnailImage);

			// Add Handlers
			this.Click += DoOnMouseClick;
			this.MouseEnterBounds += onEnter;
			this.MouseLeaveBounds += onExit;
			ActiveTheme.ThemeChanged.RegisterEvent(ThemeChanged, ref unregisterEvents);
		}
Example #26
0
        /// <summary>
        /// Constructor for simply tracking a pre-registered image.
        /// Because it was not created here, Image will not be disposed of in IDispose.Dispose().</summary>
        /// <param name="id">Image identifier</param>
        /// <param name="size">Image size</param>
        public EmbeddedImage(string id, ImageSizes size)
        {
            m_isOwner = false;
            m_id = id;
            switch (size)
            {
                case ImageSizes.e16x16: Image = ResourceUtil.GetImage16(id); break;
                case ImageSizes.e24x24: Image = ResourceUtil.GetImage24(id); break;
                case ImageSizes.e32x32: Image = ResourceUtil.GetImage32(id); break;

                default:
                    throw new ArgumentException("Invalid size specified");
            }

            if (Image == null)
                throw new ArgumentException("No image registered with this id and size");
        }
Example #27
0
        public PartThumbnailWidget(PrintItemWrapper item, string noThumbnailFileName, string buildingThumbnailFileName, ImageSizes size)
        {
            ToolTipText      = "Click to show in 3D View".Localize();
            this.ItemWrapper = item;

            // Set Display Attributes
            this.Margin  = new BorderDouble(0);
            this.Padding = new BorderDouble(5);
            Size         = size;
            switch (size)
            {
            case ImageSizes.Size50x50:
                this.Width  = 50 * GuiWidget.DeviceScale;
                this.Height = 50 * GuiWidget.DeviceScale;
                break;

            case ImageSizes.Size115x115:
                this.Width  = 115 * GuiWidget.DeviceScale;
                this.Height = 115 * GuiWidget.DeviceScale;
                break;

            default:
                throw new NotImplementedException();
            }
            this.MinimumSize = new Vector2(this.Width, this.Height);

            this.BackgroundColor = normalBackgroundColor;
            this.Cursor          = Cursors.Hand;
            this.ToolTipText     = "Click to show in 3D View".Localize();

            // set background images
            if (noThumbnailImage.Width == 0)
            {
                StaticData.Instance.LoadIcon(noThumbnailFileName, noThumbnailImage);
                noThumbnailImage.InvertLightness();
                StaticData.Instance.LoadIcon(buildingThumbnailFileName, buildingThumbnailImage);
                buildingThumbnailImage.InvertLightness();
            }
            this.thumbnailImage = new ImageBuffer(buildingThumbnailImage);

            // Add Handlers
            this.Click            += DoOnMouseClick;
            this.MouseEnterBounds += onEnter;
            this.MouseLeaveBounds += onExit;
        }
 public void SetImageSize(Uri url, int width, int height, ImageSizes deviceType)
 {
     ImageDefaults imageDefault = _imageConfigurationRepository.Get(url.ToString());
     if (imageDefault != null)
     {
         if (imageDefault.ImageSizes.ContainsKey(deviceType))
             imageDefault.ImageSizes[deviceType] = new Tuple<int, int>(width, height);
         else
             imageDefault.ImageSizes.Add(deviceType, new Tuple<int, int>(width, height));
     }
     else
     {
         imageDefault = new ImageDefaults { Url = url.ToString() };
         imageDefault.ImageSizes.Add(deviceType, new Tuple<int, int>(width, height));
     }
     _imageConfigurationRepository.Save(imageDefault);
     _savedImages.Remove(url.ToString(), SAVED_IMAGE_SECTION);
 }
Example #29
0
        public static string GetCachedImagePath(string uri, ImageSizes imageSize)
        {
            if (uri == null)
            {
                return(null);
            }

            string rootPath   = Directory.GetParent(Application.dataPath).FullName;
            string uriDir     = Path.GetDirectoryName(uri);
            string cachedPath = Path.Combine(Path.Combine(rootPath, CachedRelativePaths[imageSize]), uriDir);

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

            return(Path.Combine(rootPath, Path.Combine(CachedRelativePaths[imageSize], uri)));
        }
Example #30
0
        public virtual string GetSizeName(string fileName)
        {
            int separatorIndex;
            int dotIndex;

            if (!TryGetSeparatorAndDotIndex(fileName, out separatorIndex, out dotIndex))
            {
                return(null);
            }

            var sizeName = fileName.Substring(separatorIndex + 1, dotIndex - separatorIndex - 1);

            if (!ImageSizes.Contains(sizeName))
            {
                return(null);
            }

            return(sizeName);
        }
Example #31
0
        public PartThumbnailWidget(PrintItemWrapper item, string noThumbnailFileName, string buildingThumbnailFileName, ImageSizes size)
        {
            this.PrintItem = item;

            // Set Display Attributes
            this.Margin  = new BorderDouble(0);
            this.Padding = new BorderDouble(5);
            Size         = size;
            switch (size)
            {
            case ImageSizes.Size50x50:
                this.Width       = 50;
                this.Height      = 50;
                this.MinimumSize = new Vector2(50, 50);
                break;

            case ImageSizes.Size115x115:
                this.Width       = 115;
                this.Height      = 115;
                this.MinimumSize = new Vector2(115, 115);
                break;

            default:
                throw new NotImplementedException();
            }

            this.BackgroundColor = normalBackgroundColor;
            this.Cursor          = Cursors.Hand;

            // set background images
            if (noThumbnailImage.Width == 0)
            {
                ImageIO.LoadImageData(this.GetImageLocation(noThumbnailFileName), noThumbnailImage);
                ImageIO.LoadImageData(this.GetImageLocation(buildingThumbnailFileName), buildingThumbnailImage);
            }
            this.tumbnailImage = new ImageBuffer(buildingThumbnailImage);

            // Add Handlers
            this.Click            += new ButtonEventHandler(onMouseClick);
            this.MouseEnterBounds += new EventHandler(onEnter);
            this.MouseLeaveBounds += new EventHandler(onExit);
            ActiveTheme.Instance.ThemeChanged.RegisterEvent(onThemeChanged, ref unregisterEvents);
        }
		/// <summary>
		/// Generates thumbnails and writes the original file into external image files.
		/// </summary>
		public void GenerateThumbsAndMoveImage(Stream input, IEntryImageInformation imageInfo, ImageSizes imageSizes, int originalSize = Unlimited) {

			using (var original = ImageHelper.OpenImage(input)) {

				if (imageSizes.HasFlag(ImageSizes.Original))
					GenerateThumbAndMoveImage(original, input, imageInfo, ImageSize.Original, originalSize);

				if (imageSizes.HasFlag(ImageSizes.Thumb))
					GenerateThumbAndMoveImage(original, input, imageInfo, ImageSize.Thumb, ImageHelper.DefaultThumbSize);

				if (imageSizes.HasFlag(ImageSizes.SmallThumb))
					GenerateThumbAndMoveImage(original, input, imageInfo, ImageSize.SmallThumb, ImageHelper.DefaultSmallThumbSize);

				if (imageSizes.HasFlag(ImageSizes.TinyThumb))
					GenerateThumbAndMoveImage(original, input, imageInfo, ImageSize.TinyThumb, ImageHelper.DefaultTinyThumbSize);

			}

		}
        /// <summary>
        /// Constructor for simply tracking a pre-registered image.
        /// Because it was not created here, Image will not be disposed of in IDispose.Dispose().</summary>
        /// <param name="id">Image identifier</param>
        /// <param name="size">Image size</param>
        public EmbeddedImage(string id, ImageSizes size)
        {
            m_isOwner = false;
            m_id      = id;
            switch (size)
            {
            case ImageSizes.e16x16: Image = ResourceUtil.GetImage16(id); break;

            case ImageSizes.e24x24: Image = ResourceUtil.GetImage24(id); break;

            case ImageSizes.e32x32: Image = ResourceUtil.GetImage32(id); break;

            default:
                throw new ArgumentException("Invalid size specified");
            }

            if (Image == null)
            {
                throw new ArgumentException("No image registered with this id and size");
            }
        }
Example #34
0
        private static string GetImageUrl(ImageSizes size, XmlDocument doc)
        {
            if (doc == null)
            {
                return(null);
            }
            XmlNodeList elemList = doc.GetElementsByTagName("image");

            for (int i = 0; i < elemList.Count; i++)
            {
                if (elemList[i].Attributes == null)
                {
                    continue;
                }
                if (elemList[i].Attributes.Cast <XmlAttribute>().Any(attr => attr.Value == size.ToString().ToLower()))
                {
                    return(elemList[i].InnerText);
                }
            }

            return(null);
        }
Example #35
0
        /// <summary>
        /// Sets size
        /// </summary>
        /// <param name="size"></param>
        private static void SetSize(ImageSizes size)
        {
            switch (size)
            {
            case ImageSizes.x32:
                _height = 32;
                _width  = 32;
                break;

            case ImageSizes.x64:
                _height = 64;
                _width  = 64;
                break;

            case ImageSizes.x128:
                _height = 128;
                _width  = 128;
                break;

            case ImageSizes.x150:
                _height = 150;
                _width  = 150;
                break;

            case ImageSizes.x256:
                _height = 256;
                _width  = 256;
                break;

            case ImageSizes.x800:
                _height = 800;
                _width  = 800;
                break;

            default:
                throw new Exception("Invalid size.");
            }
        }
Example #36
0
        public virtual IList <File> GetFiles()
        {
            try
            {
                List <File> files = new List <File>();

                var fileMap = new Dictionary <string, File>(StringComparer.OrdinalIgnoreCase);
                foreach (var fd in FileSystem.GetFiles(LocalUrl))
                {
                    var file = new File(fd, this);
                    file.Set(FileSystem);
                    file.Set(ImageSizes);

                    var unresizedFileName = ImageSizes.RemoveImageSize(file.Name);
                    if (unresizedFileName != null && fileMap.ContainsKey(unresizedFileName))
                    {
                        fileMap[unresizedFileName].Add(file);

                        if (ImageSizes.GetSizeName(file.Name) == "icon")
                        {
                            file.IsIcon = true;
                        }
                    }
                    else
                    {
                        files.Add(file);
                        fileMap[file.Name] = file;
                    }
                }
                files.Sort(new TitleComparer <File>());
                return(files);
            }
            catch (DirectoryNotFoundException ex)
            {
                Engine.Logger.Warn(ex);
                return(new List <File>());
            }
        }
Example #37
0
        private async static Task<bool> scaleImage(Stream blobInput, CloudBlockBlob blobOutput, ImageSizes imageSize, string contentType)
        {
            bool retVal = true; //Assume success

            try
            {
                using (Stream output = blobOutput.OpenWrite())
                {
                    if (doScaling(blobInput, output, imageSize))
                    {
                        blobOutput.Properties.ContentType = contentType;
                    }
                    else
                        retVal = false;
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Error while scaling image: " + ex.Message);
                retVal = false;
            }

            return retVal;
        }
 protected int Convert(ImageSizes item)
 {
     switch (item)
     {
         case ImageSizes.Web:
             return 67;
         case ImageSizes.Small:
             return 64;
         case ImageSizes.Medium:
             return 561;
         case ImageSizes.Lagest:
             return 559;
         default:
             throw new NotImplementedException();
     }
 }
Example #39
0
        private async static Task <bool> scaleImage(Stream blobInput, CloudBlockBlob blobOutput, ImageSizes imageSize, string contentType)
        {
            bool retVal = true; //Assume success

            try
            {
                using (Stream output = blobOutput.OpenWrite())
                {
                    if (doScaling(blobInput, output, imageSize))
                    {
                        blobOutput.Properties.ContentType = contentType;
                    }
                    else
                    {
                        retVal = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Error while scaling image: " + ex.Message);
                retVal = false;
            }

            return(retVal);
        }
		public PartThumbnailWidget(PrintItemWrapper item, string noThumbnailFileName, string buildingThumbnailFileName, ImageSizes size)
		{
			this.PrintItem = item;

			EnsureCorrectPartExtension();

			// Set Display Attributes
			this.Margin = new BorderDouble(0);
			this.Padding = new BorderDouble(5);
			Size = size;
			switch (size)
			{
				case ImageSizes.Size50x50:
					this.Width = 50 * TextWidget.GlobalPointSizeScaleRatio;
					this.Height = 50 * TextWidget.GlobalPointSizeScaleRatio;
					break;

				case ImageSizes.Size115x115:
					this.Width = 115 * TextWidget.GlobalPointSizeScaleRatio;
					this.Height = 115 * TextWidget.GlobalPointSizeScaleRatio;
					break;

				default:
					throw new NotImplementedException();
			}
			this.MinimumSize = new Vector2(this.Width, this.Height);

			this.BackgroundColor = normalBackgroundColor;
			this.Cursor = Cursors.Hand;

			// set background images
			if (noThumbnailImage.Width == 0)
			{
				StaticData.Instance.LoadIcon(noThumbnailFileName, noThumbnailImage);
				StaticData.Instance.LoadIcon(buildingThumbnailFileName, buildingThumbnailImage);
			}
			this.thumbnailImage = new ImageBuffer(buildingThumbnailImage);

			// Add Handlers
			this.Click += new EventHandler(OnMouseClick);
			this.MouseEnterBounds += new EventHandler(onEnter);
			this.MouseLeaveBounds += new EventHandler(onExit);
			ActiveTheme.Instance.ThemeChanged.RegisterEvent(ThemeChanged, ref unregisterEvents);
		}
Example #41
0
        private static bool doScaling(Stream blobInput, Stream output, ImageSizes imageSize)
        {
            bool retVal = true; //Assume success

            try
            {
                int width = 0, height = 0;

                //TODO: get original image aspect ratio, get "priority property" (width) and calculate new height...
                switch (imageSize)
                {
                    case Medium:
                        width = 800;
                        height = 480;
                        break;
                    case Large:
                        width = 1024;
                        height = 768;
                        break;
                    case ExtraSmall:
                        width = 320;
                        height = 200;
                        break;
                    case Small:
                        width = 640;
                        height = 400;
                        break;
                }

                using (Image img = Image.FromStream(blobInput))
                {
                    //Calculate aspect ratio and new heights of scaled image
                    var widthRatio = (double)width / (double)img.Width;
                    var heightRatio = (double)height / (double)img.Height;
                    var minAspectRatio = Math.Min(widthRatio, heightRatio);
                    if (minAspectRatio > 1)
                    {
                        width = img.Width;
                        height = img.Height;
                    }
                    else
                    {
                        width = (int)(img.Width * minAspectRatio);
                        height = (int)(img.Height * minAspectRatio);
                    }

                    using (Bitmap bitmap = new Bitmap(img, width, height))
                    {
                        bitmap.Save(output, img.RawFormat);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Error while saving scaled image: " + ex.Message);
                retVal = false;
            }

            return retVal;
        }
Example #42
0
 public DisplayImage(Guid fileKey, string title, ImageSizes imageSize)
 {
     FileKey = fileKey;
     Title = title;
     ImageSize = imageSize;
 }