How do you convert an image from a path on the user's computer to a base64 string in C#?
For example, I have the path to the image (in the format C:/image/1.gif) and would like to have a data URI like data:image/gif;base64,/9j/4AAQSkZJRgABAgEAYABgAAD.. representing the 1.gif image returned.
Try this
using (Image image = Image.FromFile(Path))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
Get the byte array (byte[]) representation of the image, then use Convert.ToBase64String(), st. like this:
byte[] imageArray = System.IO.File.ReadAllBytes(#"image file path");
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
To convert a base64 image back to a System.Drawing.Image:
var img = Image.FromStream(new MemoryStream(Convert.FromBase64String(base64String)));
Since most of us like oneliners:
Convert.ToBase64String(File.ReadAllBytes(imageFilepath));
If you need it as Base64 byte array:
Encoding.ASCII.GetBytes(Convert.ToBase64String(File.ReadAllBytes(imageFilepath)));
This is the class I wrote for this purpose:
public class Base64Image
{
public static Base64Image Parse(string base64Content)
{
if (string.IsNullOrEmpty(base64Content))
{
throw new ArgumentNullException(nameof(base64Content));
}
int indexOfSemiColon = base64Content.IndexOf(";", StringComparison.OrdinalIgnoreCase);
string dataLabel = base64Content.Substring(0, indexOfSemiColon);
string contentType = dataLabel.Split(':').Last();
var startIndex = base64Content.IndexOf("base64,", StringComparison.OrdinalIgnoreCase) + 7;
var fileContents = base64Content.Substring(startIndex);
var bytes = Convert.FromBase64String(fileContents);
return new Base64Image
{
ContentType = contentType,
FileContents = bytes
};
}
public string ContentType { get; set; }
public byte[] FileContents { get; set; }
public override string ToString()
{
return $"data:{ContentType};base64,{Convert.ToBase64String(FileContents)}";
}
}
var base64Img = new Base64Image {
FileContents = File.ReadAllBytes("Path to image"),
ContentType="image/png"
};
string base64EncodedImg = base64Img.ToString();
You can easily pass the path of the image to retrieve the base64 string
public static string ImageToBase64(string _imagePath)
{
string _base64String = null;
using (System.Drawing.Image _image = System.Drawing.Image.FromFile(_imagePath))
{
using (MemoryStream _mStream = new MemoryStream())
{
_image.Save(_mStream, _image.RawFormat);
byte[] _imageBytes = _mStream.ToArray();
_base64String = Convert.ToBase64String(_imageBytes);
return "data:image/jpg;base64," + _base64String;
}
}
}
Hope this will help.
You can use Server.Map path to give relative path and then you can either create image using base64 conversion or you can just add base64 string to image src.
byte[] imageArray = System.IO.File.ReadAllBytes(Server.MapPath("~/Images/Upload_Image.png"));
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
This code works well with me on DotNet Core 6
using (Image image = Image.FromFile(path))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, ImageFormat.Jpeg);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
// In my case I didn't find the part "data:image/png;base64,", so I added.
return $"data:image/png;base64,{base64String}";
}
}
That way it's simpler, where you pass the image and then pass the format.
private static string ImageToBase64(Image image)
{
var imageStream = new MemoryStream();
try
{
image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Bmp);
imageStream.Position = 0;
var imageBytes = imageStream.ToArray();
var ImageBase64 = Convert.ToBase64String(imageBytes);
return ImageBase64;
}
catch (Exception ex)
{
return "Error converting image to base64!";
}
finally
{
imageStream.Dispose;
}
}
Based on top voted answer, updated for C# 8. Following can be used out of the box. Added explicit System.Drawing before Image as one might be using that class from other namespace defaultly.
public static string ImagePathToBase64(string path)
{
using System.Drawing.Image image = System.Drawing.Image.FromFile(path);
using MemoryStream m = new MemoryStream();
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
tring base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
The following piece of code works for me:
string image_path="physical path of your image";
byte[] byes_array = System.IO.File.ReadAllBytes(Server.MapPath(image_path));
string base64String = Convert.ToBase64String(byes_array);
The reverse of this for the googlers arriving here (there is no SO quesion/answer to that)
public static byte[] BytesFromBase64ImageString(string imageData)
{
var trunc = imageData.Split(',')[1];
var padded = trunc.PadRight(trunc.Length + (4 - trunc.Length % 4) % 4, '=');
return Convert.FromBase64String(padded);
}
Something like that
Function imgTo64(ByVal thePath As String) As String
Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(thePath)
Dim m As IO.MemoryStream = New IO.MemoryStream()
img.Save(m, img.RawFormat)
Dim imageBytes As Byte() = m.ToArray
img.Dispose()
Dim str64 = Convert.ToBase64String(imageBytes)
Return str64
End Function
Related
I am trying to create an API which will save an image at a given location .
Below is my Code for that
Image image = Image.FromFile(#"C:\Users\abc\Desktop\img-logo.jpg");
byte[] bytes = (byte[])(new ImageConverter()).ConvertTo(image, typeof(byte[]));
string str = Convert.ToBase64String(bytes);
Save_Application_Image("12004", str);
and the method in API
public void Save_Application_Image(string staffCode , string bytearray)
{
try
{
byte[] bytes = Convert.FromBase64String(bytearray);
file_path = "~/uploads/" + file_name;
FileStream file = File.Create(HttpContext.Current.Server.MapPath(file_path));
file.Write(bytes, 0, bytes.Length);
file.Close();
}
catch(Exception ex)
{
logger.LogError(ex);
}
finally
{
}
}
This api has to be called from Android Application so I will receive two string parameter.
It is saving the file perfectly but file is not readable. No preview for image file.
What is the right approach for this ?
I'm unsure of how the ImageConverter works, but I've used this before to convert Images to byte[]:
Image image = Image.FromFile(#"C:\Users\abc\Desktop\img-logo.jpg");
using (var stream = new MemoryStream())
{
image.Save(stream);
string savedImage = Convert.ToBase64String(stream.ToArray());
Save_Application_Image("12004", str);
}
I have a base64 image and i have to convert it into Image. I am doing this using this code:
public static Image ConvertBase64StringToImage(string imageBase64String)
{
var imageBytes = Convert.FromBase64String(imageBase64String);
var imageStream = new MemoryStream(imageBytes, 0, imageBytes.Length);
imageStream.Write(imageBytes, 0, imageBytes.Length);
var image = Image.FromStream(imageStream, true);
return image;
}
Then i have to convert this Image into base64 again. Im using this code:
public static string ConvertImageToBase64String(Image image)
{
var imageStream = new MemoryStream();
image.Save(imageStream, ImageFormat.Png);
imageStream.Position = 0;
var imageBytes = imageStream.ToArray();
return Convert.ToBase64String(imageBytes);
}
After converting the original base64Image to image and again to base64, it loses quality.The Original base64 image is 1676 in length and after conversion it has 1660 in length.
I need the same image after conversion because i have to compare it. Any ideas how to do it without losing quality?
According to this page although PNG files are lossless, you can specify how much file compression to use when storing. IMO, as long as the Image comes out the same (you can compare them using some sort of MD5 tool), it doesn't matter if the size of the file is different when you save it, as the actual image is still the same as the original.
This is how to convert and compare your images, if the result from CompareImages is zero, it means that they are equal or very similar.
static void Main(string[] args)
{
Image img = new Bitmap("Koala.jpg");
string img64Bit = ConvertImageToBase64String(img);
Image newImg = ConvertBase64StringToImage(img64Bit);
newImg.Save("KoalaCopy.jpg");
Console.WriteLine(CompareImages(img, newImg));
Console.ReadLine();
}
public static string ConvertImageToBase64String(Image image)
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, image.RawFormat);
return Convert.ToBase64String(ms.ToArray());
}
}
public static Image ConvertBase64StringToImage(string image64Bit)
{
byte[] imageBytes = Convert.FromBase64String(image64Bit);
return new Bitmap(new MemoryStream(imageBytes));
}
public static int CompareImages(Image i1, Image i2)
{
string img1 = ConvertImageToBase64String(i1);
string img2 = ConvertImageToBase64String(i2);
return String.Compare(img1, img2);
}
Im using the following code to get the signature from the signature pad, But any value doesn't come.
try {
var signature = padView.GetImage (Acr.XamForms.SignaturePad.ImageFormatType.Png);
using (BinaryReader br = new BinaryReader (signature)) {
var result = br.ReadBytes ((int)signature.Length);
}
} catch (Exception ex) {
// Helper_ErrorHandling.SendErrorToServer (ex);
}
Am I ding it wrong, Also how do i convert this to a base64 string
?
I'm not too familiar with the Xamarin Forms Signature Pad, but if you're looking for a way to convert a Stream to as base64 string, try this:
[...]
string base64String;
using (var memoryStream = new MemoryStream())
{
signature.CopyTo( memoryStream );
var byteArray = memoryStream.ToArray();
base64String = Convert.ToBase64String( byteArray );
}
EDIT: you can most of the time skip the copy, if you check if signature is already a MemoryStream...
[...]
string base64String;
var signatureMemoryStream = signature as MemoryStream;
if (signatureMemoryStream == null)
{
signatureMemoryStream = new MemoryStream();
signature.CopyTo( signatureMemoryStream );
}
var byteArray = signatureMemoryStream.ToArray();
base64String = Convert.ToBase64String( byteArray );
Using the most current PCL compliant Xamarin package :
acr-xamarin-forms
This method works like a charm!
private string ConvertSignatureToBase64()
{
try
{
byte[] data;
if(Device.OS == TargetPlatform.iOS)
{
var img = SignaturePad.GetImage(Acr.XamForms.SignaturePad.ImageFormatType.Jpg);
var signatureMemoryStream = new MemoryStream();
img.CopyTo(signatureMemoryStream);
data = signatureMemoryStream.ToArray();
}
else
{
var img = SignaturePad.GetImage(Acr.XamForms.SignaturePad.ImageFormatType.Jpg);
var signatureMemoryStream = (MemoryStream)img;
data = signatureMemoryStream.ToArray();
}
return Convert.ToBase64String(data);
}
catch(Exception ex)
{
return ex.ToString();
}
}
This is my code:
string photo = "somedata";
byte[] byt = System.Text.Encoding.UTF8.GetBytes(photo);
string strModified = Convert.ToBase64String(byt);
byte[] photoData = Convert.FromBase64String(strModified);
Image img = cnvrtToImg(photoData);
public Image cnvrtToImg(byte[] byteArrayIn)
{
using (MemoryStream mStream = new MemoryStream(byteArrayIn))
{
return Image.FromStream(mStream);
}
}
When the method cnvrtToImg is invoked, I get an error
Parameter is not valid
Please give me a solution
I think that System.Text.Encoding.UTF8 is not for image data, it is for text, not binary data. UTF8 just can't do some binary sequence. Base64 is the choice if you need convert binary to text.
I test with this, and confirm the cnvrtToImg is correct:
class Program
{
public static Image cnvrtToImg(byte[] byteArrayIn)
{
using (MemoryStream mStream = new MemoryStream(byteArrayIn))
{
return Image.FromStream(mStream);
}
}
static void Main(string[] args)
{
using (var file = File.Open(#"D:\0.jpg", FileMode.Open))
{
var buffer = new byte[file.Length];
file.Read(buffer, 0, (int) file.Length);
cnvrtToImg(buffer);
}
}
}
//finish
I want to base64 encode an image that is being received as HttpPostedFileBase to send it in a json object and I don't know how it can be done...and please tell me how can I decode it back to HttpPostedFileBase
I tried this and it worked
string theFileName = Path.GetFileName(YourFile.FileName);
byte[] thePictureAsBytes = new byte[YourFile.ContentLength];
using (BinaryReader theReader = new BinaryReader(YourFile.InputStream))
{
thePictureAsBytes = theReader.ReadBytes(YourFile.ContentLength);
}
string thePictureDataAsString = Convert.ToBase64String(thePictureAsBytes);
Follow the below steps to convert the HttpPostedFileBase to Base64String type
public ActionResult ParseCv(HttpPostedFileBase cvFile)
{
byte[] fileInBytes = new byte[cvFile.ContentLength];
using (BinaryReader theReader = new BinaryReader(cvFile.InputStream))
{
fileInBytes = theReader.ReadBytes(cvFile.ContentLength);
}
string fileAsString= Convert.ToBase64String(fileInBytes);
return Content(fileAsString);
}
You can do this:
byte[] binaryData;
binaryData = new Byte[product.BrochureFile.InputStream.Length];
long bytesRead = product.BrochureFile.InputStream.Read(binaryData, 0, (int)product.BrochureFile.InputStream.Length);
product.BrochureFile.InputStream.Close();
string base64String = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);