日期:2014-05-20  浏览次数:21003 次

请教一个关于缩略图的问题!
我在ASP.NET开发时遇到了这样的问题,将上传的图片(图片的大小不能固定),显示到其他页面,但显示后发现小图片还好,大图片就完全失真了。请问该怎样才能解决这个问题,希望高手们多多帮忙哈!

------解决方案--------------------
给楼主两个自己写的代码看看,希望对你有点帮助
/// <summary>
/// 按比例缩放图片,并非按原来大小裁剪
/// 水平长度优先.
/// </summary>
public static string ResizeImage(string _srcImage, int _DstX, string _dstPath)
{
System.Drawing.Image img = System.Drawing.Image.FromFile(_srcImage);
int newHight = img.Height;
int newWidth = img.Width;
while (newWidth > _DstX)//按比例缩小图片
{
newHight = Convert.ToInt32(newHight / 1.01);
newWidth = Convert.ToInt32(newWidth / 1.01);
}
System.Drawing.Image newimg = img.GetThumbnailImage(newWidth, newHight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbCallBack), IntPtr.Zero);
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(newimg);
string tempName=GenRandomNumber(22) + ".jpg ";
bmp.Save(_dstPath + tempName , System.Drawing.Imaging.ImageFormat.Jpeg);
return tempName;
}

/// <summary>
/// 按比例缩放图片,并非按原来大小裁剪
/// 垂直长度优先
/// </summary>
public static string ResizeImage(int _DstY, string _srcImage, string _dstPath)
{
System.Drawing.Image img = System.Drawing.Image.FromFile(_srcImage);
int newHight = img.Height;
int newWidth = img.Width;
while (newWidth > _DstY)//按比例缩小图片
{
newHight = Convert.ToInt32(newHight / 1.01);
newWidth = Convert.ToInt32(newWidth / 1.01);
}
System.Drawing.Image newimg = img.GetThumbnailImage(newWidth, newHight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbCallBack), IntPtr.Zero);
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(newimg);
string tempName = GenRandomNumber(22) + ".jpg ";
bmp.Save(_dstPath + tempName, System.Drawing.Imaging.ImageFormat.Jpeg);
return tempName;
}
public static bool ThumbCallBack()
{
return true;
}
public static string GenRandomNumber(int _seed)
{
Random rdm = new Random(_seed);
return System.DateTime.Now.Millisecond.ToString() + rdm.Next(1, 65536).ToString();
}
------解决方案--------------------
将图片等比缩放:
static private int[] ReducedSize(int imageWidth, int imageHeight, int targetWidth, int targetHeight)
{
int reducedWidth = imageWidth;
int reducedHeight = imageHeight;
int[] result = new int[2];

if (!(imageWidth - targetWidth < 0 && imageHeight - targetHeight < 0))
{
if ((imageWidth * 1.0 / targetWidth) > (imageHeight * 1.0 / targetHeight))
{
reducedWidth = targetWidth;
reducedHeight = (targetWidth * imageHeight) / imageWidth;
}
else
{
reducedWidth = (targetHeight * imageWidth) / imageHeight;
reducedHeight = targetHeight;
}
}

result[0] = reducedWidth;
result[1] = reducedHeight;
return result;
}