我正在使用asp.net fileupload控件上传图片,但在这里我想自动调整大小为250 * 200px。 请建议我在我的代码中添加什么。 我是asp.net的新手。
protected void Button1_Click(object sender, EventArgs e)
{ string s =@"~\img\"+FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath(s));
}
答案 0 :(得分:1)
我也发现此代码对调整大小有用
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing;
public partial class ImageUpload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string ImageName = txtName.Text;
if (FileUpLoad1.PostedFile != null && FileUpLoad1.PostedFile.FileName != null)
{
string strExtension = System.IO.Path.GetExtension(FileUpLoad1.FileName);
if ((strExtension.ToUpper() == ".JPG") | (strExtension.ToUpper() == ".GIF"))
{
// Resize Image Before Uploading to DataBase
FileUpload fi = new FileUpload();
fi = FileUpLoad1;
System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream( fi.PostedFile.InputStream);
int imageHeight = imageToBeResized.Height;
int imageWidth = imageToBeResized.Width;
int maxHeight = 120;
int maxWidth = 160;
imageHeight = (imageHeight * maxWidth) / imageWidth;
imageWidth = maxWidth;
if (imageHeight > maxHeight)
{
imageWidth = (imageWidth * maxHeight) / imageHeight;
imageHeight = maxHeight;
}
Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight);
System.IO.MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Position = 0;
byte[] image = new byte[stream.Length + 1];
stream.Read(image, 0, image.Length);
// Create SQL Connection
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["Return_AuthorizationsConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Images(ImageName,Image) VALUES (@ImageName,@Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlParameter ImageName1 = new SqlParameter("@ImageName", SqlDbType.VarChar, 50);
ImageName1.Value = ImageName.ToString();
cmd.Parameters.Add(ImageName1);
SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, image.Length);
UploadedImage.Value = image;
cmd.Parameters.Add(UploadedImage);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result > 0)
lblMessage.Text = "File Uploaded";
GridView1.DataBind();
}
}
}
}
答案 1 :(得分:0)
在服务器上获取图像后,您可以将其大小保存,然后删除原始图像。
仅用于调整大小的示例代码
http://weblogs.asp.net/gunnarpeipman/archive/2009/04/02/resizing-images-without-loss-of-quality.aspx
这是一个包含操作图像源代码的完整项目,包括调整大小。