Last active
April 19, 2024 11:59
-
-
Save gsscoder/248dd65ae25eaa3ac8c5a3111a344cbc to your computer and use it in GitHub Desktop.
C# image utilities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Drawing; | |
using System.Drawing.Drawing2D; | |
using System.Drawing.Imaging; | |
using System.IO; | |
public static class ImageUtil | |
{ | |
public static Image Resize(this Image image, int width, int height) | |
{ | |
var destRect = new Rectangle(0, 0, width, height); | |
var destImage = new Bitmap(width, height); | |
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); | |
using var graphics = Graphics.FromImage(destImage); | |
graphics.CompositingMode = CompositingMode.SourceCopy; | |
graphics.CompositingQuality = CompositingQuality.HighQuality; | |
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; | |
graphics.SmoothingMode = SmoothingMode.HighQuality; | |
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; | |
using var wrapMode = new ImageAttributes(); | |
wrapMode.SetWrapMode(WrapMode.TileFlipXY); | |
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); | |
return destImage; | |
} | |
public static byte[] ToByteArray(this Image image, ImageFormat format) | |
{ | |
using var ms = new MemoryStream(); | |
image.Save(ms, format); | |
return ms.ToArray(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment