以前图片上传至数据库与显示时,需要把图片的宽度与高度读出来存在数据库表中,前些天做一个相册,发现从前的做法不太理想,改变做法是在读取图片时,再做尺寸调整。代码前三行,说明如何从数据流转为图片的方法。代码片断如下,请参考:
View Code byte[] buffer = (byte[])dataRow["Picture"]; //从数据库取到的图片数据
MemoryStream s = new MemoryStream(buffer, 0, buffer.Length); //转换为数据流
Bitmap photo = new Bitmap(s);
int _thumbnailSize = 160; //定义显示图片尺寸
int width, height; //定义图片宽度和高度
//如果原图片的宽度与高度都小于定义显示图片尺寸
if (photo.Width < _thumbnailSize && photo.Height < _thumbnailSize)
{
width = photo.Width; //宽度等于原宽度
height = photo.Height;//高度等于原高度
}
//如果原图片宽度大于原图片的高度
else if (photo.Width > photo.Height)
{
width = _thumbnailSize; //宽度等于定义图片尺寸
height = photo.Height * _thumbnailSize / photo.Width; //高度做相应比例缩小
}
//如果原图片高度大于原图片的宽度
else
{
width = photo.Width * _thumbnailSize / photo.Height; //宽度做相应比例缩小
height = _thumbnailSize; //高度等于定义图片尺寸
}
Bitmap target = new Bitmap(width, height);
using (Graphics graphics = Graphics.FromImage(target))
{
graphics.CompositingQuality = CompositingQuality.HighSpeed;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.DrawImage(photo, 0, 0, width, height);
using (MemoryStream memoryStream = new MemoryStream())
{
target.Save(memoryStream, ImageFormat.Png);
memoryStream.WriteTo(context.Response.OutputStream);
}
}