if (FileUpload1.FileName.ToString() == "")
{
Label3.Text = "请选择图片!";
}
else
{
Boolean FileOK = false;
if (this.FileUpload1.HasFile)
{
if (FileUpload1.PostedFile.ContentLength <= 2097152)
{
Session["WorkingImage"] = Guid.NewGuid().ToString() + Path.GetExtension(FileUpload1.FileName.ToString()).ToLower();
String FileExtension = Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();
String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (FileExtension == allowedExtensions[i])
{
FileOK = true;
}
}
}
else
{
FileOK = false;
Response.Write("<script language=javascript>alert('图片不要超过 2M 大小!');window.location.href=window.location.href;</script>");
}
}
if (FileOK)
{
try
{
Byte[] oFileByte = new byte[this.FileUpload1.PostedFile.ContentLength];
System.IO.Stream oStream = this.FileUpload1.PostedFile.InputStream;
System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);
int oWidth = oImage.Width;
int oHeight = oImage.Height;
int tWidth;
int tHeight;
if (oWidth >= oHeight)
{
tWidth = 300;
tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
}
else
{
tHeight = 300;
tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
}
Bitmap tImage = new Bitmap(tWidth, tHeight);
Graphics g = Graphics.FromImage(tImage);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(Color.Transparent);
g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);
string fullFileName = this.FileUpload1.PostedFile.FileName.ToString();
fullFileName = fullFileName.Remove(fullFileName.LastIndexOf('.'));
string filename = fullFileName.Substring(fullFileName.LastIndexOf("\\") + 1);
string strLocation = path.ToString();
string tFullName = strLocation + Session["WorkingImage"].ToString();
try
{
tImage.Save(tFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
TextBox3.Text = "uploadfiles/product/" + Session["WorkingImage"].ToString();
path = "../uploadfiles/product/" + Session["WorkingImage"].ToString();
}
catch (Exception)
{
Response.Write("<script language=javascript>alert('上传失败,请重试!');window.location.href=window.location.href;</script>");
}
finally
{
oImage.Dispose();
g.Dispose();
tImage.Dispose();
}
}
catch (Exception)
{
Response.Write("<script language=javascript>alert('上传失败,请重试!');window.location.href=window.location.href;</script>");
}
}
}