Bitmap.Save上出现GDI+异常
本文关键字:GDI+ 异常 Save Bitmap | 更新日期: 2023-09-27 18:20:26
我想保存调整大小的图像,但我遇到了GDI+错误。代码:
System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(path));
float aspectRatio = (float)image.Size.Width / (float)image.Size.Height;
int newHeight = 200;
int newWidth = Convert.ToInt32(aspectRatio * newHeight);
System.Drawing.Bitmap thumbBitmap = new System.Drawing.Bitmap(newWidth, newHeight);
System.Drawing.Graphics thumbGraph = System.Drawing.Graphics.FromImage(thumbBitmap);
thumbGraph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
thumbGraph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbGraph.DrawImage(image, imageRectangle);
thumbBitmap.Save("~/images/galeria/thumb/" + FileUpload1.FileName);
thumbGraph.Dispose();
thumbBitmap.Dispose();
image.Dispose();
错误是由以下行引起的:
thumbBitmap.Save("~/images/galeria/thumb/" + FileUpload1.FileName);
有什么解决办法吗?
第1版:
System.Drawing.dll中发生类型为"System.Runtime.InteropServices.ExternalException"的异常,但未在用户代码中处理
附加信息:GDI+中出现一般性错误。
您的代码有几个错误:
thumbBitmap.Save("~/images/galeria/thumb/" + FileUpload1.FileName);
- 只能在通过
HttpServerUtility.MapPath
(即this.Server.MapPath
)的路径中使用~
字符。GDI需要一个有效的Win32文件名。您需要先翻译文件名 - 您不能信任上载文件的
FileName
属性:某些版本的Internet Explorer提供完整的本地文件名,这意味着您的路径将是无效的.../galeria/thumb/D:'Me'myfile.jpg
。其他网络浏览器通常会提供一个假名称,并且只保留文件扩展名。您也不能信任用户提供正确的扩展。如果用户上传了一个恶意文件,该文件可以被解释为有效的位图,但也是一个有效的PHP脚本,可以擦除服务器的HDD,会发生什么 - 与显式调用
Dispose
方法相比,您应该始终更喜欢using
块 - 导入
System.Drawing
命名空间,这样就不会在代码中指定完整的类型名称 - 您正在将缩略图保存为位图,这些都是未压缩的大文件。您应该将它们压缩为JPEG或PNG图像。您还使用原始图像的文件扩展名保存了该图像(您无法信任该扩展名)
以下是我将如何改进它:
using( Image image = Image.FromFile( Server.MapPath( path ) ) ) {
float aspectRatio = (float)image.Size.Width / (float)image.Size.Height;
int newHeight = 200;
int newWidth = (ToInt32)( aspectRatio * newHeight );
using( Bitmap thumbBitmap = new System.Drawing.Bitmap( newWidth, newHeight ) )
using( Graphics thumbGraph = Graphics.FromImage( thumbBitmap ) ) {
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbGraph.DrawImage( image, imageRectangle );
String outputFileName = this.Server.MapPath( "~/images/galeria/thumb" );
outputFileName = Path.Combine( outputFileName, Path.GetFileNameWithoutExtension( path ) ) + ".jpg";
// Use code from here to save as a JPEG: https://msdn.microsoft.com/en-us/library/bb882583(v=vs.110).aspx
thumbBitmap.Save( outputFileName, jpegEncoder, jpegEncoderParameters );
}
}