VB.NET || How To Resize & Rotate Image, Convert Image To Byte Array, Change Image Format, & Fix Image Orientation Using VB.NET
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 VB.NET.
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.Resize‘ and ‘Utils.Image.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 Imports Utils.Image Dim path = $"path-to-file\file.extension" Dim image = System.Drawing.Image.FromFile(path) ' Resize image 500x500 Dim resized = image.Resize(New System.Drawing.Size(500, 500)) ' Rotate 90 degrees counter clockwise Dim rotated = image.Rotate(-90) |
3. Resize & Rotate – Byte Array
The example below demonstrates the use of ‘Utils.Image.Resize‘ and ‘Utils.Image.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 Dim bytes As Byte() ' Resize image 800x800 Dim resized = Utils.Image.Resize(bytes, New System.Drawing.Size(800, 800)) ' Rotate 180 degrees clockwise Dim rotated = Utils.Image.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 Dim stream As New System.IO.MemoryStream() ' Resize image 2000x2000 Dim resized = Utils.Image.Resize(stream, New System.Drawing.Size(2000, 2000)) ' Rotate 360 degrees Dim rotated = Utils.Image.Rotate(stream, 360) |
5. Convert Image To Byte Array
The example below demonstrates the use of ‘Utils.Image.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 Imports Utils.Image Dim path = $"path-to-file\file.extension" Dim image = System.Drawing.Image.FromFile(path) ' Convert image to byte array Dim bytes = image.ToArray() |
6. Change Image Format
The example below demonstrates the use of ‘Utils.Image.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 Imports Utils.Image Dim path = $"path-to-file\file.extension" Dim image = System.Drawing.Image.FromFile(path) ' Convert image to another format Dim newImage = image.ConvertFormat(System.Drawing.Imaging.ImageFormat.Png) |
7. Fix Image Orientation
The example below demonstrates the use of ‘Utils.Image.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.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 Imports Utils.Image Dim path = $"path-to-file\file.extension" Dim 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 292 293 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 9, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Namespace Image Public Module modImage ''' <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> <Runtime.CompilerServices.Extension()> Public Function Resize(source As System.Drawing.Image, desiredSize As System.Drawing.Size, Optional preserveAspectRatio As Boolean = True) As System.Drawing.Image If desiredSize.IsEmpty Then Throw New ArgumentException("Image size cannot be empty", NameOf(desiredSize)) End If Dim resizedWidth = desiredSize.Width Dim resizedHeight = desiredSize.Height Dim sourceFormat = source.RawFormat source.FixOrientation If preserveAspectRatio Then Dim sourceWidth = Math.Max(source.Width, 1) Dim sourceHeight = Math.Max(source.Height, 1) Dim resizedPercentWidth = desiredSize.Width / sourceWidth Dim resizedPercentHeight = desiredSize.Height / sourceHeight Dim resizedPercentRatio = Math.Min(resizedPercentHeight, resizedPercentWidth) resizedWidth = CInt(sourceWidth * resizedPercentRatio) resizedHeight = CInt(sourceHeight * resizedPercentRatio) End If Dim resizedImage = New System.Drawing.Bitmap(resizedWidth, resizedHeight) resizedImage.SetResolution(source.HorizontalResolution, source.VerticalResolution) Using 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) End Using If Not sourceFormat.Equals(resizedImage.RawFormat) Then resizedImage = CType(resizedImage.ConvertFormat(sourceFormat), System.Drawing.Bitmap) End If Return resizedImage End Function ''' <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 Function Resize(stream As System.IO.Stream, desiredSize As System.Drawing.Size, Optional preserveAspectRatio As Boolean = True) As System.Drawing.Image Dim image As System.Drawing.Image Using original = StreamToImage(stream) image = Resize(original, desiredSize, preserveAspectRatio:=preserveAspectRatio) End Using Return image End Function ''' <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 Function Resize(bytes As Byte(), desiredSize As System.Drawing.Size, Optional preserveAspectRatio As Boolean = True) As System.Drawing.Image Dim image As System.Drawing.Image Using original = BytesToImage(bytes) image = Resize(original, desiredSize, preserveAspectRatio:=preserveAspectRatio) End Using Return image End Function ''' <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> <Runtime.CompilerServices.Extension()> Public Function Rotate(source As System.Drawing.Image, angle As Decimal) As System.Drawing.Image Dim sourceFormat = source.RawFormat source.FixOrientation Dim alpha = angle While alpha < 0 alpha += 360 End While Dim gamma = 90D Dim beta = 180 - angle - gamma Dim c1 = source.Height Dim a1 = Math.Abs((c1 * Math.Sin(alpha * Math.PI / 180))) Dim b1 = Math.Abs((c1 * Math.Sin(beta * Math.PI / 180))) Dim c2 = source.Width Dim a2 = Math.Abs((c2 * Math.Sin(alpha * Math.PI / 180))) Dim b2 = Math.Abs((c2 * Math.Sin(beta * Math.PI / 180))) Dim width = CInt(b2 + a1) Dim height = CInt(b1 + a2) Dim rotatedImage = New System.Drawing.Bitmap(width, height) rotatedImage.SetResolution(source.HorizontalResolution, source.VerticalResolution) Using 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(angle) graphicsHandle.TranslateTransform(-rotatedImage.Width \ 2, -rotatedImage.Height \ 2) graphicsHandle.DrawImage(source, New System.Drawing.Point((width - source.Width) \ 2, (height - source.Height) \ 2)) End Using If Not sourceFormat.Equals(rotatedImage.RawFormat) Then rotatedImage = CType(rotatedImage.ConvertFormat(sourceFormat), System.Drawing.Bitmap) End If Return rotatedImage End Function ''' <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 Function Rotate(stream As System.IO.Stream, angle As Decimal) As System.Drawing.Image Dim image As System.Drawing.Image Using original = StreamToImage(stream) image = Rotate(original, angle) End Using Return image End Function ''' <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 Function Rotate(bytes As Byte(), angle As Decimal) As System.Drawing.Image Dim image As System.Drawing.Image Using original = BytesToImage(bytes) image = Rotate(original, angle) End Using Return image End Function ''' <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> <Runtime.CompilerServices.Extension()> Public Function ToArray(source As System.Drawing.Image, Optional format As System.Drawing.Imaging.ImageFormat = Nothing) As Byte() If format Is Nothing Then format = source.ResolvedFormat If format.Equals(System.Drawing.Imaging.ImageFormat.MemoryBmp) Then format = System.Drawing.Imaging.ImageFormat.Png End If End If Dim bytes As Byte() Using stream = New System.IO.MemoryStream source.Save(stream, format) bytes = stream.ToArray End Using Return bytes End Function ''' <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> <Runtime.CompilerServices.Extension()> Public Function ConvertFormat(source As System.Drawing.Image, format As System.Drawing.Imaging.ImageFormat) As System.Drawing.Image Dim bytes = source.ToArray(format) Dim image = BytesToImage(bytes) Return image End Function ''' <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> <Runtime.CompilerServices.Extension()> Public Function ResolvedFormat(source As System.Drawing.Image) As System.Drawing.Imaging.ImageFormat Dim format = FindImageFormat(source.RawFormat) Return format End Function ''' <summary> ''' Returns all the ImageFormats as an IEnumerable ''' </summary> ''' <returns>All the ImageFormats as an IEnumerable</returns> Public Function GetImageFormats() As IEnumerable(Of System.Drawing.Imaging.ImageFormat) Static formats As IEnumerable(Of System.Drawing.Imaging.ImageFormat) = GetType(System.Drawing.Imaging.ImageFormat) _ .GetProperties(Reflection.BindingFlags.Static Or Reflection.BindingFlags.Public) _ .Select(Function(p) CType(p.GetValue(Nothing, Nothing), System.Drawing.Imaging.ImageFormat)) Return formats End Function ''' <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 Function FindImageFormat(raw As System.Drawing.Imaging.ImageFormat) As System.Drawing.Imaging.ImageFormat Dim format = GetImageFormats().FirstOrDefault(Function(x) raw.Equals(x)) If format Is Nothing Then format = System.Drawing.Imaging.ImageFormat.Png End If Return format End Function ''' <summary> ''' Update the image to reflect its exif orientation ''' </summary> ''' <param name="image">The image to update</param> <Runtime.CompilerServices.Extension()> Public Sub FixOrientation(image As System.Drawing.Image) Dim orientationId = 274 If Not image.PropertyIdList.Contains(orientationId) Then Return End If Dim orientation = BitConverter.ToInt16(image.GetPropertyItem(orientationId).Value, 0) Dim rotateFlip = System.Drawing.RotateFlipType.RotateNoneFlipNone Select Case orientation Case 1 ' Image is correctly oriented rotateFlip = System.Drawing.RotateFlipType.RotateNoneFlipNone Case 2 ' Image has been mirrored horizontally rotateFlip = System.Drawing.RotateFlipType.RotateNoneFlipX Case 3 ' Image has been rotated 180 degrees rotateFlip = System.Drawing.RotateFlipType.Rotate180FlipNone Case 4 ' Image has been mirrored horizontally and rotated 180 degrees rotateFlip = System.Drawing.RotateFlipType.Rotate180FlipX Case 5 ' Image has been mirrored horizontally and rotated 90 degrees clockwise rotateFlip = System.Drawing.RotateFlipType.Rotate90FlipX Case 6 ' Image has been rotated 90 degrees clockwise rotateFlip = System.Drawing.RotateFlipType.Rotate90FlipNone Case 7 ' Image has been mirrored horizontally and rotated 270 degrees clockwise rotateFlip = System.Drawing.RotateFlipType.Rotate270FlipX Case 8 ' Image has been rotated 270 degrees clockwise rotateFlip = System.Drawing.RotateFlipType.Rotate270FlipNone End Select If rotateFlip <> System.Drawing.RotateFlipType.RotateNoneFlipNone Then image.RotateFlip(rotateFlip) End If End Sub ''' <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 Function BytesToImage(bytes As Byte()) As System.Drawing.Image Return StreamToImage(New System.IO.MemoryStream(bytes)) End Function ''' <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 Function StreamToImage(stream As System.IO.Stream) As System.Drawing.Image Return System.Drawing.Image.FromStream(stream) End Function End Module End Namespace End Namespace ' 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 46 47 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 9, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Imports Utils.Image Module Program Sub Main(args As String()) Try Dim path = $"" ' Image Dim image = System.Drawing.Image.FromFile(path) 'Dim newImage = image.Resize(New System.Drawing.Size(500, 500)) Dim newImage = image.Rotate(-90) ' Byte 'Dim bytes As Byte() 'Dim newImage = Utils.Image.Resize(bytes, New System.Drawing.Size(800, 800)) 'Dim newImage = Utils.Image.Rotate(bytes, 180) ' Stream 'Dim stream As New System.IO.MemoryStream 'Dim newImage = Utils.Image.Resize(stream, New System.Drawing.Size(2000, 2000)) 'Dim newImage = Utils.Image.Rotate(stream, 360) Dim newPath = $"" newImage.Save(newPath) Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' 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.
Leave a Reply