I had to convert GIF to JPEG. I had to save the bytes to image then reopen it and convert it to JPEG. I tried to change the type using two streams but I got error "A generic error occurred in GDI+". Is there any explanation for this?
public static byte[] GetJpegBytes(byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
{
var temporaryImage = $"{Path.Combine(System.Web.HttpRuntime.AppDomainAppPath, Guid.NewGuid().ToString())}.jpeg";
var image = Image.FromStream(stream);
image.Save(temporaryImage, ImageFormat.Jpeg);
using (var memoryStream = new FileStream(temporaryImage, FileMode.Open))
{
byte[] byteRsult = new byte[memoryStream.Length];
memoryStream.Read(byteRsult, 0, (int)memoryStream.Length);
memoryStream.Close();
File.Delete(temporaryImage);
return byteRsult;
}
}
}
You can use this extension for convert format image I use this simple extension to convert a stream.
public static Stream ConvertImage(this Stream originalStream, ImageFormat format)
{
var image = Image.FromStream(originalStream);
using(var stream = new MemoryStream())
{
image.Save(stream, format);
stream.Position = 0;
return stream;
}
}
usage:
var outputStream = stream.ConvertImage(ImageFormat.Png);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With