以下是简短的答案之一:
private static MemoryStream GetImageResized(MemoryStream data, int previewWidth, int previewHeight)
{
const int pixelPadding = 6;
const int bottomSize = 0;
using (var src = new Bitmap(data))
{
// default to width-based resizing...
int width = previewWidth;
var height = (int)(previewWidth/(src.Width/(double)src.Height));
if (src.Width <= previewWidth && src.Height <= previewHeight)
{
// no resizing necessary...
width = src.Width;
height = src.Height;
}
else if (height > previewHeight)
{
// aspect is based on the height, not the width...
width = previewHeight/((src.Height/src.Width) == 0 ? 1 : (src.Height/src.Width));
height = previewHeight;
}
using (
var dst = new Bitmap(width + pixelPadding, height + bottomSize + pixelPadding, PixelFormat.Format24bppRgb))
{
var rSrcImg = new Rectangle(0,0, src.Width, src.Height);
var rDstImg = new Rectangle(pixelPadding/2, pixelPadding/2, dst.Width - pixelPadding, dst.Height - pixelPadding - bottomSize);
using (Graphics g = Graphics.FromImage(dst))
{
g.Clear(Color.FromArgb(64, 64, 64));
g.FillRectangle(Brushes.White, rDstImg);
g.CompositingMode = CompositingMode.SourceOver;
g.CompositingQuality = CompositingQuality.GammaCorrected;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
g.DrawImage(src, rDstImg, rSrcImg, GraphicsUnit.Pixel);
}
var ms = new MemoryStream();
// save the bitmap to the stream...
dst.Save(ms, ImageFormat.Png);
ms.Position = 0;
return ms;
}
}
}
您可以致电此方法来调整图像大小。例如:
private void GetThumbnailImage(HttpContext context, string fileName, int maxWidth, int maxHeight)
{
var data = new MemoryStream();
using (var input = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var buffer = new byte[input.Length];
input.Read(buffer, 0, buffer.Length);
data.Write(buffer, 0, buffer.Length);
input.Close();
}
// reset position...
data.Position = 0;
MemoryStream ms = GetImageResized(
data, maxWidth, maxHeight);
context.Response.ContentType = "image/png";
// output stream...
context.Response.OutputStream.Write(ms.ToArray(), 0, (int)ms.Length);
// Possible Caching
//context.Response.Cache.SetCacheability(HttpCacheability.Public);
//context.Response.Cache.SetExpires(DateTime.UtcNow.AddHours(2));
//context.Response.Cache.SetETag(...);
data.Dispose();
ms.Dispose();
}
我写了一篇关于它的文章。代码示例已附加到文章中。这篇文章在波斯,但你可以使用谷歌翻译。 http://www.devzone.ir/post/1389/09/16/Dynamic-Thumbnails-in-ASP.aspx
非常感谢的开关输入。图像已缩小为缩略图大小...我仍然很难绑定到gridview。 – Arianule 2011-04-23 13:40:38
@Arianule - DId你可以绑定它? – TechGiant 2011-04-23 17:03:03