Dårlig kvalitet på billede efter upload
HejJeg har "lånt" nedenstående script, men har problemer med at kvaliteten på de uploadede billeder ikke er særlig god. Er der nogle der ved hvorfor?
public void Upload_Click(object sender, System.EventArgs e)
{
string dir = "~/images/galleri/diverse/";
string strFileName;
if(uploadedFile1.PostedFile.FileName.IndexOf("\\") > 0)
{
strFileName = uploadedFile1.PostedFile.FileName.Substring(uploadedFile1.PostedFile.FileName.LastIndexOf("\\") + 1);
}
else { strFileName = "ukendt.fil"; }
if(!File.Exists(Server.MapPath(dir + strFileName)))
{
int MaxSize = 405;
try
{
System.Drawing.Image image = new System.Drawing.Bitmap(uploadedFile1.PostedFile.InputStream);
uploadedFile1.PostedFile.SaveAs(Server.MapPath(dir + strFileName));
System.Drawing.Bitmap bOrg = (System.Drawing.Bitmap)image;
System.Drawing.Imaging.ImageFormat format = image.RawFormat;
if(image.Width>MaxSize || image.Height>MaxSize)
{
Bitmap b = Resize(bOrg,MaxSize,MaxSize);
b.Save(Server.MapPath(dir + strFileName ), format);
}
else
{ //Gem original da billede allerede er mindre end 100px
uploadedFile1.PostedFile.SaveAs(Server.MapPath(dir + strFileName));
}
Label1.Text = "Billedet er uploaded";
}
catch
{
Label1.Text= "Der skete en fejl ved uploading af billedet";
}
}
else
{
Label1.Text = "Filnavn eksisterer allerede, prøv at ombøbe billedet!";
}
private static Bitmap Resize(Bitmap b, int MaxHeight, int MaxWidth)
{
int nWidth = b.Width;
int nHeight = b.Height;
if(nHeight>MaxHeight)
{
nWidth = (int)((((double)b.Width)/((double)b.Height))*((double)MaxHeight));
nHeight = MaxHeight;
}
if(nWidth>MaxWidth)
{
nWidth=MaxWidth;
nHeight = (int)((((double)b.Height)/((double)b.Width))*((double)MaxWidth));
}
Bitmap bTemp = (Bitmap)b.Clone();
b = new Bitmap(nWidth, nHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
double nXFactor = (double)bTemp.Width/(double)nWidth;
double nYFactor = (double)bTemp.Height/(double)nHeight;
for (int x = 0; x < b.Width; ++x)
for (int y = 0; y < b.Height; ++y)
b.SetPixel(x, y, bTemp.GetPixel((int)(Math.Floor(x * nXFactor)),
(int)(Math.Floor(y * nYFactor))));
return b;
}