Ever need to store a picture in a database? It's not the easiest thing to do, but this class I wrote makes it pretty quick and easy.
The attached project consists of a VB.NET class that does all the hard work for you. With this class you can:
1) Convert an image to a Base64 object
2) Convert a Base64 object back to an image
3) Convert an array of bytes to an image
4) Convert an image to an array of bytes
It works quickly and you will be able to save images as strings in your database. A string is a much easier thing to save than an image IMO.
I also built out a quick sample project so you can see how the class works and how you can use it.
Here's the code of my class:
vb.net Code:
Imports System.IO
Imports System.Drawing
''' <summary>
''' ImageToByteArray - Takes in an image and converts it to an array of bytes - PREFERRED METHOD
''' ImageToBase64 - Takes in an image and converts it to a Base64 string
''' ByteArrayToImage - Takes in a byte array and converts it to an image - PREFERRED METHOD
''' Base64ToImage - Takes in a Base64 string and converts it to an image
''' </summary>
''' <remarks>Thanks to jmcilhinney for his insight and remarks on the following methods</remarks>
Public Class I2BB2I
Public Shared Function ImageToByteArray(img As Image) As Byte()
Using strm As New MemoryStream
img.Save(strm, img.RawFormat)
Return strm.GetBuffer()
End Using
End Function
Public Shared Function ImageToBase64(img As Image) As String
The attached example is a quick and dirty way of showing what the small class can do. This was written in VS2012, but should convert backwards pretty easily if you are looking to play with the source code. Feel free to modify it and do whatever you want to it.
Last edited by mbutler755; Jan 16th, 2014 at 08:25 PM.
Reason: Update class & project