I am reducing the quality of an image and saving it to the file system. I wish to return the new data of the image in Base64 string format. How can I do this?
Code:
var bitmap = new Bitmap(Base64ToImage(base64String));
var jgpEncoder = GetEncoder(ImageFormat.Jpeg);
var myEncoder = Encoder.Quality;
var myEncoderParameters = new EncoderParameters(1);
var myEncoderParameter = new EncoderParameter(myEncoder, Convert.ToInt64(75L));
myEncoderParameters.Param[0] = myEncoderParameter;
bitmap.Save(filePath, jgpEncoder, myEncoderParameters);
Update:
Would the following be an appropriate method?
// Convert the image to byte[]
var stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Jpg);
var imageBytes = stream.ToArray();
// Convert byte[] to Base64 String
var reducedQuality = Convert.ToBase64String(imageBytes);
return reducedQuality;
Instead of saving it to a file, save it to a MemoryStream
. Then you can use:
string base64 = Convert.ToBase64String(stream.ToArray());
And to write the original binary data to a file:
using (var output = File.Create(filePath))
{
stream.CopyTo(output);
}
Alternatively, you could use ToBase64Transform
with a CryptoStream
:
using (var output = new CryptoStream(File.Create(filePath),
new ToBase64Transform())
{
bitmap.Save(output, jpgEncoder, myEncoderParameters);
}
That should write it to the file directly as base64.
See more on this question at Stackoverflow