我正在使用图像处理程序来调整大小并以二进制格式存储图像 下面是处理程序代码。我想优化这段代码,非常感谢任何帮助。
public class image : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 StudentId;
if (context.Request.QueryString["id"] != null)
StudentId = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");
Int32 w;
if (context.Request.QueryString["w"] != null)
w = Convert.ToInt32(context.Request.QueryString["w"]);
else
throw new ArgumentException("No parameter specified");
Int32 h;
if (context.Request.QueryString["h"] != null)
h = Convert.ToInt32(context.Request.QueryString["h"]);
else
throw new ArgumentException("No parameter specified");
using (System.Drawing.Image img = ShowImage(StudentId))
{
byte[] bmpBytes;
System.Drawing.Image pic = Resize(img, w, h);
MemoryStream ms = new MemoryStream(); // better use a using statement
pic.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
bmpBytes = ms.GetBuffer();
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(bmpBytes);
ms.Close();
context.Response.End();
img.Dispose();
}
}
public bool IsReusable
{
get
{
return false;
}
}
protected System.Drawing.Image Resize(System.Drawing.Image img, int resizedW, int resizedH)
{
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(resizedW, resizedH);
System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage((System.Drawing.Image)bmp);
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphic.DrawImage(img, 0, 0, resizedW, resizedH);
graphic.Dispose();
return (System.Drawing.Image)bmp;
}
public System.Drawing.Image ShowImage(int id)
{
string conn = ConfigurationManager.ConnectionStrings["MyManageConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT StudentPhoto FROM tblStudent WHERE StudentId = @ID";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", id);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
//return new MemoryStream((byte[])img);
//return (byte[])img;
MemoryStream ms = new MemoryStream((byte[])img);
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
return returnImage;
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
}
这是我的图片处理程序代码。我们可以直接转换为二进制到图像和调整大小。
<asp:Image ID="imgStudentPhoto" runat="server" ImageUrl='<%#"image.ashx?id="+Eval("StudentId")+"&w=200&h=200" %>' Height="60px" Width="60px"></asp:Image>
我的网格视图中的html
代码。当我以二进制格式保存图像时,它的大小大多为3mb。
保存原始图像或保存调整大小图像哪个更好?
我还要求在服务器中保存图像更好,或者在sql server
中以二进制保存更好。
答案 0 :(得分:0)
如果图像尺寸较大,最好调整图像大小并保存。
最好的方法是将图像存储在项目根目录下的文件夹中,并将其路径保存在数据库中。