Ladda upp och förminska bilder med ASP.NET

Vi kör ett litet torsdagstema med bildbehandling. Skrev för ett tag sen lite kortfattat om hur man kan ladda upp filer med ASP.NET. Ser att det ramlar in en hel del folk genom sökningar så tänkte gå vidare på ämnet.

Nu tänkte jag bjuda på en till mesta del hemmasnickrad klass för att ladda upp och förminska bilder till servern. Kvaliteten blir ibland inte perfekt så denna funktion passar bäst till att skapa mindre tumnaglar.

Sen har jag även märkt att röda nyanser blir något flammiga ibland. Själva funktionen "CreateThumbnail" har inte jag skrivit men har haft den så länge att jag glömt bort var den kommer från. Om någon har en bättre lösning som ger bättre resultat är jag mycket intresserad. Annars kanske det få bli en djupdykning i källkoden för gratisprogrammet Paint.NET i jakt på bätte förminskningsfunktioner.

Men nu till exemplet. Ber om ursäkt för dålig dokumentation och en blandad kompott på svenska och engelska. Använd den precis som du vill. Jag uppskattar länkar tillbaks och även om du gör några framsteg på bildkvaliteten.

Så här anropar man klassen:

if (fu.HasFile)
{
Trace.Write("We found a image to upload");
HttpPostedFile userPostedFile = fu.PostedFile;
ImageUploader imageUploader = new ImageUploader("C:/sökväg/på/server/", userPostedFile, "Namnpåbild.jpg");
//Utlämna mått för att behålla orginalstorlek på bilden
imageUploader.IntMaxWidth = 150;
imageUploader.IntMaxHeight = 50;
bool boolStatus = imageUploader.UploadImage();
if(boolStatus)
Trace.Write("Image uploaded!");
}

Och här är själva klassen:

using System;
using System.Data;
using System.Data.SqlClient;
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.Drawing;
using System.Drawing.Imaging;


/// <summary>
/// Summary description for ImageUploader
/// </summary>
public class ImageUploader : Page
{

//Lokala variabler
private HttpPostedFile userPostedFile = null;
private string strWhereStatement = null;
private string strRootPath = string.Empty;
private string strImageName = string.Empty;
private int intMaxWidth;
private int intMaxHeight;

//Properties
public string StrRootPath
{
get { return strRootPath; }
set { strRootPath = value; }
}
public string StrImageName
{
get { return strImageName; }
set { strImageName = value; }
}
public int IntMaxWidth
{
get { return intMaxWidth; }
set { intMaxWidth = value; }
}
public int IntMaxHeight
{
get { return intMaxHeight; }
set { intMaxHeight = value; }
}


//I första konstruktorn använder vi filens orginalnamn
public ImageUploader(string StrRootPath,HttpPostedFile UserPostedFile)
{
strRootPath = StrRootPath;
userPostedFile = UserPostedFile;
//Ta bort eventuell filändelse
strImageName = userPostedFile.FileName.Remove(userPostedFile.FileName.LastIndexOf("."));
//UploadImage(userPostedFile);
}
//I den utökade så skickar vi med ett eget filnamn
public ImageUploader(string StrRootPath,HttpPostedFile UserPostedFile,string StrImageName)
{
strRootPath = StrRootPath;
userPostedFile = UserPostedFile;

strImageName = StrImageName;
}



public bool UploadImage()
{
bool tooHigh = false;
bool tooWide = false;
bool doUpload = false;
bool uploaded = false;
string strFileExt = string.Empty;

try
{

//Kontrollera att filen är större än 0KB
if (userPostedFile.ContentLength > 0)
{

//Check på filändelse och om man ska tillåta uppladdning

//Jpg och Jpeg
if (userPostedFile.ContentType.Equals("image/jpeg") || userPostedFile.ContentType.Equals("image/pjpeg"))
{
doUpload = true;
strImageName += ".jpg";
}
//Gif
if (userPostedFile.ContentType.Equals("image/gif"))
{
doUpload = true;
strImageName += ".gif";
}
//Bmp
if (userPostedFile.ContentType.Equals("image/bmp"))
{
doUpload = true;
strImageName += ".bmp";
}
//Png
if (userPostedFile.ContentType.Equals("image/png"))
{
doUpload = true;
strImageName += ".png";
}

System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(userPostedFile.InputStream, false);

//Kolla höjd
if (intMaxHeight != null)
{
if (bitmap.Height > intMaxHeight)
{
doUpload = true;
tooHigh = true;
}
}

//Kolla bredd
if (intMaxWidth != null)
{
if (bitmap.Width > intMaxWidth)
{
doUpload = true;
tooWide = true;
}
}

Trace.Write(strRootPath + strImageName);
if (doUpload && bitmap != null)
{
Trace.Write("doUpload!!");

//Förminska om den är för stor, och ladda upp
if (tooHigh || tooWide)
{
Trace.Write("tooBig!!");
//Skapa liten automagiskt
double photoWidth, photoHeight;
double percentageDifference = 0;

photoWidth = intMaxWidth;


//Nya mått på bilden.
percentageDifference = bitmap.Width / photoWidth;
photoHeight = bitmap.Height / percentageDifference;

//Kolla även höjden
if (photoHeight > intMaxHeight)
{
photoHeight = intMaxHeight;
percentageDifference = bitmap.Height / photoHeight;
photoWidth = bitmap.Height / percentageDifference;
}

Bitmap outputBitMap = CreateThumbnail(bitmap, Convert.ToInt32(photoWidth), Convert.ToInt32(photoHeight));

//Kolla vad det är för format
ImageFormat imageFormat = outputBitMap.RawFormat;

//Spara bilden
outputBitMap.Save(@"" + strRootPath + strImageName, imageFormat);
uploaded = true;
}
//Ladda upp orginalbilden om den är inom måtten
else
{
Trace.Write("Rätt storlek eller mindre.");


userPostedFile.SaveAs(@"" + strRootPath + strImageName);
uploaded = true;
}

}

}
}
catch(Exception objException)
{
Trace.Write("Upload fel!", objException.Message);
uploaded=false;
}
return uploaded;
}

//Tar emot en BitMap och gör den mindre
public static Bitmap CreateThumbnail(Bitmap loBMP, int lnWidth, int lnHeight)
{
System.Drawing.Bitmap bmpOut = null;

try
{

ImageFormat loFormat = loBMP.RawFormat;
decimal lnRatio;
int lnNewWidth = 0;
int lnNewHeight = 0;

//Om bilden är större än en thumbnail, returnera den.
if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
return loBMP;

if (loBMP.Width > loBMP.Height)
{
lnRatio = (decimal)lnWidth / loBMP.Width;
lnNewWidth = lnWidth;
decimal lnTemp = loBMP.Height * lnRatio;
lnNewHeight = (int)lnTemp;
}
else
{
lnRatio = (decimal)lnHeight / loBMP.Height;
lnNewHeight = lnHeight;
decimal lnTemp = loBMP.Width * lnRatio;
lnNewWidth = (int)lnTemp;
}

bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
loBMP.Dispose();
}
catch
{
return null;
}
return bmpOut;
}
}

By Jesper Lind

Paint.NET - gratis program för bildbehandling

http://www.codeodyssey.se/upload/resource/blog/paint-net.png

Laddade just hem Paint.NET och har provkört det lite snabbt. Verkar vara kanonbra. Det startar upp på typ en sekund och har en hel del funktionalitet när det gäller bildbehandling.

Jag har länge letat efter ett sådant här program för att använda till snabbare ändringar på bilder, och nu har jag funnit det. Tidigare har jag gjort all bildbehandling i Photoshop och det vet ju de flesta användare att det är ganska så segstartat.

Att programmet är helt gratis skadar ju inte heller. Det är släppt under Creative Commons Attribution-NonCommercial-NoDerivs 2.5 Licens och C# kod på 133000 rader finns att ladda hem för den som är sugen.

(Tack Sovrat)

By Jesper Lind
1