我们有一段代码可以将 .Net System.Drawing.Bitmap 保存到文件中。 Save 调用指定文件位置以及我们希望将图像数据保存为 Jpeg 的 ImageFormat,因此代码如下所示:
public MediaFile IngestImage(System.Drawing.Bitmap imgSrc, string name){
... // left out because it is not relevant to this question
imgSrc.Save(fullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
... // left out because it is not relevant to this question
}
出于某种原因,此方法有时会将 PNG 图像生成为 .jpg 文件。大多数时候这不是什么大问题,但是项目的另一个部分存在这些文件不是实际 jpeg(Windows 媒体服务)的问题。
感谢任何帮助,有没有人见过这个?
注意: 完整路径类似于“\servcer\share\file.jpg”。我们使用扩展名“jpg”保存 jpg。因此问题...稍后我们在 Windows Media Server 上创建发布点以播放 SMIL 播放列表,然后我们必须在发布点开始播放时向发布点“通告”文件和格式,因为它需要 Jpg 文件是文件的扩展名,内容实际上是PNG
下面是创建传递给上述方法的 BitpMap 对象的实际代码...
public static Bitmap CreateBitmap(string text, int height, int width, Color foregroundColor, Color backgroundColor, string fontName, int fontSize, bool antialias)
{
// Initialize graphics
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
using (Graphics g = Graphics.FromImage(bmp))
{
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
//g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
if (antialias)
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.AntiAlias;
}
// Set colors
SolidBrush fgBrush = new SolidBrush(foregroundColor);
SolidBrush bgBrush = new SolidBrush(backgroundColor);
// paint background
RectangleF rectF = new RectangleF(0, 0, width, height);
g.FillRectangle(bgBrush, rectF);
// Load font
FontFamily fontFamily = FontFamily.GenericSerif;
Font font = new Font(fontFamily, fontSize, FontStyle.Regular, GraphicsUnit.Pixel);
try
{
fontFamily = new FontFamily(fontName);
font = new Font(fontFamily, fontSize, FontStyle.Regular, GraphicsUnit.Pixel);
}
catch { }
// Set font direction & alignment
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
// Finally, draw the text
g.DrawString(text, font, fgBrush, rectF, format);
return bmp;
}
}
最佳答案
我会通过以下方式解决这个问题:
削减
CreateBitmap()
。例如,如果您删除除调用new
的行和return
行之外的所有内容,是否会出现问题?我假设它会,但值得检查。如果此修改后问题消失的可能性很小,请使用 binary search看看您是否可以追踪到特定行。用
try
/catch
封装Save
调用,看看是否有某个地方出现了ExternalException
默默的吃了Bitmap.Save()
(继承自Image.Save()
)关于ExternalException
的说明如下:
The image was saved with the wrong image format.
-or-
The image was saved to the same file it was created from.
fullPath
中是否已经存在带有 .jpg 扩展名的 PNG 格式的失败文件?
关于c# - .Net 中的位图保存是否以不正确的格式保存图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1347652/