日期:2014-05-18  浏览次数:20466 次

ASP.NET二进制图片如何转换成JPEG格式在页面输出并能控制大小?
我现在的做法是用一个handler来读取数据库中的二进制图片,然后展示到页面上。页面上用个image控件来接收图片,设定了width和height。但是这样有个问题,在页面上的图片是我说希望的大小,但是直接复制页面到内容到excel里以后,图片就恢复成原来大小了,很不好看。请问如何解决?

ImageHandler.ashx.cs文件:
C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
using System.IO;

namespace Space
{
    /// <summary>
    /// ImageHandler 的摘要说明
    /// </summary>
    public class ImageHandler : IHttpHandler
    {
        private string strConn = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString; //获取配置文件

        public void ProcessRequest(HttpContext context)
        {
            string imageID = context.Request.QueryString["ImID"];
            SqlConnection conn = new SqlConnection(strConn);
            conn.Open();
            string strQuery = @"select Photo from dbo.[User] where ID='" + imageID + "'";
            SqlCommand cmd = new SqlCommand(strQuery, conn);
            SqlDataReader sdr = cmd.ExecuteReader();
            sdr.Read();
            if (sdr[0] != DBNull.Value)
            {
                context.Response.ContentType = "image/jpeg";
                context.Response.BinaryWrite((Byte[])sdr[0]);
                //获取原始图片高度和宽度
                MemoryStream s = new MemoryStream((Byte[])sdr[0]);
                Image img = Image.FromStream(s);
                int width = img.Width;
                int height = img.Height;                
            }
            conn.Close();
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}



前台页面绑定:
HTML code

<td id="tdImage" style="width: 67px;" runat="server">
                        <asp:Image ID="image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+Eval("UID") %>'
                            Height='100px' Width='65px' />
                    </td>


请问如何修改使之能够得到我想要的大小,比如Height='100px' Width='65px' ?

------解决方案--------------------
这样
C# code
Response.ClearContent();
MemoryStream s = new MemoryStream((Byte[])sdr[0]);
System.Drawing.Image img = System.Drawing.Image.FromStream(s);
System.Drawing.Image image = img.GetThumbnailImage(100, 65, null, IntPtr.Zero);
image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
image.Dispose();
img.Dispose(); 
Response.End();