Daily Archives: May 9, 2021
C# || How To Split & Batch An Array/List/IEnumerable Into Smaller Sub-Lists Of N Size Using C#
The following is a module with functions which demonstrates how to split/batch an Array/List/IEnumerable into smaller sublists of n size using C#.
This generic extension function uses a simple for loop to group items into batches.
1. Partition – Integer Array
The example below demonstrates the use of ‘Utils.Extensions.Partition‘ to group an integer array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// Partition - Integer Array using Utils; // Declare array of integers var numbers = new int[] { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; // Split array into sub groups var numbersPartition = numbers.Partition(3); // Display grouped batches for (var batchCount = 0; batchCount < numbersPartition.Count; ++batchCount) { var batch = numbersPartition[batchCount]; Console.WriteLine($"Batch #{batchCount + 1}"); foreach (var item in batch) { Console.WriteLine($" Item: {item}"); } } // expected output: /* Batch #1 Item: 1987 Item: 19 Item: 22 Batch #2 Item: 2009 Item: 2019 Item: 1991 Batch #3 Item: 28 Item: 31 */ |
2. Partition – String List
The example below demonstrates the use of ‘Utils.Extensions.Partition‘ to group a list of strings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// Partition - String List using Utils; // Declare list of strings var names = new List<string>() { "Kenneth", "Jennifer", "Lynn", "Sole" }; // Split array into sub groups var namesPartition = names.Partition(2); // Display grouped batches for (var batchCount = 0; batchCount < namesPartition.Count; ++batchCount) { var batch = namesPartition[batchCount]; Console.WriteLine($"Batch #{batchCount + 1}"); foreach (var item in batch) { Console.WriteLine($" Item: {item}"); } } // expected output: /* Batch #1 Item: Kenneth Item: Jennifer Batch #2 Item: Lynn Item: Sole */ |
3. Partition – Custom Object List
The example below demonstrates the use of ‘Utils.Extensions.Partition‘ to group a list of custom objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
// Partition - Custom Object List using Utils; public class Part { public string PartName { get; set; } public int PartId { get; set; } } // Declare list of objects var parts = new List<Part>() { new Part() { PartName = "crank arm", PartId = 1234 }, new Part() { PartName = "chain ring", PartId = 1334 }, new Part() { PartName = "regular seat", PartId = 1434 }, new Part() { PartName = "banana seat", PartId = 1444 }, new Part() { PartName = "cassette", PartId = 1534 }, new Part() { PartName = "shift lever", PartId = 1634 } }; // Split array into sub groups var partsPartition = parts.Partition(4); // Display grouped batches for (var batchCount = 0; batchCount < partsPartition.Count; ++batchCount) { var batch = partsPartition[batchCount]; Console.WriteLine($"Batch #{batchCount + 1}"); foreach (var item in batch) { Console.WriteLine($" Item: {item.PartId} - {item.PartName}"); } } // expected output: /* Batch #1 Item: 1234 - crank arm Item: 1334 - chain ring Item: 1434 - regular seat Item: 1444 - banana seat Batch #2 Item: 1534 - cassette Item: 1634 - shift lever */ |
4. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 9, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Collections.Generic; namespace Utils { public static class Extensions { /// <summary> /// Breaks a list into smaller sub-lists of a specified size /// </summary> /// <param name="source">An IEnumerable to split into smaller sub-lists</param> /// <param name="size">The maximum size of each sub-list</param> /// <returns>The smaller sub-lists of the specified size</returns> public static List<List<T>> Partition<T>(this IEnumerable<T> source, int size) { var result = new List<List<T>>(); List<T> batch = null; int index = 0; foreach (var item in source) { if (index % size == 0) { batch = new List<T>(); result.Add(batch); } batch.Add(item); ++index; } return result; } } }// http://programmingnotes.org/ |
5. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 9, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using System.Collections.Generic; using Utils; public class Program { public class Part { public string PartName { get; set; } public int PartId { get; set; } } static void Main(string[] args) { try { // Declare array of integers var numbers = new int[] { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; // Split array into sub groups var numbersPartition = numbers.Partition(3); // Display grouped batches for (var batchCount = 0; batchCount < numbersPartition.Count; ++batchCount) { var batch = numbersPartition[batchCount]; Display($"Batch #{batchCount + 1}"); foreach (var item in batch) { Display($" Item: {item}"); } } Display(""); // Declare list of strings var names = new List<string>() { "Kenneth", "Jennifer", "Lynn", "Sole" }; // Split array into sub groups var namesPartition = names.Partition(2); // Display grouped batches for (var batchCount = 0; batchCount < namesPartition.Count; ++batchCount) { var batch = namesPartition[batchCount]; Display($"Batch #{batchCount + 1}"); foreach (var item in batch) { Display($" Item: {item}"); } } Display(""); // Declare list of objects var parts = new List<Part>() { new Part() { PartName = "crank arm", PartId = 1234 }, new Part() { PartName = "chain ring", PartId = 1334 }, new Part() { PartName = "regular seat", PartId = 1434 }, new Part() { PartName = "banana seat", PartId = 1444 }, new Part() { PartName = "cassette", PartId = 1534 }, new Part() { PartName = "shift lever", PartId = 1634 } }; // Split array into sub groups var partsPartition = parts.Partition(4); // Display grouped batches for (var batchCount = 0; batchCount < partsPartition.Count; ++batchCount) { var batch = partsPartition[batchCount]; Display($"Batch #{batchCount + 1}"); foreach (var item in batch) { Display($" Item: {item.PartId} - {item.PartName}"); } } } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C# || How To Set & Get The Description Of An Enum Using C#
The following is a module with functions which demonstrates how to set and get the description of an enum using C#.
This function uses the DescriptionAttribute to get the description of an Enum element. If a description attribute is not specified, the string value of the Enum element is returned.
1. Get Description
The example below demonstrates the use of ‘Utils.Extensions.GetDescription‘ to get the description of enum elements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
// Get Description using Utils; public enum MimeTypes { [System.ComponentModel.Description("application/pdf")] ApplicationPDF = 1, [System.ComponentModel.Description("application/octet-stream")] ApplicationOctect = 2, [System.ComponentModel.Description("application/zip")] ApplicationZip = 3, [System.ComponentModel.Description("application/msword")] ApplicationMSWordDOC = 4, [System.ComponentModel.Description("application/vnd.openxmlformats-officedocument.wordprocessingml.document")] ApplicationMSWordDOCX = 5, [System.ComponentModel.Description("application/vnd.ms-excel")] ApplicationMSExcelXLS = 6, [System.ComponentModel.Description("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")] ApplicationMSExcelXLSX = 7 } foreach (MimeTypes value in System.Enum.GetValues(typeof(MimeTypes))) { Console.WriteLine($"Numeric Value: {(int)value}, Name: {value.ToString()}, Description: {value.GetDescription()}"); } // expected output: /* Numeric Value: 1, Name: ApplicationPDF, Description: application/pdf Numeric Value: 2, Name: ApplicationOctect, Description: application/octet-stream Numeric Value: 3, Name: ApplicationZip, Description: application/zip Numeric Value: 4, Name: ApplicationMSWordDOC, Description: application/msword Numeric Value: 5, Name: ApplicationMSWordDOCX, Description: application/vnd.openxmlformats-officedocument.wordprocessingml.document Numeric Value: 6, Name: ApplicationMSExcelXLS, Description: application/vnd.ms-excel Numeric Value: 7, Name: ApplicationMSExcelXLSX, Description: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet */ |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 9, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Linq; namespace Utils { public static class Extensions { /// <summary> /// Returns the description of an enum decorated with a DescriptionAttribute /// </summary> /// <param name="value">An Enumeration value</param> /// <returns>The description of an enumeration value</returns> public static string GetDescription(this System.Enum value) { var description = value.ToString(); var attribute = GetAttribute<System.ComponentModel.DescriptionAttribute>(value); if (attribute != null) { description = attribute.Description; } return description; } public static T GetAttribute<T>(System.Enum value) where T : System.Attribute { var field = value.GetType().GetField(value.ToString()); var attribute = ((T[])field.GetCustomAttributes(typeof(T), false)).FirstOrDefault(); return attribute; } } }// http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 9, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using Utils; public class Program { public enum MimeTypes { [System.ComponentModel.Description("application/pdf")] ApplicationPDF = 1, [System.ComponentModel.Description("application/octet-stream")] ApplicationOctect = 2, [System.ComponentModel.Description("application/zip")] ApplicationZip = 3, [System.ComponentModel.Description("application/msword")] ApplicationMSWordDOC = 4, [System.ComponentModel.Description("application/vnd.openxmlformats-officedocument.wordprocessingml.document")] ApplicationMSWordDOCX = 5, [System.ComponentModel.Description("application/vnd.ms-excel")] ApplicationMSExcelXLS = 6, [System.ComponentModel.Description("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")] ApplicationMSExcelXLSX = 7, [System.ComponentModel.Description("application/vnd.ms-powerpoint")] ApplicationMSPowerPointPPT = 8, [System.ComponentModel.Description("application/vnd.openxmlformats-officedocument.presentationml.presentation")] ApplicationMSPowerPointPPTX = 9, [System.ComponentModel.Description("audio/basic")] AudioBasic = 10, [System.ComponentModel.Description("audio/mpeg")] AudioMPEG = 11, [System.ComponentModel.Description("audio/x-wav")] AudioWAV = 12, [System.ComponentModel.Description("image/gif")] ImageGIF = 13, [System.ComponentModel.Description("image/jpeg")] ImageJPEG = 14, [System.ComponentModel.Description("image/png")] ImagePNG = 15, [System.ComponentModel.Description("text/html")] TextHTML = 16, [System.ComponentModel.Description("text/plain")] TextPlain = 17, [System.ComponentModel.Description("video/mpeg")] VideoMPEG = 18, [System.ComponentModel.Description("video/x-msvideo")] VideoAVI = 19 } static void Main(string[] args) { try { foreach (MimeTypes value in System.Enum.GetValues(typeof(MimeTypes))) { Display($"Numeric Value: {(int)value}, Name: {value.ToString()}, Description: {value.GetDescription()}"); } } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C# || How To Iterate & Get The Values Of An Enum Using C#
The following is a module with functions which demonstrates how to iterate and get the values of an enum using C#.
This function is a generic wrapper for the Enum.GetValues function.
1. Get Values – Basic Enum
The example below demonstrates the use of ‘Utils.Methods.GetEnumValues‘ to get the values of a simple Enum.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Get Values - Basic Enum enum Colors { Red, Green, Blue, Yellow } var colors = Utils.Methods.GetEnumValues<Colors>(); foreach (var color in colors) { Console.WriteLine($"Numeric Value: {(int)color}, Name: {color.ToString()}"); } // expected output: /* Numeric Value: 0, Name: Red Numeric Value: 1, Name: Green Numeric Value: 2, Name: Blue Numeric Value: 3, Name: Yellow */ |
2. Get Values – Numbered Enum
The example below demonstrates the use of ‘Utils.Methods.GetEnumValues‘ to get the values of a numbered Enum.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// Get Values - Numbered Enum public enum Pets { None = 0, Dog = 1, Cat = 2, Rodent = 4, Bird = 8, Fish = 16, Reptile = 32, Other = 64 } var pets = Utils.Methods.GetEnumValues<Pets>(); foreach (var pet in pets) { Console.WriteLine($"Numeric Value: {(int)pet}, Name: {pet.ToString()}"); } // expected output: /* Numeric Value: 0, Name: None Numeric Value: 1, Name: Dog Numeric Value: 2, Name: Cat Numeric Value: 4, Name: Rodent Numeric Value: 8, Name: Bird Numeric Value: 16, Name: Fish Numeric Value: 32, Name: Reptile Numeric Value: 64, Name: Other */ |
3. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 9, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Collections.Generic; namespace Utils { public static class Methods { /// <summary> /// Returns a List of the values of the constants in a specified enumeration /// </summary> /// <returns>The values contained in the enumeration</returns> public static List<T> GetEnumValues<T>() { var type = typeof(T); if (!type.IsSubclassOf(typeof(System.Enum))) { throw new InvalidCastException($"Unable to cast '{type.FullName}' to System.Enum"); } var result = new List<T>(); foreach (T value in System.Enum.GetValues(type)) { result.Add(value); } return result; } } }// http://programmingnotes.org/ |
4. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 9, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using System.Collections.Generic; public class Program { enum Colors { Red, Green, Blue, Yellow } public enum Pets { None = 0, Dog = 1, Cat = 2, Rodent = 4, Bird = 8, Fish = 16, Reptile = 32, Other = 64 } static void Main(string[] args) { try { var colors = Utils.Methods.GetEnumValues<Colors>(); foreach (var color in colors) { Display($"Numeric Value: {(int)color}, Name: {color.ToString()}"); } Display(""); var pets = Utils.Methods.GetEnumValues<Pets>(); foreach (var pet in pets) { Display($"Numeric Value: {(int)pet}, Name: {pet.ToString()}"); } } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C# || How To Resize & Rotate Image, Convert Image To Byte Array, Change Image Format, & Fix Image Orientation Using C#
The following is a module with functions which demonstrates how to resize an image, rotate an image to a specific angle, convert an image to a byte array, change an image format, and fix an image orientation Using C#.
Contents
1. Overview
2. Resize & Rotate - Image
3. Resize & Rotate - Byte Array
4. Resize & Rotate - Memory Stream
5. Convert Image To Byte Array
6. Change Image Format
7. Fix Image Orientation
8. Utils Namespace
9. More Examples
1. Overview
To use the functions in this module, make sure you have a reference to ‘System.Drawing‘ in your project.
One way to do this is, in your Solution Explorer (where all the files are shown with your project), right click the ‘References‘ folder, click ‘Add References‘, then type ‘System.Drawing‘ in the search box, and add a reference to System.Drawing in the results Tab.
Note: Don’t forget to include the ‘Utils Namespace‘ before running the examples!
2. Resize & Rotate – Image
The example below demonstrates the use of ‘Utils.Image.Extensions.Resize‘ and ‘Utils.Image.Extensions.Rotate‘ to resize and rotate an image object.
Resizing and rotating an image returns a newly created image object.
1 2 3 4 5 6 7 8 9 10 11 12 |
// Resize & Rotate - Image using Utils.Image; var path = $@"path-to-file\file.extension"; var image = System.Drawing.Image.FromFile(path); // Resize image 500x500 var resized = image.Resize(new System.Drawing.Size(500, 500)); // Rotate 90 degrees counter clockwise var rotated = image.Rotate(-90); |
3. Resize & Rotate – Byte Array
The example below demonstrates the use of ‘Utils.Image.Extensions.Resize‘ and ‘Utils.Image.Extensions.Rotate‘ to resize and rotate a byte array.
Resizing and rotating an image returns a newly created image object.
1 2 3 4 5 6 7 8 9 10 |
// Resize & Rotate - Byte Array // Read file to byte array byte[] bytes; // Resize image 800x800 var resized = Utils.Image.Extensions.Resize(bytes, new System.Drawing.Size(800, 800)); // Rotate 180 degrees clockwise var rotated = Utils.Image.Extensions.Rotate(bytes, 180); |
4. Resize & Rotate – Memory Stream
The example below demonstrates the use of ‘Utils.Image.Resize‘ and ‘Utils.Image.Rotate‘ to resize and rotate a memory stream.
Resizing and rotating an image returns a newly created image object.
1 2 3 4 5 6 7 8 9 10 |
// Resize & Rotate - Memory Stream // Read file to memory stream var stream = new System.IO.MemoryStream(); // Resize image 2000x2000 var resized = Utils.Image.Extensions.Resize(stream, new System.Drawing.Size(2000, 2000)); // Rotate 360 degrees var rotated = Utils.Image.Extensions.Rotate(stream, 360); |
5. Convert Image To Byte Array
The example below demonstrates the use of ‘Utils.Image.Extensions.ToArray‘ to convert an image object to a byte array.
The optional function parameter allows you to specify the image format.
1 2 3 4 5 6 7 8 9 |
// Convert Image To Byte Array using Utils.Image; var path = $@"path-to-file\file.extension" var image = System.Drawing.Image.FromFile(path); // Convert image to byte array var bytes = image.ToArray(); |
6. Change Image Format
The example below demonstrates the use of ‘Utils.Image.Extensions.ConvertFormat‘ to convert the image object raw format to another format.
Converting an images format returns a newly created image object.
1 2 3 4 5 6 7 8 9 |
// Change Image Format using Utils.Image; var path = $@"path-to-file\file.extension"; var image = System.Drawing.Image.FromFile(path); // Convert image to another format var newImage = image.ConvertFormat(System.Drawing.Imaging.ImageFormat.Png); |
7. Fix Image Orientation
The example below demonstrates the use of ‘Utils.Image.Extensions.FixOrientation‘ to update the image object to reflect its Exif orientation.
When you view an image in a Photo Viewer, it automatically corrects image orientation if it has Exif orientation data.
‘Utils.Image.Extensions.FixOrientation‘ makes it so the loaded image object reflects the correct orientation when rendered according to its Exif orientation data.
1 2 3 4 5 6 7 8 9 |
// Fix Image Orientation using Utils.Image; var path = $@"path-to-file\file.extension"; var image = System.Drawing.Image.FromFile(path); // Correct the image object to reflect its Exif orientation image.FixOrientation(); |
8. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 9, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Collections.Generic; using System.Linq; namespace Utils { namespace Image { public static class Extensions { /// <summary> /// Resizes an image to a specified size /// </summary> /// <param name="source">The image to resize</param> /// <param name="desiredSize">The size to resize the image to</param> /// <param name="preserveAspectRatio">Determines if the aspect ratio should be preserved</param> /// <returns>A new image resized to the specified size</returns> public static System.Drawing.Image Resize(this System.Drawing.Image source, System.Drawing.Size desiredSize, bool preserveAspectRatio = true) { if (desiredSize.IsEmpty) { throw new ArgumentException("Image size cannot be empty", nameof(desiredSize)); } var resizedWidth = desiredSize.Width; var resizedHeight = desiredSize.Height; var sourceFormat = source.RawFormat; source.FixOrientation(); if (preserveAspectRatio) { var sourceWidth = Math.Max(source.Width, 1); var sourceHeight = Math.Max(source.Height, 1); var resizedPercentWidth = desiredSize.Width / (double)sourceWidth; var resizedPercentHeight = desiredSize.Height / (double)sourceHeight; var resizedPercentRatio = Math.Min(resizedPercentHeight, resizedPercentWidth); resizedWidth = System.Convert.ToInt32(sourceWidth * resizedPercentRatio); resizedHeight = System.Convert.ToInt32(sourceHeight * resizedPercentRatio); } var resizedImage = new System.Drawing.Bitmap(resizedWidth, resizedHeight); resizedImage.SetResolution(source.HorizontalResolution, source.VerticalResolution); using (var graphicsHandle = System.Drawing.Graphics.FromImage(resizedImage)) { graphicsHandle.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphicsHandle.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphicsHandle.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; graphicsHandle.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphicsHandle.DrawImage(source, 0, 0, resizedWidth, resizedHeight); } if (!sourceFormat.Equals(resizedImage.RawFormat)) { resizedImage = (System.Drawing.Bitmap)resizedImage.ConvertFormat(sourceFormat); } return resizedImage; } /// <summary> /// Resizes an image to a specified size /// </summary> /// <param name="stream">The stream of the image to resize</param> /// <param name="desiredSize">The size to resize the image to</param> /// <param name="preserveAspectRatio">Determines if the aspect ratio should be preserved</param> /// <returns>A new image resized to the specified size</returns> public static System.Drawing.Image Resize(System.IO.Stream stream, System.Drawing.Size desiredSize, bool preserveAspectRatio = true) { System.Drawing.Image image; using (var original = StreamToImage(stream)) { image = Resize(original, desiredSize, preserveAspectRatio: preserveAspectRatio); } return image; } /// <summary> /// Resizes an image to a specified size /// </summary> /// <param name="bytes">The byte array of the image to resize</param> /// <param name="desiredSize">The size to resize the image to</param> /// <param name="preserveAspectRatio">Determines if the aspect ratio should be preserved</param> /// <returns>A new image resized to the specified size</returns> public static System.Drawing.Image Resize(byte[] bytes, System.Drawing.Size desiredSize, bool preserveAspectRatio = true) { System.Drawing.Image image; using (var original = BytesToImage(bytes)) { image = Resize(original, desiredSize, preserveAspectRatio: preserveAspectRatio); } return image; } /// <summary> /// Rotates an image to a specified angle /// </summary> /// <param name="source">The image to resize</param> /// <param name="angle">The angle to rotate the image</param> /// <returns>A new image rotated to the specified angle</returns> public static System.Drawing.Image Rotate(this System.Drawing.Image source, decimal angle) { var sourceFormat = source.RawFormat; source.FixOrientation(); var alpha = angle; while (alpha < 0) { alpha += 360; } var gamma = 90M; var beta = 180 - angle - gamma; var c1 = source.Height; var a1 = Math.Abs((c1 * Math.Sin((double)alpha * Math.PI / 180))); var b1 = Math.Abs((c1 * Math.Sin((double)beta * Math.PI / 180))); var c2 = source.Width; var a2 = Math.Abs((c2 * Math.Sin((double)alpha * Math.PI / 180))); var b2 = Math.Abs((c2 * Math.Sin((double)beta * Math.PI / 180))); var width = System.Convert.ToInt32(b2 + a1); var height = System.Convert.ToInt32(b1 + a2); var rotatedImage = new System.Drawing.Bitmap(width, height); rotatedImage.SetResolution(source.HorizontalResolution, source.VerticalResolution); using (var graphicsHandle = System.Drawing.Graphics.FromImage(rotatedImage)) { graphicsHandle.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphicsHandle.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphicsHandle.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; graphicsHandle.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphicsHandle.TranslateTransform(rotatedImage.Width / 2, rotatedImage.Height / 2); graphicsHandle.RotateTransform((float)angle); graphicsHandle.TranslateTransform(-rotatedImage.Width / 2, -rotatedImage.Height / 2); graphicsHandle.DrawImage(source, new System.Drawing.Point((width - source.Width) / 2, (height - source.Height) / 2)); } if (!sourceFormat.Equals(rotatedImage.RawFormat)) { rotatedImage = (System.Drawing.Bitmap)rotatedImage.ConvertFormat(sourceFormat); } return rotatedImage; } /// <summary> /// Rotates an image to a specified angle /// </summary> /// <param name="stream">The stream of the image to resize</param> /// <param name="angle">The angle to rotate the image</param> /// <returns>A new image rotated to the specified angle</returns> public static System.Drawing.Image Rotate(System.IO.Stream stream, decimal angle) { System.Drawing.Image image; using (var original = StreamToImage(stream)) { image = Rotate(original, angle); } return image; } /// <summary> /// Rotates an image to a specified angle /// </summary> /// <param name="bytes">The byte array of the image to rotate</param> /// <param name="angle">The angle to rotate the image</param> /// <returns>A new image rotated to the specified angle</returns> public static System.Drawing.Image Rotate(byte[] bytes, decimal angle) { System.Drawing.Image image; using (var original = BytesToImage(bytes)) { image = Rotate(original, angle); } return image; } /// <summary> /// Converts an image to a byte array /// </summary> /// <param name="source">The image to convert</param> /// <param name="format">The format the byte array image should be converted to</param> /// <returns>The image as a byte array</returns> public static byte[] ToArray(this System.Drawing.Image source, System.Drawing.Imaging.ImageFormat format = null) { if (format == null) { format = source.ResolvedFormat(); if (format.Equals(System.Drawing.Imaging.ImageFormat.MemoryBmp)) { format = System.Drawing.Imaging.ImageFormat.Png; } } byte[] bytes; using (var stream = new System.IO.MemoryStream()) { source.Save(stream, format); bytes = stream.ToArray(); } return bytes; } /// <summary> /// Converts an image to a different ImageFormat /// </summary> /// <param name="source">The image to convert</param> /// <param name="format">The format the image should be changed to</param> /// <returns>The new image converted to the specified format</returns> public static System.Drawing.Image ConvertFormat(this System.Drawing.Image source, System.Drawing.Imaging.ImageFormat format) { var bytes = source.ToArray(format); var image = BytesToImage(bytes); return image; } /// <summary> /// Returns the resolved static image format from an images RawFormat /// </summary> /// <param name="source">The image to get the format from</param> /// <returns>The resolved image format</returns> public static System.Drawing.Imaging.ImageFormat ResolvedFormat(this System.Drawing.Image source) { var format = FindImageFormat(source.RawFormat); return format; } /// <summary> /// Returns all the ImageFormats as an IEnumerable /// </summary> /// <returns>All the ImageFormats as an IEnumerable</returns> public static IEnumerable<System.Drawing.Imaging.ImageFormat> GetImageFormats() { var formats = typeof(System.Drawing.Imaging.ImageFormat) .GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public) .Select(p => (System.Drawing.Imaging.ImageFormat)p.GetValue(null, null)); return formats; } /// <summary> /// Returns the static image format from a RawFormat /// </summary> /// <param name="raw">The ImageFormat to get info from</param> /// <returns>The resolved image format</returns> public static System.Drawing.Imaging.ImageFormat FindImageFormat(System.Drawing.Imaging.ImageFormat raw) { var format = GetImageFormats().FirstOrDefault(x => raw.Equals(x)); if (format == null) { format = System.Drawing.Imaging.ImageFormat.Png; } return format; } /// <summary> /// Update the image to reflect its exif orientation /// </summary> /// <param name="image">The image to update</param> public static void FixOrientation(this System.Drawing.Image image) { var orientationId = 274; if (!image.PropertyIdList.Contains(orientationId)) { return; } var orientation = BitConverter.ToInt16(image.GetPropertyItem(orientationId).Value, 0); var rotateFlip = System.Drawing.RotateFlipType.RotateNoneFlipNone; switch (orientation) { case 1: // Image is correctly oriented rotateFlip = System.Drawing.RotateFlipType.RotateNoneFlipNone; break; case 2: // Image has been mirrored horizontally rotateFlip = System.Drawing.RotateFlipType.RotateNoneFlipX; break; case 3: // Image has been rotated 180 degrees rotateFlip = System.Drawing.RotateFlipType.Rotate180FlipNone; break; case 4: // Image has been mirrored horizontally and rotated 180 degrees rotateFlip = System.Drawing.RotateFlipType.Rotate180FlipX; break; case 5: // Image has been mirrored horizontally and rotated 90 degrees clockwise rotateFlip = System.Drawing.RotateFlipType.Rotate90FlipX; break; case 6: // Image has been rotated 90 degrees clockwise rotateFlip = System.Drawing.RotateFlipType.Rotate90FlipNone; break; case 7: // Image has been mirrored horizontally and rotated 270 degrees clockwise rotateFlip = System.Drawing.RotateFlipType.Rotate270FlipX; break; case 8: // Image has been rotated 270 degrees clockwise rotateFlip = System.Drawing.RotateFlipType.Rotate270FlipNone; break; } if (rotateFlip != System.Drawing.RotateFlipType.RotateNoneFlipNone) { image.RotateFlip(rotateFlip); } } /// <summary> /// Returns an image from a byte array /// </summary> /// <param name="bytes">The bytes representing the image</param> /// <returns>The image from the byte array</returns> public static System.Drawing.Image BytesToImage(byte[] bytes) { return StreamToImage(new System.IO.MemoryStream(bytes)); } /// <summary> /// Returns an image from a stream /// </summary> /// <param name="stream">The stream representing the image</param> /// <returns>The image from the stream</returns> public static System.Drawing.Image StreamToImage(System.IO.Stream stream) { return System.Drawing.Image.FromStream(stream); } } } }// http://programmingnotes.org/ |
9. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 9, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using Utils.Image; public class Program { static void Main(string[] args) { try { var path = ""; // Image var image = System.Drawing.Image.FromFile(path); var resized = image.Resize(new System.Drawing.Size(500, 500)); //var rotated = image.Rotate(-90); // Byte //byte[] bytes; //var resized = Utils.Image.Extensions.Resize(bytes, new System.Drawing.Size(800, 800)); //var rotated = Utils.Image.Extensions.Rotate(bytes, 180); // Stream //var stream = new System.IO.MemoryStream(); //var resized = Utils.Image.Extensions.Resize(stream, new System.Drawing.Size(2000, 2000)); //var rotated = Utils.Image.Extensions.Rotate(stream, 360); var newPath = ""; resized.Save(newPath); } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.