how to convert image into string in c#? Especially

2019-10-02 07:39发布

问题:

I am new to c#. I am developing an iOS project. i want to upload images to server. So i want to convert image into string. can anyone help me to do this.

I am agree any type of method to upload image to sever.

回答1:

How about that?

FileStream stream = new FileStream(imageFilePath, FileMode.Open);
BinaryReader binreader = new BinaryReader(stream);
byte[] buffer = new byte[(int) stream.Length];
buffer = binreader.ReadBytes((int) stream.Length);
string serialized = Convert.ToBase64String(buffer)

If you have the System.Drawing.Image object instead of a file path, you can do:

System.Drawing.Image image; //initialize it someway
MemoryStream ms = new MemoryStream();
image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg); //if it is jpeg
byte[] buffer = ms.ToArray();
string serialized = Convert.ToBase64String(buffer);

And then you pass the 'serialiazed' value to the server.

Put if it will work depends on how the server will handle that.



回答2:

The same just a little bit less code

//Clientside    
byte[] imgBytes = File.ReadAllBytes("FilePath");
string imgStr = System.Convert.ToBase64String(imgBytes);

//Serverside 
byte[] serverSideImgBytes = System.Convert.FromBase64String(imgStr);
File.WriteAllBytes("PathAndFileName", serverSideImgBytes);