System.Drawing.Image.FromFile()处理图片,内存不足错误
在批量为图片添加图片水印的时候,出现“内存不足”的错误。水印方法如下(网上找来的):
/// <summary>
/// 为图片添加图片水印
/// </summary>
/// <param name="originalimage"></param>
/// <param name="MarkImg">水印图片绝对路径</param>
public static void Add_ImgWartMark(string originalimage,string MarkImg)
{
System.Drawing.Image image = System.Drawing.Image.FromFile(originalimage);
System.Drawing.Image copyImage = System.Drawing.Image.FromFile(MarkImg);
Graphics g = Graphics.FromImage(image);
g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
g.Dispose();
string extension = Path.GetExtension(originalimage);
string newPath = originalimage.Replace(extension, "_w" + extension);
image.Save(newPath);
image.Dispose();
copyImage.Dispose();
image = null;
copyImage = null;
}
之前没有判断图片的格式,就直接把图片的地址传了进来,结果一直出现“内存不足”的错误。这是因为在外层遍历文件的时候,没有判断是否是图片就传了进来。/// 为图片添加图片水印
/// </summary>
/// <param name="originalimage"></param>
/// <param name="MarkImg">水印图片绝对路径</param>
public static void Add_ImgWartMark(string originalimage,string MarkImg)
{
System.Drawing.Image image = System.Drawing.Image.FromFile(originalimage);
System.Drawing.Image copyImage = System.Drawing.Image.FromFile(MarkImg);
Graphics g = Graphics.FromImage(image);
g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
g.Dispose();
string extension = Path.GetExtension(originalimage);
string newPath = originalimage.Replace(extension, "_w" + extension);
image.Save(newPath);
image.Dispose();
copyImage.Dispose();
image = null;
copyImage = null;
}
所以在外面判断下图片格式就没什么问题了。
if(Path.GetExtension(file.Name)!=".jpg")
{
//调水印方法
}
{
//调水印方法
}