DevTrain Startseite SharePoint Camp ? In 5 Tagen zum SharePoint Profi!  
  
  
SUCHEN:  
ARTIKEL ONLINE: 525   

Kategorien
.NET
Datenbanken
Web
XML

Allgemein
Camp
Foren
Events
Persönliche Einstellungen
Registrieren
Prämien Shop
Kontakt
Impressum
Über DevTrain

Autoren


   Autor: Christian Mairoll Artikel Drucken
        
Erstellen einer Bildergallerie in ASP.NET

Bild-Manipulationen waren in ASP nur mit Fremdkomponenten möglich oder durch Ausweichen auf andere Scriptsprachen wie PHP. Mit dem .NET-Framework kann sich nun jeder problemlos eine Routine zum Verändern von Bilddaten schreiben. Dieser Artikel beschreibt die Möglichkeit, aus einem vordefinierten Ordner voller Grafiken, eine Bildergallerie fürs Web zu erstellen.

Die Bildergallerie soll aus einem Ordner alle Grafikdateien einlesen, diese zuerst in Thumbnail-Größe (140px maximale Seitenlänge) generieren und dann noch die großen Galleriebilder in der Größe von maximal 800px Seitenlänge erzeugen. Aus den Thumbnails wird anschließend eine Tabelle mit einer frei wählbaren Anzahl an Spalten gerendert.

In der ASPX-Seite benötigen wir lediglich ein Control. Einen <span>-Bereich in dem wir am Ende das ganze erzeugte HTML der Gallerie-Tabelle schreiben.

<span id="Output" runat="server"></span>


Das folgende Listing zeigt den vollständigen Source der codebehind-Datei. Zur Verwendung müssen Sie nur beachten, daß der Pfad zu den Quelldaten (sFolder) gültig ist. Die Größe der erzeugten Bilder kann über die Variablen MaxSizeThumb und MaxSizeLarge festgelegt werden.

using System;

using System.Collections;

using System.Drawing;

using System.Drawing.Imaging;

using System.Drawing.Drawing2D;

using System.IO;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

 

namespace ImageGallery

{

       public class Gallery : System.Web.UI.Page

       {

             protected System.Web.UI.HtmlControls.HtmlGenericControl Output;

      

             public Gallery()

             {

                    Page.Init += new System.EventHandler(Page_Init);

             }

 

             private void Page_Load(object sender, System.EventArgs e)

             {

                    int MaxSizeThumb = 140;

                    int MaxSizeLarge = 800;

                    string sFolder = @"c:\Daten\Fotos\";

 

                    DirectoryInfo Folder = new DirectoryInfo(sFolder);

                    FileInfo[] Files = Folder.GetFiles();

                   

                    string ErrorText = "";

                    string ImgRoot = Server.MapPath("Images\\");

                    ArrayList aFiles = new ArrayList();

 

                    foreach (FileInfo NextFile in Files)

                    {

                           try

                           {

                                  ErrorText = "";

                                  string myFile = sFolder + NextFile.Name;

                                  string Filepath = myFile.ToLower();

                                  Filepath = Filepath.Substring(0, Filepath.LastIndexOf("\\"));

                                 

                                  // get the image-filename without the extension

                                  string Filename = myFile.ToLower();

                                  if (Filename.EndsWith(".jpg"))

                                  {

                                        Filename = Filename.Substring(0, Filename.Length - 4);

                                  }

                                  Filename = Filename.Substring(Filename.LastIndexOf("\\") + 1);

                                 

                                  // create the subfolder for the thumbnails

                                  Directory.CreateDirectory(ImgRoot);

                                 

                                  // create thumbnail if not exist

                                 if (!File.Exists(ImgRoot + "k_" + Filename + ".jpg"))

                                  {

                                        if (!CreateImage(myFile, ImgRoot + "k_" + Filename + ".jpg", MaxSizeThumb))

                                        {

                                               ErrorText += "Error while generating the image";

                                        }

                                  }

                                  // call GarbageCollection to free the memory needed when generating the image

                                  GC.Collect();

                                 

                                  // create large image if not exist

                                  if (!File.Exists(ImgRoot + Filename + ".jpg"))

                                  {

                                        if (!CreateImage(myFile, ImgRoot + Filename + ".jpg", MaxSizeLarge))

                                         {

                                               ErrorText += "Error while generating the image";

                                        }

                                  }

                                  // call GarbageCollection to free the memory needed when generating the image

                                  GC.Collect();

 

                                  // add file to ArrayList if there is no error

                                  if (ErrorText.Length == 0)

                                  {

                                        ArrayList aFInfo = new ArrayList();

                                        aFInfo.Add(NextFile.Name);

                                        aFInfo.Add(@"Images/" + "k_" + Filename + @".jpg");

                                        aFInfo.Add(@"Images/" + Filename + @".jpg");

                                        aFiles.Add(aFInfo);

                                  }

 

                           }

                           catch(ArgumentException argex)

                           {

                                  // Response.Write(@"<!-- Error: source is not a valid image-file -->" + "\r\n");

                           }

                           catch(Exception ex)

                           {

                                  // Response.Write(@"Error: " + ex.ToString() + @" + "\r\n");

                           }

                    }

                   

                    // build the table with images

                    int tCols = 4; // specify how many columns

                    string OutputHTML = "";

                    int j = 0;

                    OutputHTML += @"<table border=0 cellspacing=20 cellpadding=0>" + "\r\n";

                   

                    for(int i = 0; i<=aFiles.Count - 1; i++)

                    {

                           j++;

                           if(j==1)

                           {

                                  OutputHTML += @"<tr>" + "\r\n";

                           }

                           ArrayList AL = (ArrayList)aFiles[i];

                           OutputHTML += @"<td align=center><a href=""";

                           OutputHTML += Server.HtmlDecode(AL[2].ToString()) + @""">";

                           OutputHTML += @"<img src=""" + AL[1].ToString() + @""" border=0></a><br>";

                           OutputHTML += AL[0].ToString() + @"</td>" + "\r\n";

                           if(j==tCols)

                           {

                                  OutputHTML += @"</tr>" + "\r\n";

                                  j=0;

                           }

                    }

                    OutputHTML += @"</table>" + "\r\n";

                   

                    // write the HTML output within the span-control.

                    Output.InnerHtml = OutputHTML;

             }

 

             private bool CreateImage(string Source, string Target, int MaxSize)

             {

                    try

                    {

                           // load source image

                           Bitmap SourceBitmap = new Bitmap(Source);

                   

                           Size s = new Size();

                           // calculate size from MaxSize

                           if (SourceBitmap.Width > SourceBitmap.Height)

                           {

                                  s.Width = MaxSize;

                                  s.Height = Convert.ToInt32((double)1 / SourceBitmap.Width * MaxSize * SourceBitmap.Height);

                           }

                           else

                           {

                                  s.Width = Convert.ToInt32((double)1 / SourceBitmap.Height * MaxSize * SourceBitmap.Width);

                                  s.Height = MaxSize;

                           }

                          

                           // load new image

                           Bitmap TargetBitmap = new Bitmap(s.Width, s.Height);

                           Graphics bmpGraphics = Graphics.FromImage(TargetBitmap);

                          

                           // set some quality properties

                           bmpGraphics.InterpolationMode = InterpolationMode.High;

                           bmpGraphics.SmoothingMode = SmoothingMode.AntiAlias;

                          

                           // generate the new image with the rectangle-size

                           Rectangle FinalRectangle = new Rectangle(0, 0, s.Width, s.Height);

                           bmpGraphics.DrawImage(SourceBitmap, FinalRectangle);

                          

                           // save the new image in the /images subfolder of the web-root

                           TargetBitmap.Save(Target, ImageFormat.Jpeg);

                           return(true);

                    }

                    catch

                    {

                           return(false);

                    }

             }

 

             private void Page_Init(object sender, EventArgs e)

             {

                    //

                    // CODEGEN: This call is required by the ASP.NET Web Form Designer.

                    //

                    InitializeComponent();

             }

 

             #region Web Form Designer generated code

             /// <summary>

             /// Required method for Designer support - do not modify

             /// the contents of this method with the code editor.

             /// </summary>

             private void InitializeComponent()

             {   

                    this.Load += new System.EventHandler(this.Page_Load);

 

             }

             #endregion

       }

}


DevTrain Camp - Schneller zum .NET 3.5 Developer
 
Verwandte Artikel      Verlinkte Dokumente
    Keine verknüpften Dokumente
    Keine Links vorhanden

  Erfasst am: 17.10.2001
  Gültig bis: 16.11.2001
10 Ratings
Bewertung: 74,0%
schlecht    sehr gut  

 
© Copyright 2007 ppedv AG