简体   繁体   中英

How can I convert javascript jpeg string image to C# image bytes?

I am reading the image content in React Front-end App using javascript FileReader() as

return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = e => resolve(e.target.result);
    reader.onerror = reject;   
    reader.readAsDataURL(file);   // file is a jpeg file
  });

Now, I want to pass this image string C# SDK, which accepts image data bytes of the form

var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
fileStream.Close();

How do I convert the image string? I have tried by just removing the initial image format padding as

Face= Face.Replace("data:image/jpeg;base64,", string.Empty);

And then passed Face to bytes buffer as

byte[] buffer = Encoding.UTF8.GetBytes(Face); //also tried Convert.FromBase64String(Face);

First you need to decode the Base64 string by using Convert.FromBase64String . Then you can load your image from the resulting byte array using some sort of image library.

Example (haven't tested it):

Face = Face.Replace("data:image/jpeg;base64,", string.Empty);
byte[] FaceBytes = Convert.FromBase64String(Face);
using (var ms = new MemoryStream(FaceBytes ))
{
    var image = Image.FromStream(ms);
    // Do something with image
}

Or you can just simply use the FaceBytes array for whatever you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM