背景
邮件中需要发送一些图片报表,报表长宽比过大, 长度 1800,宽 8000,此时发送到邮件显示的图片宽度过小。此时在HTML设置长宽等参数无效
解决方案
尝试发送一张 1000 * 1000的图片,设置图片的长宽各为1000,此时在邮件中显示正常。
使用代码将图片进行分割,除了最后一张图片,所以图片的高度都为1000,接图片分割之后插入到HTML模板中,发送到邮箱。
代码
1、先将base64转图片
public Image ConvertBase64ToImage(string base64String){byte[] imageBytes = Convert.FromBase64String(base64String);using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length)){ms.Write(imageBytes, 0, imageBytes.Length);Image image = Image.FromStream(ms, true);return image;}}
2、计算长宽比,按照图片宽度1000的比例
var ratio = img.Width / 1000.0;
img = ResizeImage(img, 1000, Convert.ToInt32(img.Height / ratio));
3、重新设置图片大小,按照图片宽度1000生成
public Bitmap ResizeImage(Image originalImage, int maxWidth, int maxHeight){int originalWidth = originalImage.Width;int originalHeight = originalImage.Height;float aspectRatio = (float)originalWidth / (float)originalHeight;int resizedWidth = maxWidth;int resizedHeight = (int)(maxWidth / aspectRatio);if (resizedHeight > maxHeight){resizedHeight = maxHeight;resizedWidth = (int)(maxHeight * aspectRatio);}Bitmap resizedImage = new Bitmap(resizedWidth, resizedHeight);using (Graphics graphics = Graphics.FromImage(resizedImage)){graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;graphics.DrawImage(originalImage, 0, 0, resizedWidth, resizedHeight);}return resizedImage;}
4、计算需要分割几张图片
var count = Math.Ceiling(img.Height / 1000.0);
5、生成分割的图片并转 Base64字符串
List<Image> imgs = new List<Image>();var builder = new StringBuilder();for (int i = 0; i < count; i++){var height = 1000;var width = 1000;if ((i + 1) == count){height = img.Height - i * 1000;}var temp = CropImage(img, new Rectangle(0, i * 1000, width, height));//temp.Save(@"C:\myfiles\" + i + ".png");var imgBase64Str = ImageToBase64(temp);builder.Append($"<img width=\"{width}\" height=\"{height}\" src=\"data:image/png;base64,{imgBase64Str}\" />");}
6、将生成的小图转Base64
public string ImageToBase64(Image image){using (MemoryStream ms = new MemoryStream()){image.Save(ms, ImageFormat.Jpeg);byte[] imageBytes = ms.ToArray();return Convert.ToBase64String(imageBytes);}}