Validere format i image upload
God formiddag alle eksperter. Jeg er i min skole ved at lave et Billedeupload som også skalere billedet. Indtil videre virker det perfekt.Men den kan bare ikke li' at jeg uploader andet end JPeg :(
public partial class _Default : System.Web.UI.Page
{
private string savepath = "~/Images/";
private string original = HttpContext.Current.Request.PhysicalApplicationPath + "/Images/";
private string thumb = HttpContext.Current.Request.PhysicalApplicationPath + "/Images/Thumb/";
protected void Page_Load(object sender, EventArgs e)
{ }
private System.Drawing.Image Scale(System.Drawing.Image image, int maxSizeWidthOrHeigh)
{
int w = image.Width;
int h = image.Height;
if (w > h)
{
w = maxSizeWidthOrHeigh;
h = image.Height * maxSizeWidthOrHeigh / image.Width;
}
else
{
w = image.Width * maxSizeWidthOrHeigh / image.Height;
h = maxSizeWidthOrHeigh;
}
using (Bitmap bm = new Bitmap(w, h))
{
using (Graphics gr = Graphics.FromImage((System.Drawing.Image)bm))
{
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.DrawImage(image, 0, 0, w, h);
}
try
{
return (System.Drawing.Image)bm.Clone();
}
finally
{
bm.Dispose();
}
}
}
private void saveAsThumbnail(string original, string thumb, int maxSize)
{
System.Drawing.Image originalImg = System.Drawing.Image.FromFile(original);
using (System.Drawing.Image thumbImg = (System.Drawing.Image)Scale(originalImg, maxSize))
{
thumbImg.Save(thumb, ImageFormat.Jpeg);
thumbImg.Dispose();
originalImg.Dispose();
}
}
protected void Button_upload_Click(object sender, EventArgs e)
{
if (FileUpload_default.HasFile)
{
string filename = FileUpload_default.FileName;
string savename = Server.MapPath(savepath) + filename;
FileUpload_default.SaveAs(Request.PhysicalApplicationPath + "/Images/" + FileUpload_default.FileName);
saveAsThumbnail(Request.PhysicalApplicationPath + "/Images/" + FileUpload_default.FileName, Request.PhysicalApplicationPath + "/Images/Thumb/" + FileUpload_default.FileName, Convert.ToInt32(textSize.Text));
LinkThumb.Text = "Se Thumb";
LinkThumb.NavigateUrl = "~/Images/Thumb/" + filename;
LinkImage.Text = "Se Image";
LinkImage.NavigateUrl = "~/Images/" + filename;
}
else
{
Response.Write("Vedhæft en fil for at fortage et upload!");
}
}