Schlagwort: Images

Created with Sketch.

Convert Image to Byte Array (and back)

The following functions can be used to convert an image object to a byte array (and vise versa). This is often used to store images in a database or file or to use them in a stream. /// <summary> /// Converts an image to a byte array. /// </summary> /// <param name=“image“>The image.</param> /// <returns>Byte…

Create an Icon from an Image

The following C# code changes an image object into an icon. public static Icon ConvertImageToIcon(Image img) { if (img == null) return null; Bitmap square = new Bitmap(img.Width, img.Height); // create new bitmap Graphics g = Graphics.FromImage(square); // allow drawing to it g.DrawImage(img, 0, 0, img.Width, img.Height); // draw image with specified dimensions g.Flush(); //…

Changing size of Images

The following function changes the size of an image object and optionally changes the ratio of the image or crops the image. Perfectly for creating thumbnails. /// <summary> /// Changes the size of an image. /// </summary> /// <param name=“image“>The image.</param> /// <param name=“newWidth“>The new width of the image.</param> /// <param name=“newHeight“>The new height of the image.</param> /// <param name=“resizeOptions“>Options that define how to resize the image.</param> /// <param name=“qualityOptions“>Options that define the rendering quality.</param> /// <returns>New Image</returns> public static Image ChangeSize(this Image image, int newWidth, int newHeight, ImageResizeOptions resizeOptions = ImageResizeOptions.KeepRatio, ImageQualityOptions qualityOptions = ImageQualityOptions.Default) {   if (image == null)     throw new ArgumentNullException(nameof(image));     Rectangle rect;     if (resizeOptions == ImageResizeOptions.Stretch)   {     rect = new Rectangle(0, 0, newWidth, newHeight);   }   else   {     if (image.Height <= newHeight && image.Width <= newWidth)       return new Bitmap(image);       double originalSize = resizeOptions == ImageResizeOptions.Crop ? Math.Min(image.Width, image.Height) : Math.Max(image.Width, image.Height);     double newSize = resizeOptions == ImageResizeOptions.Crop ? Math.Min(newWidth, newHeight) : Math.Max(newWidth, newHeight);     double ratio = newSize / originalSize;     double newImageHeight = (float)image.Height * ratio;…