简体   繁体   中英

Rotate byte array Image and encode to Base64 string

I am having a very difficult time trying to figure this one out:

I am working with a front-end which

  1. Reads an image taken from a mobile device to a byte array
  2. Converts the byte array to be stored as a Base64 string
  3. Sends the Base64 string to a database

The back-end is only slated to store images as Base64 strings, as it later embeds the image as a Base64 string to an email for the user whose email application will only show Base64-embedded images. The problem is that the images are embedding 90 degrees counter-clockwise in the email, so I am trying to rotate the image 90 degrees before encoding the base64 string which is inserted into a Sql stored procedure (executed from the application). I feel like this code should simply do the trick:

HttpPostedFile img = imageUpload.PostedFile;
Stream stream = img.InputStream;
BinaryReader binaryReader = new BinaryReader(stream);
byte[] bytes = binaryReader.ReadBytes((int)stream.Length);
// Rotate Image Code (help):
using (var memoryStream = new MemoryStream(bytes))
{
var rotateImage = System.Drawing.Image.FromStream(memoryStream);                  rotateImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
rotateImage.Save(memoryStream, rotateImage.RawFormat);
bytes = memoryStream.ToArray();
}
// End Rotate Image Code
insert.Parameters.AddWithValue("@Image",Convert.ToBase64String(bytes));

But I am receiving an error when I try and run it: System.ArgumentNullException: Value cannot be null. Parameter name: encoder at the line "bytes = memoryStream.ToArray();"

When I try and save it as a jpeg the image gets chopped off at the top, but no other formats work.

I think there is a problem in the line:

rotateImage.Save(memoryStream, rotateImage.RawFormat);

Maybe you should specify the format. Try with:

rotateImage.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);

Or even better, you can catch and force convertion only when there is an exception:

try
{
    rotateImage.Save(memoryStream, rotateImage.RawFormat);
}
catch (System.ArgumentNullException) 
{
    rotateImage.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}

I think the issue is related to this answer

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