我似乎在这里做错了什么。
我想要做的就是在gridview 中显示一个缩略图。
ASPX 页面有一个gridview 和一个asp:image 控件。asp:image 控件的 imageurl 来自一个网站。
获得 imageUrl 后,我想使用下面的 ResizeImage 函数将图像渲染为缩略图。最后,我想将缩略图分配给显示缩略图的 gridview 列,如下面的代码所示
protected void SearchResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType.Equals(DataControlRowType.DataRow))
{
System.Web.UI.WebControls.Image imgNew = (System.Web.UI.WebControls.Image)e.Row.FindControl("ProductThumbField");
imgNew.Source = Utils.ResizeImage(imgNew.ImageUrl.ToString(),60,60);
}
}
这是调整图像大小的代码。(取自stackoverflow问题和答案的一个例子)。
private static Bitmap ResizeImage(String filename, int maxWidth, int maxHeight)
{
using (System.Drawing.Image originalImage = System.Drawing.Image.FromFile(filename))
{
//Caluate new Size
int newWidth = originalImage.Width;
int newHeight = originalImage.Height;
double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;
if (aspectRatio <= 1 && originalImage.Width > maxWidth)
{
newWidth = maxWidth;
newHeight = (int)Math.Round(newWidth / aspectRatio);
}
else if (aspectRatio > 1 && originalImage.Height > maxHeight)
{
newHeight = maxHeight;
newWidth = (int)Math.Round(newHeight * aspectRatio);
}
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics g = Graphics.FromImage(newImage))
{
//--Quality Settings Adjust to fit your application
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);
return newImage;
}
}
这是 ASPX 页面的代码片段。
<asp:GridView ID="SearchResults" runat="Server" AutoGenerateColumns="false" EnableViewState="false"
AllowPaging="true" PageSize="10" ondatabound="SearchResults_DataBound" >
<RowStyle CssClass="EvenRow" />
<AlternatingRowStyle CssClass="OddRow" />
<Columns>
<asp:TemplateField meta:resourceKey="ProductThumbField">
<ItemStyle CssClass="ProductNameColumn" />
<HeaderStyle CssClass="ProductNameColumn" />
<ItemTemplate>
<asp:image id="ProductThumbImg" runat="server" imageurl='<%# GetProductThumb(Container.DataItem) %>' Width ="60px" Height = "60px" />
</ItemTemplate>
</asp:TemplateField>