我们的代码中有这个方法。它将图像(png,gif等)转换为jpeg。
public static byte[] ImageToJpeg(byte[] content, long quality)
{
try
{
byte[] fileContent = null;
using (System.IO.MemoryStream readMemoryStream = new System.IO.MemoryStream(content))
{
using (System.Drawing.Bitmap image = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(readMemoryStream, true))
{
System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;
System.Drawing.Imaging.ImageCodecInfo jpgCodecInfo = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);
System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
System.Drawing.Imaging.EncoderParameter encoderParameter = new System.Drawing.Imaging.EncoderParameter(encoder, quality);
encoderParameters.Param[0] = encoderParameter;
using (System.IO.MemoryStream writeMemoryStream = new System.IO.MemoryStream())
{
image.Save(writeMemoryStream, jpgCodecInfo, encoderParameters);
fileContent = writeMemoryStream.ToArray();
}
}
}
return fileContent;
}
catch (System.Exception exception)
{
System.InvalidCastException invalidCastException = new System.InvalidCastException("Invalid conversion", exception);
throw invalidCastException;
}
}
它适用于我们的语言环境机器上的所有图像。部署在服务器上时,我们在此方法中获得了一些“GDI +中发生了一般错误”错误。
有什么想法吗?谢谢!