Skip to content

Instantly share code, notes, and snippets.

@alexdelgado0792
Created April 17, 2019 17:01
Show Gist options
  • Save alexdelgado0792/5780b908dec137df24dba53c8fb6b6a3 to your computer and use it in GitHub Desktop.
Save alexdelgado0792/5780b908dec137df24dba53c8fb6b6a3 to your computer and use it in GitHub Desktop.
Images util
using System;
using System.Drawing;
using System.IO;
namespace Util
{
public class ImageUtil
{
/// <summary>
/// Convert Image to Byte
/// </summary>
/// <param name="img">Image to convert</param>
/// <returns>image in byte array</returns>
public static byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
/// <summary>
/// For use of src="data:image/png;base64,(string Base64 imageBytes) in img HTML tag
/// </summary>
/// <param name="imageBytes">image in byte array</param>
/// <returns>string of the image in Base64</returns>
public static string ImageToBase64(byte[] imageBytes)
{
return Convert.ToBase64String(imageBytes);
}
/// <summary>
/// For use of src="data:image/png;base64,(string Base64 imageBytes) in img HTML tag
/// </summary>
/// <param name="filePath">File path of the image</param>
/// <returns>string of the image in Base64</returns>
public static string ImageToBase64(string filePath)
{
string imageBase64;
using (var image = Image.FromFile(filePath))
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, image.RawFormat);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
imageBase64 = Convert.ToBase64String(imageBytes);
}
}
return imageBase64;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment