I want to use C# to convert a byteArray to base64string by using Convert.ToBase64String(), then I want to send this string to save using MySQL by sending post data to a PHP page. My problem is I can't convert this string back to a byteArray using this method as after this string is retrieved from the PHP page (after it got data from MySQL), it tells me that argument on method Convert.FromBase64String() was wrong.
I don't where is problem occurs, how can I solve it?
My code:
public static string BitmapToString(BitmapImage img)
{
try
{
WriteableBitmap bmp = new WriteableBitmap(img);
byte[] byteArray = null;
string str = null;
MemoryStream stream = new MemoryStream();
bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
byteArray = stream.ToArray();
str = Convert.ToBase64String(byteArray);
return str;
}
catch (System.Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
return null;
}
public static BitmapImage StringToBitmap(string str)
{
try
{
byte[] byteArray = Convert.FromBase64String(str);
Stream memStream = new MemoryStream(byteArray);
BitmapImage img = null;
MemoryStream stream = new MemoryStream(byteArray);
stream.Seek(0, SeekOrigin.Begin);
img = new BitmapImage();
img.SetSource(stream);
return img;
}
catch (System.Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
return null;
}
Convert.FromBase64String() will work for Convert.ToBase64String() results but there can be inputs in your aplication which not converted to Base64String, those cases might fail.
This is not be a issue with those two methods. Check Convert.ToBase64String() result and what you get when you read it from database.
Related
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
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);
}
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
public static string GetAvatar()
{
logger.Info("Start--GetAvatar");//aatif
// string headerText = "Bearer " + token;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.mxit.com/user/public/avatar/id");
//request.Method = method;
//request.Headers.Add(HttpRequestHeader.Authorization, headerText);
//if (contentType != null)
//{
// request.ContentType = contentType;
//}
string method = "GET";
if (method == "GET")
{
try
{
WebResponse response = request.GetResponse(); // Byte Stream
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
string JsonGET = responseFromServer.ToString();
// Avatar res = JsonConvert.DeserializeObject<Avatar>(JsonGET);
reader.Close();
dataStream.Close();
response.Close();
logger.Info("End--GetAvatar");//aatif
return JsonGET;
}
catch (Exception ex)
{
logger.Error("CacheData.GetAvatar():" + ex.StackTrace); /// Aatif
}
}
logger.Info("End--GetAvatar"); ///aatif
return null;
}
string avatar = MURLEngine.GetAvatar();
Showing Image in front end:
<span id="ProfileImage">
<img src="data:image/png;base64,#Model.avatarimage" />
</span>
How do i show the byte stream image on the front end? I am unable to do so right now.
You're close. Convert to base64.
(The other answers don't directly relate to your need for a WebRequest.)
public static string GetAvatar()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.mxit.com/user/public/avatar/vini.katyal");
WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
MemoryStream ms = new MemoryStream();
responseStream.CopyTo(ms);
byte[] buffer = ms.ToArray();
string result = Convert.ToBase64String(buffer);
response.Close();
responseStream.Close();
return result;
}
I suggest you create a GET method in your controller which accepts an id of your row or something. Based on that just fetch the byte array and send it back to the as an contentresult. Here is an example for that:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Image(int id)
{
byte[] byteArray = _imageRepository.GetImage(id);
return new FileContentResult(byteArray, "image/jpeg");
}
In the view you can call this controller method in following way:
<img src="Image/1234" alt="Image 1234"/>
Try to use Convert class methods. You can make use of Convert.ToBase64String method to convert a byte array to base64 string representation of the image.
Example from MSDN:
try {
inFile = new System.IO.FileStream(inputFileName,
System.IO.FileMode.Open,
System.IO.FileAccess.Read);
binaryData = new Byte[inFile.Length];
long bytesRead = inFile.Read(binaryData, 0,
(int)inFile.Length);
inFile.Close();
}
catch (System.Exception exp) {
// Error creating stream or reading from it.
System.Console.WriteLine("{0}", exp.Message);
return;
}
// Convert the binary input into Base64 UUEncoded output.
string base64String;
try {
base64String =
System.Convert.ToBase64String(binaryData,
0,
binaryData.Length);
}
catch (System.ArgumentNullException) {
System.Console.WriteLine("Binary data array is null.");
return;
}
Here is another example that I found.
I solved the issue:
WebResponse response = request.GetResponse();
byte[] b = null;
using (Stream stream = response.GetResponseStream())
using (MemoryStream ms = new MemoryStream())
{
int count = 0;
do
{
byte[] buf = new byte[1024];
count = stream.Read(buf, 0, 1024);
ms.Write(buf, 0, count);
} while (stream.CanRead && count > 0);
b = ms.ToArray();
}
return Convert.ToBase64String(b);
I firstly convert the response to Stream and then to Byte array then to the base64 string