Image

We found 10 examples in language CSharp for this search. You will see 44 fragments of code.

Other methods


        /// <summary>
        /// Изображение 16x16
        /// </summary>
        /// <param name="value">Расчетный счет</param>
        /// <returns></returns>
        public static Bitmap GetImage(this Ruleset value)
        {
            Bitmap image = ResourceImage.GetByCode(value.Workarea, ResourceImage.RULESET_X16);
            if (value.StateId == State.STATEDELETED)
                image = GetImageDeleted(value.Workarea, image);
            return image;
        }

        /// <summary>
        /// Изображение 16x16
        /// </summary>
        /// <param name="value">Расчетный счет</param>
        /// <returns></returns>
        public static Bitmap GetImage(this AgentBankAccount value)
        {
            Bitmap image = ResourceImage.GetByCode(value.Workarea, ResourceImage.MONEY_X16);
            if (value.StateId == State.STATEDELETED)
                image = GetImageDeleted(value.Workarea, image);
            return image;
        }
        /// <summary>
        /// Изображение 16x16
        /// </summary>
        /// <param name="value">Наименование набора</param>
        /// <returns></returns>
        public static Bitmap GetImage(this ProductRecipe value)
        {
            Bitmap image = ResourceImage.GetByCode(value.Workarea, ResourceImage.CUBEGREEN_X16);
            if (value.StateId == State.STATEDELETED)
                image = GetImageDeleted(value.Workarea, image);
            return image;
        }

        /// <summary>
        /// Изображение 16x16
        /// </summary>
        /// <param name="value">Колонка</param>
        /// <returns></returns>
        public static Bitmap GetImage(this CustomViewColumn value)
        {
            Bitmap image = ResourceImage.GetByCode(value.Workarea, ResourceImage.COLUMN_X16);
            if (value.StateId == State.STATEDELETED)
                image = GetImageDeleted(value.Workarea, image);
            return image;
        }

        /// <summary>
        /// Изображение 16x16
        /// </summary>
        /// <param name="value">Графические ресурсы</param>
        /// <returns></returns>
        public static Bitmap GetImage(this ResourceImage value)
        {
            Bitmap image = ResourceImage.GetByCode(value.Workarea, ResourceImage.IMAGE_X16);
            if (value.StateId == State.STATEDELETED)
                image = GetImageDeleted(value.Workarea, image);
            return image;
        }

        /// <summary>
        /// Изображение 16x16
        /// </summary>
        /// <param name="value">Элемент проекта</param>
        /// <returns></returns>
        public static Bitmap GetImage(this PriceValue value)
        {
            Bitmap image = ResourceImage.GetByCode(value.Workarea, ResourceImage.PRICEUAH_X16);
            if (value.StateId == State.STATEDELETED)
                image = GetImageDeleted(value.Workarea, image);
            return image;
        }


        public static Image ConvertBytesToImage(byte[] bytes)
        {
            return Image.FromStream(new MemoryStream(bytes, 0, bytes.Length), true);
        }

        public static Image ConvertStreamToImage(Stream stream)
        {
            return Image.FromStream(stream);
        }

        public static Bitmap ResizeImage(Image image, int width, int height)
        {
            return ResizeImage(image, width, height, 0);
        }

        public static Bitmap SquareImage(byte[] image)
        {
            return SquareImage(ConvertBytesToImage(image));
        }


		public void Recalc()
		{
			if (Link == null) return;

			#region Image
			Image = null;
			if (Link.Banner.Enable && Link.Banner.DisplayedImage != null)
				Image = Link.Banner.DisplayedImage;
			else if (Link.Thumbnail.Enable && Link.Thumbnail.Image != null)
				Image = Link.Thumbnail.Image;
			else if (FormatState.ShowCategoryTags && Link.Tags.HasCategories)
				Image = Properties.Resources.TagsWidgetCategories;
			else if (FormatState.ShowSuperFilterTags && Link.Tags.HasSuperFilters)
				Image = Properties.Resources.TagsWidgetSuperFIlters;
			else if (FormatState.ShowKeywordTags && Link.Tags.HasKeywords)
				Image = Properties.Resources.TagsWidgetKeywords;
			else if (FormatState.ShowSecurityTags && Link.Security.HasSecuritySettings)
			{
				if (Link.Security.IsForbidden)
					Image = Properties.Resources.TagsWidgetSecurityHidden;
				else if (Link.Security.NoShare)
					Image = Properties.Resources.TagsWidgetSecurityLocal;
				else if (Link.Security.IsRestricted)
				{
					if (!String.IsNullOrEmpty(Link.Security.AssignedUsers))
						Image = Properties.Resources.TagsWidgetSecurityWhiteList;
					else if (!String.IsNullOrEmpty(Link.Security.DeniedUsers))
						Image = Properties.Resources.TagsWidgetSecurityBlackList;
				}
			}

			if (Image == null && !Link.Widget.Disabled)
				Image = Link.Widget.DisplayedImage;
			#endregion

			#region Text
			Text = !String.IsNullOrEmpty(Link.DisplayName) ? Link.DisplayName : String.Empty;
			WordWrap = Link.Settings.TextWordWrap;
			#endregion

			#region Font
			if (Link.DisplayFont != null)
			{
				Font = Link.DisplayFont;
			}
			else if (Link is LibraryObjectLink)
			{
				var objectLinkSettings = (LibraryObjectLinkSettings)Link.Settings;

				if (objectLinkSettings.DisplayAsBold)
				{
					Font = _parent.FolderBox.BoldRowFont;
				}
				else
				{
					switch (objectLinkSettings.RegularFontStyle)
					{
						case (FontStyle.Bold | FontStyle.Italic | FontStyle.Underline):
							Font = _parent.FolderBox.BoldItalicUndrerlineRowFont;
							break;
						case (FontStyle.Bold | FontStyle.Italic):
							Font = _parent.FolderBox.BoldItalicRowFont;
							break;
						case (FontStyle.Italic | FontStyle.Underline):
							Font = _parent.FolderBox.ItalicUnderlineRowFont;
							break;
						case (FontStyle.Bold | FontStyle.Underline):
							Font = _parent.FolderBox.BoldUnderlineRowFont;
							break;
						case FontStyle.Bold:
							Font = _parent.FolderBox.BoldRowFont;
							break;
						case FontStyle.Italic:
							Font = _parent.FolderBox.ItalicRowFont;
							break;
						case FontStyle.Underline:
							Font = _parent.FolderBox.UnderlineRowFont;
							break;
						default:
							Font = _parent.FolderBox.RegularRowFont;
							break;
					}
				}
			}
			else
				Font = _parent.FolderBox.RegularRowFont;
			#endregion

			#region Fore Color
			ForeColor = Link.DisplayColor;
			#endregion

			#region Image Size and Coordinates
			int imageLeft;
			int imageTop;
			int imageWidth;
			int imageHeight;
			if (Link.Banner.Enable && Link.Banner.DisplayedImage != null)
			{
				if (Link.Banner.TextEnabled)
				{
					imageLeft = 0;
				}
				else
				{
					switch (Link.Banner.ImageAlignement)
					{
						case HorizontalAlignment.Left:
							imageLeft = 0;
							break;
						case HorizontalAlignment.Center:
							imageLeft = (_parent.DataGridView.Width - Link.Banner.DisplayedImage.Width) / 2;
							if (imageLeft < 0)
								imageLeft = 0;
							break;
						case HorizontalAlignment.Right:
							imageLeft = _parent.DataGridView.Width - Link.Banner.DisplayedImage.Width;
							if (imageLeft < 0)
								imageLeft = 0;
							break;
						default:
							imageLeft = 0;
							break;
					}
				}
				imageWidth = Link.Banner.DisplayedImage.Width;
				imageHeight = Link.Banner.DisplayedImage.Height;
			}
			else if (Link.Thumbnail.Enable && Link.Thumbnail.Image != null)
			{
				imageWidth = Link.Thumbnail.Image.Width;
				imageHeight = Link.Thumbnail.Image.Height;
				switch (Link.Thumbnail.ImageAlignement)
				{
					case HorizontalAlignment.Left:
						imageLeft = 0;
						break;
					case HorizontalAlignment.Center:
						imageLeft = (_parent.DataGridView.Width - Link.Thumbnail.Image.Width) / 2;
						if (imageLeft < 0)
							imageLeft = 0;
						break;
					case HorizontalAlignment.Right:
						imageLeft = _parent.DataGridView.Width - Link.Thumbnail.Image.Width;
						if (imageLeft < 0)
							imageLeft = 0;
						break;
					default:
						imageLeft = 0;
						break;
				}
			}
			else if ((FormatState.ShowCategoryTags ||
					FormatState.ShowKeywordTags ||
					FormatState.ShowSuperFilterTags ||
					FormatState.ShowSecurityTags
					) &&
				(Link.Security.HasSecuritySettings || Link.Tags.HasTags) &&
				Image != null)
			{
				imageLeft = 0;
				imageWidth = DefaultImageWidth;
				imageHeight = DefaultImageHeight;
			}
			else if (!Link.Widget.Disabled && Link.Widget.DisplayedImage != null)
			{
				imageLeft = WidthMargin;
				imageWidth = Link.Widget.DisplayedImage.Width > DefaultImageWidth ? Link.Widget.DisplayedImage.Width : DefaultImageWidth;
				imageHeight = Link.Widget.DisplayedImage.Height > DefaultImageHeight ? Link.Widget.DisplayedImage.Height : DefaultImageHeight;
			}
			else
			{
				imageLeft = 0;
				imageWidth = 0;
				imageHeight = DefaultImageHeight;
			}
			#endregion

			#region Text Size and Coordinates
			int textLeft = 0;
			int textTop;
			int textWidth;
			int textHeight;

			var textForCalculation = Text;
			using (var g = Graphics.FromImage(new Bitmap(1, 1)))
			{
				if (Link.Thumbnail.Enable && Link.Thumbnail.Image != null)
				{
					var fontForSizeCalculation = Font;
					var textSize = g.MeasureString(
						textForCalculation,
						fontForSizeCalculation,
						new Size(Int32.MaxValue, Int32.MaxValue));
					textWidth = (Int32)Math.Ceiling(textSize.Width);
					textHeight = (Int32)Math.Ceiling(textSize.Height);
					switch (Link.Thumbnail.TextAlignement)
					{
						case HorizontalAlignment.Left:
							if (Link.Thumbnail.ImageAlignement == HorizontalAlignment.Center && textWidth > imageWidth)
								textLeft = imageLeft + Link.Thumbnail.ImagePadding + imageWidth / 2 - textWidth / 2;
							else
								textLeft = imageLeft + Link.Thumbnail.ImagePadding;
							if (textLeft < Link.Thumbnail.ImagePadding)
								textLeft = Link.Thumbnail.ImagePadding;
							if (Link.Thumbnail.ImageAlignement == HorizontalAlignment.Right &&
								textLeft + textWidth > _parent.DataGridView.Width)
								textLeft = _parent.DataGridView.Width - textWidth;
							break;
						case HorizontalAlignment.Center:
							textLeft = imageLeft + (imageWidth - textWidth) / 2;
							if (textLeft < Link.Thumbnail.ImagePadding)
								textLeft = Link.Thumbnail.ImagePadding;
							if (Link.Thumbnail.ImageAlignement == HorizontalAlignment.Right &&
								textLeft + textWidth > _parent.DataGridView.Width)
								textLeft = _parent.DataGridView.Width - textWidth;
							break;
						case HorizontalAlignment.Right:
							if (Link.Thumbnail.ImageAlignement == HorizontalAlignment.Center && textWidth > imageWidth)
								textLeft = imageLeft + Link.Thumbnail.ImagePadding + imageWidth / 2 - textWidth / 2;
							else
								textLeft = imageLeft + imageWidth - textWidth;
							if (textLeft < Link.Thumbnail.ImagePadding)
								textLeft = Link.Thumbnail.ImagePadding;
							if (Link.Thumbnail.ImageAlignement == HorizontalAlignment.Right &&
								textLeft + textWidth > _parent.DataGridView.Width)
								textLeft = _parent.DataGridView.Width - textWidth;
							break;
					}
				}
				else
				{
					var fontForSizeCalculation = new Font(
						Font.FontFamily,
						(Int32)Math.Ceiling(Font.Size),
						FontStyle.Bold | FontStyle.Italic | FontStyle.Underline,
						GraphicsUnit.Point);
					var textSize = g.MeasureString(
						textForCalculation,
						fontForSizeCalculation,
						new Size(WordWrap ? _parent.DataGridView.Width - imageWidth - WidthMargin : Int32.MaxValue, Int32.MaxValue));
					textWidth = (Int32)Math.Ceiling(textSize.Width);
					textHeight = (Int32)Math.Ceiling(textSize.Height);
					textLeft = imageLeft + imageWidth + WidthMargin;
				}
			}
			#endregion

			#region Correct Image and text coordinates
			if (Link.Thumbnail.Enable &&
				Link.Thumbnail.Image != null &&
				!String.IsNullOrEmpty(Text))
			{
				imageTop = 0;
				textTop = 0;
				switch (Link.Thumbnail.TextPosition)
				{
					case ThumbnailTextPosition.Top:
						textTop = 0;
						imageTop = textTop + textHeight + HeightMargin;
						break;
					case ThumbnailTextPosition.Bottom:
						imageTop = 0;
						textTop = imageTop + imageHeight + HeightMargin;
						break;
				}

				if (Link.Thumbnail.ImageAlignement == HorizontalAlignment.Center &&
					Link.Thumbnail.TextAlignement != HorizontalAlignment.Center &&
					textWidth > imageWidth)
				{
					switch (Link.Thumbnail.TextAlignement)
					{
						case HorizontalAlignment.Left:
							imageLeft = textLeft - Link.Thumbnail.ImagePadding;
							break;
						case HorizontalAlignment.Right:
							imageLeft = textLeft + textWidth - imageWidth - Link.Thumbnail.ImagePadding;
							break;
					}
				}
			}
			else if (textHeight > imageHeight)
			{
				textTop = 0;
				if (Link != null && Link.Banner.Enable)
					imageTop = Link.Banner.ImageVerticalAlignement == VerticalAlignment.Top ? 0 : (textHeight - imageHeight) / 2;
				else
					imageTop = WordWrap ? 0 : (textHeight - imageHeight) / 2;
			}
			else if (textHeight == imageHeight)
			{
				textTop = 0;
				imageTop = 0;
			}
			else
			{
				if (Link != null && Link.Banner.Enable)
					textTop = Link.Banner.ImageVerticalAlignement == VerticalAlignment.Top ? 0 : (imageHeight - textHeight) / 2;
				else
					textTop = (imageHeight - textHeight) / 2;
				imageTop = 0;
			}
			#endregion

			ImageBorder = new Rectangle(imageLeft, imageTop, imageWidth, imageHeight);
			TextBorder = new Rectangle(textLeft, textTop, textWidth, textHeight);

			int newRowWidth;
			int newRowHeight;
			if (Link.Thumbnail.Enable &&
				Link.Thumbnail.Image != null &&
				!String.IsNullOrEmpty(Text))
			{
				newRowWidth = Math.Max(ImageBorder.Width, TextBorder.Width);
				newRowHeight = textHeight + imageHeight + HeightMargin;
			}
			else
			{
				newRowWidth = ImageBorder.Width + TextBorder.Width;
				newRowHeight = Math.Max(textHeight, imageHeight);
			}

			switch (_parent.FolderBox.FormatState.RowSpace)
			{
				case 2:
					newRowHeight += 5;
					break;
				case 3:
					newRowHeight += 10;
					break;
			}

			if (newRowWidth != RowWidth ||
				newRowHeight != RowHeight)
			{
				RowWidth = newRowWidth;
				RowHeight = newRowHeight;
				_parent.OnInfoChanged();
			}

			_parent.Cells[0].Value = Text;
			_parent.Height = RowHeight;
		}

		public void Dispose()
		{
			_parent = null;
		}


		public static Point GetCenter(this Rectangle control)
		{
			return new Point(control.X + control.Width / 2, control.Y + control.Height / 2);
		}

		public static Point GetOffset(this Point point, int x, int y)
		{
			return new Point(point.X + x, point.Y + y);
		}

		public static Image Resize(this Image image, Size size)
		{
			var originalWidth = image.Width;
			var originalHeight = image.Height;
			var percentWidth = originalWidth != size.Width ? (float)size.Width / originalWidth : float.PositiveInfinity;
			var percentHeight = originalHeight != size.Height ? (float)size.Height / originalHeight : float.PositiveInfinity;
			var percent = Math.Min(percentHeight, percentWidth);
			if (float.IsInfinity(percent))
				percent = 1;
			else if (percent > 1)
				return image;
			var newWidth = (int)(originalWidth * percent);
			var newHeight = (int)(originalHeight * percent);
			Image newImage = new Bitmap(newWidth, newHeight);
			using (var graphicsHandle = Graphics.FromImage(newImage))
			{
				graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
				graphicsHandle.DrawImage(
					image,
					0,
					0,
					newWidth,
					newHeight);
			}
			return newImage;
		}

		public static Image DrawPadding(this Image image, Padding padding)
		{
			Image newImage = new Bitmap(
				image.Width + padding.Left + padding.Right,
				image.Height + padding.Top + padding.Bottom
				);
			using (var graphicsHandle = Graphics.FromImage(newImage))
			{
				graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
				graphicsHandle.DrawImage(
					image,
					0 + padding.Left,
					0 + padding.Top,
					image.Width,
					image.Height);
			}
			return newImage;
		}

		public static Image DrawBorder(this Image image, int borderSize = 1, Color? borderColor = null)
		{
			if (!borderColor.HasValue)
				borderColor = Color.Black;
			var originalWidth = image.Width;
			var originalHeight = image.Height;
			var newWidth = originalWidth + borderSize * 2;
			var newHeight = originalHeight + borderSize * 2;
			Image newImage = new Bitmap(newWidth, newHeight);
			using (var graphicsHandle = Graphics.FromImage(newImage))
			{
				graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
				graphicsHandle.DrawImage(
					image,
					borderSize,
					borderSize,
					originalWidth,
					originalHeight);
				using (var pen = new Pen(borderColor.Value, borderSize))
					graphicsHandle.DrawRectangle(pen, borderSize / 2, borderSize / 2, originalWidth + borderSize,
						originalHeight + borderSize);
			}
			return newImage;
		}

		public static Image DrawShadow(this Image image, int shadowSize = 1, Color? shadowColor = null)
		{
			if (!shadowColor.HasValue)
				shadowColor = Color.Black;
			var originalWidth = image.Width;
			var originalHeight = image.Height;
			var newWidth = originalWidth + shadowSize;
			var newHeight = originalHeight + shadowSize;
			Image newImage = new Bitmap(newWidth, newHeight);
			using (var graphicsHandle = Graphics.FromImage(newImage))
			{
				var alphaIncreemet = 32 / shadowSize;
				var alpha = alphaIncreemet;
				for (var shadowX = 0; shadowX < shadowSize; shadowX++)
				{
					using (Brush brush = new SolidBrush(Color.FromArgb(alpha, shadowColor.Value)))
						graphicsHandle.FillRectangle(
							brush,
							shadowX,
							shadowSize - shadowX,
							originalWidth,
							originalHeight);
					alpha += alphaIncreemet;
				}

				graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
				graphicsHandle.DrawImage(
					image,
					shadowSize,
					0,
					originalWidth,
					originalHeight);
			}
			return newImage;
		}

        #region 缩略图
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径(物理路径)</param>
        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>    
        public static Image Thumbnail(this Image originalImage, int width = 100, int height = 100, string mode = "Cut")
        {
            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW":  //指定高宽缩放(可能变形)                
                    break;
                case "W":   //指定宽,高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H":   //指定高,宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut": //指定高宽裁减(不变形)                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);

            return bitmap;
            //try
            //{
            //    //以jpg格式保存缩略图
            //    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            //}
            //catch (System.Exception e)
            //{
            //    throw e;
            //}
            //finally
            //{
            //    originalImage.Dispose();
            //    bitmap.Dispose();
            //    g.Dispose();
            //}
        }

        /// <summary>
        /// 获取所有图片格式
        /// </summary>
        /// <returns></returns>
        private static Dictionary<String, ImageFormat> GetImageFormats()
        {
            var dic = new Dictionary<String, ImageFormat>();
            var properties = typeof(ImageFormat).GetProperties(BindingFlags.Static | BindingFlags.Public);
            foreach (var property in properties)
            {
                var format = property.GetValue(null, null) as ImageFormat;
                if (format == null) continue;
                dic.Add(("." + property.Name).ToUpper(), format);
            }
            return dic;
        }
        /// <summary>
        /// 根据图像获取图像的扩展名
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static String GetExtension(this Image image)
        {
            foreach (var pair in ImageFormats)
            {
                if (pair.Value.Guid == image.RawFormat.Guid)
                {
                    return pair.Key;
                }
            }
            throw new BadImageFormatException();
        }
        private static SortedDictionary<int, ImageType> InitImageTag()
        {
            SortedDictionary<int, ImageType> list = new SortedDictionary<int, ImageType>();

            list.Add((int)ImageType.BMP, ImageType.BMP);
            list.Add((int)ImageType.JPG, ImageType.JPG);
            list.Add((int)ImageType.GIF, ImageType.GIF);
            list.Add((int)ImageType.PCX, ImageType.PCX);
            list.Add((int)ImageType.PNG, ImageType.PNG);
            list.Add((int)ImageType.PSD, ImageType.PSD);
            list.Add((int)ImageType.RAS, ImageType.RAS);
            list.Add((int)ImageType.SGI, ImageType.SGI);
            list.Add((int)ImageType.TIFF, ImageType.TIFF);
            return list;

        }
        /// <summary>  
        /// 通过文件头获取图像文件的类型  
        /// </summary>  
        /// <param name="path"></param>  
        /// <returns></returns>  
        public static string GetExtension(this string path)
        {
            return CheckImageType(path);
        }
        /// <summary>  
        /// 通过文件头判断图像文件的类型  
        /// </summary>  
        /// <param name="path"></param>  
        /// <returns></returns>  
        private static string CheckImageType(string path)
        {
            byte[] buf = new byte[2];
            try
            {
                using (StreamReader sr = new StreamReader(path))
                {
                    int i = sr.BaseStream.Read(buf, 0, buf.Length);
                    if (i != buf.Length)
                    {
                        return ImageType.None.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                //Debug.Print(ex.ToString());
                return ImageType.None.ToString();
            }
            return GetExtension(buf);
        }


	public void Generate(ImageBuffer colourImage, ProjectionMode projectionMode)
	{
		this.projectionMode = projectionMode;

		bool isProjection = projectionMode == ProjectionMode.ProjectX
			|| projectionMode == ProjectionMode.ProjectY
			|| projectionMode == ProjectionMode.ProjectZ;

		/*
		if (isProjection)
		{
			// TODO: Get/use projectedImageWidth
			projectedImageWidth = 0;
		} */

		// ConvertToGreyscale
		// this.image = colourImage->convert(preset=>"grey");

		// TODO: Get working in app, this works for porting:  Convert image to grayscale externally
		this.image = colourImage;

		// Get image dimensions
		imageWidth = this.image.Width;
		imageHeight = this.image.Height;

		GMoveLine.Restart();

		// Compute speed range
		speedRange = highSpeed - lowSpeed;

		/*
		if ((projectionMode  != "-spherical") && (((projectionMode  == "-cylinderZ") || projectedImageWidth  == "-") && projectedImageHeight  == "-")) {
			print STDERR <<END;
		0: you must set either the image width or its height, or both.
		END
			exit 1;
		}*/

		/* ******************************************************** */
		/*               TODO: Scale width/height
		/* ******************************************************** */

		/*
		if (defined projectedImageWidth && projectedImageWidth == "-") {
			projectedImageWidth = projectedImageHeight * imageWidth / imageHeight;
		}

		if (defined projectedImageHeight && projectedImageHeight == "-") {
			projectedImageHeight = projectedImageWidth * imageHeight / imageWidth;
		}*/

		var maxVecLength = .1; // Longest vector in mm. Splits longer vectors. Very small -> long processing times.

		double oldX = double.MinValue;
		double oldY = double.MinValue;
		double oldE = 0;
		double currentZ = double.MinValue;

		double lastZOutput = -1;

		string line;

		while(null != (line = inputStream.ReadLine()))
		//foreach (string line in allLines)
		{
			bool hasMove = line.StartsWith("G0") || line.StartsWith("G1");

			GMoveLine gmove = null;

			if(hasMove)
			{
				gmove = new GMoveLine(line);
			}

			double x = (hasMove) ? gmove.X : double.MinValue;
			double y = (hasMove) ? gmove.Y : double.MinValue;
			double z = (hasMove) ? gmove.Z : double.MinValue;
			double e = (hasMove) ? gmove.E : 0;
			double f = (hasMove) ? gmove.F : double.MinValue;

			z = (z != double.MinValue) ? z : currentZ;

			if (x != double.MinValue)
			{
				// If this is the first move and oldZ is yet to be defined
				if (oldZ == double.MinValue)
				{
					outMove(x, y, z, e, false);
				}
				else
				{
					var xd = x - oldX;
					var yd = y - oldY;
					var zd = z - oldZ;
					var ed = e - oldE;

					var length = Math.Sqrt(xd * xd + yd * yd + zd * zd);

					if (length <= maxVecLength)
					{
						outMove(x, y, z, e, false);
					}
					else
					{
						var lastSegOut = 0;
						var oSlow = surfaceSpeed(oldX, oldY, oldZ);

						double nSegs = (int)(length / maxVecLength + 0.5);

						var xDelta = xd / nSegs;
						var yDelta = yd / nSegs;
						var zDelta = zd / nSegs;
						var eDelta = ed / nSegs;

						// Break the source G0/1 move into segments of maxVecLength
						for (var i = 1; i <= nSegs; i++)
						{
							var nx = oldX + xDelta * i;
							var ny = oldY + yDelta * i;
							var nz = oldZ + zDelta * i;

							var slow = surfaceSpeed(nx, ny, nz);
							if (slow != oSlow && i > 1)
							{
								// pattern has changed. Time to output the vector so far
								outMove(
									oldX + xDelta * (i - 1),
									oldY + yDelta * (i - 1),
									oldZ + zDelta * (i - 1),
									oldE + eDelta * (i - 1),
									true);

								oSlow = slow;
								lastSegOut = i;
							}
						}

						if (lastSegOut != nSegs)
						{
							outMove(
								x,
								y,
								z,
								oldE + eDelta * (nSegs - 1),
								lastSegOut != 0);
						}
					}
				}

				oldX = x;
				oldY = y;
				oldZ = z;
				oldE = e;
			}
			else
			{
				if (gmove != null)
				{
					if (gmove.X != double.MinValue)
					{
						oldX = gmove.X;
					}

					if (gmove.Y != double.MinValue)
					{
						oldY = gmove.Y;
					}

					if (gmove.Z != double.MinValue)
					{
						currentZ = oldZ = gmove.Z;
					}

					if (gmove.E != double.MinValue)
					{
						oldE = gmove.E;
					}
				}

				outputStream.WriteLine(line);
			}
		}
	}

	private double surfaceSpeed(double x, double y, double z)
	{
		switch (projectionMode)
		{
			case ProjectionMode.CylinderZ:
				return surfaceSpeedCylinderZ(x, y, z);

			case ProjectionMode.ProjectX:
				return surfaceSpeedProjectX(x, y, z);

			case ProjectionMode.ProjectY:
				return surfaceSpeedProjectY(x, y, z);

			case ProjectionMode.ProjectZ:
				return surfaceSpeedProjectZ(x, y, z);

			case ProjectionMode.Spherical:
				xOffset = 0;
				yOffset = 0;
				return surfaceSpeedSpherical(x, y, z);
		}

		return double.MinValue;
	}

	private bool outsideImage(double imageX, double imageY)
	{
		return imageX < 0
			|| imageX >= imageWidth
			|| imageY < 0
			|| imageY >= imageHeight;
	}

	private double surfaceSpeedProjectY(double x, double y, double z)
	{
		var xNormalized = (y - printCentreY + (double)projectedImageWidth / 2.0) / (double)projectedImageWidth;
		var zNormalized = (z - zOffset) / (double)projectedImageHeight;

		var imageX = xNormalized * imageWidth;
		var imageY = zNormalized * (double)imageHeight;

		if (outsideImage(imageX, imageY))
		{
			// return highSpeed;
			return outsideSpeed;
		}

		var grey = greyAt(imageX, imageY);
		var greyAmount = grey / 255;

		return lowSpeed + greyAmount * (double)speedRange;
	}

	private double greyAt(double dx, double dy)
	{
		// TODO: Conversion from double to int needs reconsidered
		int x = (int)Math.Floor(dx);
		int y = (int)Math.Floor(dy);

		//Console.WriteLine("{0}/{1} {2}/{3}", dx, dy, x, y);

		// Get pixel color
		var color = image.GetPixel(x, y);
		return color.red;
	}

	private void outMove(double x, double y, double z, double e, bool extra)
	{
		string added = extra ? " ; added" : "";
		double fspeed = surfaceSpeed(x, y, z);

		outputStream.Write("G1 ");

		if (x != double.MinValue)
		{
			outputStream.Write("X{0:0.000} ", x);
		}

		if (y != double.MinValue)
		{
			outputStream.Write("Y{0:0.000} ", y);
		}

		if (z != lastZOutput && z != double.MinValue)
		{
			outputStream.Write("Z{0:0.000} ", z);
		}

		if (e != double.MinValue)
		{
			outputStream.Write("E{0:0.000} ", e);
		}

		outputStream.Write("F{0:0.000} ", fspeed);

		outputStream.Write(Environment.NewLine);

		lastZOutput = z;
	}

        public ToolbarBuilder AddBasic()
        {
            AddBold();
            AddItalic();
            AddUnderline();
            AddRemoveFormat();
            return this;
        }

        public ToolbarBuilder AddStandard()
        {
            AddBasic();
            AddJustifyCenter();
            AddJustifyFull();
            AddJustifyLeft();
            AddJustifyRight();
            AddH1();
            AddH2();
            AddH3();
            AddH4();
            AddH5();
            AddH6();
            AddTextColor();
            AddUnorderedList();
            AddOrderedList();
            return this;
        }

        public ToolbarBuilder AddAll()
        {
            AddStandard();
            AddSubscript();
            AddSuperscript();
            AddStrikeThrough();
            AddHorizontalRule();
            AddIndent();
            AddOutdent();
            AddUndo();
            AddRedo();
            AddParagraph();
            return this;
        }

        #region Add functions

        public ToolbarBuilder AddBold(string imagePath = null)
        {
            AddOnce(new RichEditorToolbarItem
            {
                ImagePath = string.IsNullOrEmpty(imagePath) ? "ZSSbold.png" : imagePath,
                Label = "bold",
                ClickFunc = (input) =>
                {
                    input.SetBold();
                    return string.Empty;
                }
            });
            return this;
        }

        public ToolbarBuilder AddItalic(string imagePath = null)
        {
            AddOnce(new RichEditorToolbarItem
            {
                ImagePath = string.IsNullOrEmpty(imagePath) ? "ZSSitalic.png" : imagePath,
                Label = "italic",
                ClickFunc = (input) =>
                {
                    input.SetItalic();
                    return string.Empty;
                }
            });
            return this;
        }

        public ToolbarBuilder AddSubscript(string imagePath = null)
        {
            AddOnce(new RichEditorToolbarItem
            {
                ImagePath = string.IsNullOrEmpty(imagePath) ? "ZSSsubscript.png" : imagePath,
                Label = "subscript",
                ClickFunc = (input) =>
                {
                    input.SetSubscript();
                    return string.Empty;
                }
            });
            return this;
        }

        public ToolbarBuilder AddBasic()
        {
            AddBold();
            AddItalic();
            AddUnderline();
            AddRemoveFormat();
            return this;
        }

        public ToolbarBuilder AddStandard()
        {
            AddBasic();
            AddJustifyCenter();
            AddJustifyFull();
            AddJustifyLeft();
            AddJustifyRight();
            AddH1();
            AddH2();
            AddH3();
            AddH4();
            AddH5();
            AddH6();
            AddTextColor();
            AddUnorderedList();
            AddOrderedList();
            return this;
        }

        public ToolbarBuilder AddAll()
        {
            AddStandard();
            AddSubscript();
            AddSuperscript();
            AddStrikeThrough();
            AddHorizontalRule();
            AddIndent();
            AddOutdent();
            AddUndo();
            AddRedo();
            AddParagraph();
            return this;
        }

        #region Add functions

        public ToolbarBuilder AddBold(string imagePath = null)
        {
            AddOnce(new RichEditorToolbarItem
            {
                ImagePath = string.IsNullOrEmpty(imagePath) ? "ZSSbold.png" : imagePath,
                Label = "bold",
                ClickFunc = (input) =>
                {
                    input.SetBold();
                    return string.Empty;
                }
            });
            return this;
        }

        public ToolbarBuilder AddItalic(string imagePath = null)
        {
            AddOnce(new RichEditorToolbarItem
            {
                ImagePath = string.IsNullOrEmpty(imagePath) ? "ZSSitalic.png" : imagePath,
                Label = "italic",
                ClickFunc = (input) =>
                {
                    input.SetItalic();
                    return string.Empty;
                }
            });
            return this;
        }

        public ToolbarBuilder AddSubscript(string imagePath = null)
        {
            AddOnce(new RichEditorToolbarItem
            {
                ImagePath = string.IsNullOrEmpty(imagePath) ? "ZSSsubscript.png" : imagePath,
                Label = "subscript",
                ClickFunc = (input) =>
                {
                    input.SetSubscript();
                    return string.Empty;
                }
            });
            return this;
        }


		protected override void AddImageInternal(string imageFilePath)
		{
			var imageName = Path.GetFileNameWithoutExtension(imageFilePath);
			File.Copy(imageFilePath, Path.Combine(_sourcePath, String.Format("{0}_xl.png", imageName)));
			using (var originalImage = Image.FromFile(imageFilePath))
			{
				using (var largeImage = originalImage.Resize(new Size((Int32)(originalImage.Width * 0.7), originalImage.Height)))
				{
					largeImage.Save(Path.Combine(_sourcePath, String.Format("{0}_l.png", imageName)));
				}
				using (var mediumImage = originalImage.Resize(new Size((Int32)(originalImage.Width * 0.5), originalImage.Height)))
				{
					mediumImage.Save(Path.Combine(_sourcePath, String.Format("{0}_md.png", imageName)));
				}
				using (var smallImage = originalImage.Resize(new Size((Int32)(originalImage.Width * 0.3), originalImage.Height)))
				{
					smallImage.Save(Path.Combine(_sourcePath, String.Format("{0}_sm.png", imageName)));
				}
				using (var extraSmallImage = originalImage.Resize(new Size((Int32)(originalImage.Width * 0.15), originalImage.Height)))
				{
					extraSmallImage.Save(Path.Combine(_sourcePath, String.Format("{0}_xs.png", imageName)));
				}
			}
		}


		protected override void AddImageInternal(string imageFilePath)
		{
			var imageName = Path.GetFileNameWithoutExtension(imageFilePath);
			using (var originalImage = Image.FromFile(imageFilePath))
			{
				using (var largeImage = originalImage.Resize(new Size(32, 32)))
				{
					if (largeImage.Width < 32)
					{
						var paddingSize = (Int32)Math.Floor(((Double)32 - largeImage.Width) / 2);
						using (var largePaddingImage = largeImage.DrawPadding(new Padding(paddingSize, 0, paddingSize, 0)))
						{
							largePaddingImage.Save(Path.Combine(_sourcePath, String.Format("{0}_l.png", imageName)));
						}
					}
					else if (largeImage.Height < 32)
					{
						var paddingSize = (Int32)Math.Floor(((Double)32 - largeImage.Height) / 2);
						using (var largePaddingImage = largeImage.DrawPadding(new Padding(0, paddingSize, 0, paddingSize)))
						{
							largePaddingImage.Save(Path.Combine(_sourcePath, String.Format("{0}_l.png", imageName)));
						}
					}
					else
						largeImage.Save(Path.Combine(_sourcePath, String.Format("{0}_l.png", imageName)));
				}
				using (var smallImage = originalImage.Resize(new Size(24, originalImage.Height)))
				{
					var basePaddingSize = 4;
					if (smallImage.Width < 24)
					{
						var paddingSize = basePaddingSize + (Int32)Math.Floor(((Double)24 - smallImage.Width) / 2);
						using (var smallPaddingImage = smallImage.DrawPadding(new Padding(paddingSize, basePaddingSize, paddingSize, basePaddingSize)))
						{
							smallPaddingImage.Save(Path.Combine(_sourcePath, String.Format("{0}_sm.png", imageName)));
						}
					}
					else if (smallImage.Height < 24)
					{
						var paddingSize = basePaddingSize + (Int32)Math.Floor(((Double)24 - smallImage.Height) / 2);
						using (var smallPaddingImage = smallImage.DrawPadding(new Padding(basePaddingSize, paddingSize, basePaddingSize, paddingSize)))
						{
							smallPaddingImage.Save(Path.Combine(_sourcePath, String.Format("{0}_sm.png", imageName)));
						}
					}
					else
						using (var smallPaddingImage = smallImage.DrawPadding(new Padding(basePaddingSize)))
						{
							smallPaddingImage.Save(Path.Combine(_sourcePath, String.Format("{0}_sm.png", imageName)));
						}
				}
			}
		}

Google.Apis.Compute.beta.Data.Image : IDirectResponseSchema

Constructors :

public Image()

Methods :

public Nullable<Int64> get_ArchiveSizeBytes()
public Void set_ArchiveSizeBytes(Nullable<Int64> value = )
public String get_CreationTimestamp()
public Void set_CreationTimestamp(String value = )
public DeprecationStatus get_Deprecated()
public Void set_Deprecated(DeprecationStatus value = )
public String get_Description()
public Void set_Description(String value = )
public Nullable<Int64> get_DiskSizeGb()
public Void set_DiskSizeGb(Nullable<Int64> value = )
public String get_Family()
public Void set_Family(String value = )
public IList<GuestOsFeature> get_GuestOsFeatures()
public Void set_GuestOsFeatures(IList<GuestOsFeature> value = )
public Nullable<UInt64> get_Id()
public Void set_Id(Nullable<UInt64> value = )
public CustomerEncryptionKey get_ImageEncryptionKey()
public Void set_ImageEncryptionKey(CustomerEncryptionKey value = )
public String get_Kind()
public Void set_Kind(String value = )
public String get_LabelFingerprint()
public Void set_LabelFingerprint(String value = )
public IDictionary<StringString> get_Labels()
public Void set_Labels(IDictionary<StringString> value = )
public IList<Nullable<Int64>> get_LicenseCodes()
public Void set_LicenseCodes(IList<Nullable<Int64>> value = )
public IList<String> get_Licenses()
public Void set_Licenses(IList<String> value = )
public Nullable<Boolean> get_Locked()
public Void set_Locked(Nullable<Boolean> value = )
public String get_Name()
public Void set_Name(String value = )
public RawDiskData get_RawDisk()
public Void set_RawDisk(RawDiskData value = )
public RolloutPolicy get_RolloutOverride()
public Void set_RolloutOverride(RolloutPolicy value = )
public Nullable<Boolean> get_SatisfiesPzs()
public Void set_SatisfiesPzs(Nullable<Boolean> value = )
public String get_SelfLink()
public Void set_SelfLink(String value = )
public InitialStateConfig get_ShieldedInstanceInitialState()
public Void set_ShieldedInstanceInitialState(InitialStateConfig value = )
public String get_SourceDisk()
public Void set_SourceDisk(String value = )
public CustomerEncryptionKey get_SourceDiskEncryptionKey()
public Void set_SourceDiskEncryptionKey(CustomerEncryptionKey value = )
public String get_SourceDiskId()
public Void set_SourceDiskId(String value = )
public String get_SourceImage()
public Void set_SourceImage(String value = )
public CustomerEncryptionKey get_SourceImageEncryptionKey()
public Void set_SourceImageEncryptionKey(CustomerEncryptionKey value = )
public String get_SourceImageId()
public Void set_SourceImageId(String value = )
public String get_SourceSnapshot()
public Void set_SourceSnapshot(String value = )
public CustomerEncryptionKey get_SourceSnapshotEncryptionKey()
public Void set_SourceSnapshotEncryptionKey(CustomerEncryptionKey value = )
public String get_SourceSnapshotId()
public Void set_SourceSnapshotId(String value = )
public String get_SourceType()
public Void set_SourceType(String value = )
public String get_Status()
public Void set_Status(String value = )
public IList<String> get_StorageLocations()
public Void set_StorageLocations(IList<String> value = )
public IList<String> get_UserLicenses()
public Void set_UserLicenses(IList<String> value = )
public String get_ETag()
public Void set_ETag(String value = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()