.NET Core3.1保存图片,首先引用System.Drawing.Common
/// <summary> /// 保存图片 /// </summary> /// <param name="img">图片文件</param> /// <param name="width">指定宽度</param> /// <param name="height">指定高度</param> /// <param name="mode">缩放类型:HW、W、H、Cut</param> /// <param name="msg"></param> private static string SaveImage(Image img, int width, int height, string mode, string msg) { string imgName = string.Empty; Image originalImage = img; int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; switch (mode) { case "HW"://指定高宽缩放(可能变形) break; case "W"://指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case "H"://指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case "Cut"://指定高宽裁减(不变形) if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } break; default: break; } //新建一个bmp图片 Image bitmap = new Bitmap(towidth, toheight); using (var g = Graphics.FromImage(bitmap)) { //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel); var font = new Font(FontFamily.GenericSansSerif, 20, FontStyle.Bold, GraphicsUnit.Pixel); var color = Color.FromArgb(128, 255, 255, 255); var brush = new SolidBrush(color); var point = new Point(towidth - 100, toheight - 30); g.DrawString(msg, font, brush, point); } try { string filePath = AppDomain.CurrentDomain.BaseDirectory + "Picture\\"; string dir = Path.GetDirectoryName(filePath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } Random rd = new Random(); imgName = $"{ToUnixTimestampByMilliseconds(DateTime.Now)}{rd.Next(0,1000000)}.jpg"; //以jpg格式保存缩略图 bitmap.Save($"{filePath}{imgName}", ImageFormat.Jpeg); return imgName; } catch (Exception e) { throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); } }
如果报错:A generic error occurred in GDI+ 需要从以下4个方面进行分析:
1. 相应的帐户没有写权限。
解决方法:赋予 NETWORK SERVICE 帐户以写权限,赋予权限方法这里不做表述。
2. 指定的物理路径不存在。
解决方法:
在调用 Save 方法之前,先判断目录是否存在,若不存在,则创建。
if (!Directory.Exists(dirpath))
Directory.CreateDirectory(dirpath);
3.生成的文件名格式有误:
我这里就是这个错误,因为我保存的文件名是获取的当前时间,生成的格式是yyyy-MM-dd HH:mm:ss,这个格式也导致报这个错,经过
排查,发现是HH:mm:ss中的:导致的原因,最终将:移除,就能正常保存。
4.文件被锁定
有个简单的土方法解决,将bitmap复制一份并且释放掉之前的bitmap就可以保存了
例如:
Bitmap bmpTemp = new Bitmap(image);
Bitmap bmp = new Bitmap(bmpTemp);
bmpTemp.Dispose();
bmp.Save(image, ImageFormat.Jpeg);