代码写多了,有些使用过的方法和技巧会一时半会想不起来,平日记录下来,方便自己和有需要的人日后查阅。
using (var stream = new FileStream(physicalPath, FileMode.Open, FileAccess.Read)) { Bitmap target = null; int targetWidth, targetHeight; try { using (var bitmap = new Bitmap(stream)) { var size = bitmap.PhysicalDimension; if (size.Width > size.Height) { if (size.Width > _maximumWidth) { targetWidth = _maximumWidth; targetHeight = (int)size.Height * _maximumWidth / (int)size.Width; } else { targetWidth = (int)size.Width; targetHeight = (int)size.Height; } if (targetHeight >= _maximumHeight) { targetWidth = targetWidth * _maximumHeight / targetHeight; targetHeight = _maximumHeight; } } else { if (size.Height > _maximumHeight) { targetHeight = _maximumHeight; targetWidth = (int)size.Width * _maximumHeight / (int)size.Height; } else { targetHeight = (int)size.Height; targetWidth = (int)size.Width; } if (targetWidth >= _maximumWidth) { targetHeight = targetHeight * _maximumWidth / targetWidth; targetWidth = _maximumWidth; } } SizeF targetSize = SizeF.Empty; targetSize = new SizeF(targetWidth, targetHeight); target = new Bitmap(targetWidth, targetHeight);
using (var graphics = Graphics.FromImage(target)) { graphics.CompositingQuality = compositingQuality; graphics.InterpolationMode = interpolationMode; graphics.CompositingMode = CompositingMode.SourceCopy; graphics.DrawImage(bitmap, 0, 0, targetSize.Width, targetSize.Height); } } context.Response.ContentType = "image/jpg"; using (MemoryStream memoryStream = new MemoryStream()) { target.Save(memoryStream, ImageFormat.Jpeg); memoryStream.WriteTo(context.Response.OutputStream); } } finally { if (target != null) { target.Dispose(); } } }