How to convert base64String to image?
This is a example to convert base64String to image using the HttpHandler. Here we get base64string as input from the client and then Remove any blank spaces with + symbol. Lenth of the Base-64 string should be multiples of 4 and it was converted as byte array. Byte array then assigned to the handler class variable, there the byte array converted to image and assigned to image control.
Method that handles users base64String
protected void Button_Click(object sender, EventArgs e)
{
byte[] byte_array;
string base_64_string;
// Remove any blank spaces with + symbol, because it will show error as " Invalid character in a Base-64 string. "
base_64_string = TextBox.Text.Replace(" ", "+");
// Lenth of the Base-64 string should be multiples of 4, so add one or two equals at the end.
int count = (base_64_string).Length % 4;
if (count > 0)
{
base_64_string += new string('=', (4 - count));
}
// Convert from base 64 string to byte[]
byte_array = Convert.FromBase64String(s);
ImageHandler.byt = byte_array;
// Call handler class that will convert the byte[] to image URL
Image.ImageUrl = "ImageHandler.ashx";
}ImageHandler class to convert byte[] to image
using System.Web;
using System.Web.Services;
namespace WebApp
{
///
/// Summary description for $codebehindclassname$
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class ImageHandler : IHttpHandler
{
public static byte[] byt;
// Converts byte to image and assigns to image control
public void ProcessRequest(HttpContext context)
{
if (byt != null)
{
context.Response.ContentType = "image/png/jpeg";
context.Response.OutputStream.Write(byt, 0, byt.Length);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}