Click here to Skip to main content
15,894,410 members
Articles / Desktop Programming / Windows Forms

Crystal Image Toolkit: thumbnail image control and picture viewing.

Rate me:
Please Sign up or sign in to vote.
4.68/5 (21 votes)
11 May 2011LGPL37 min read 109.9K   8.3K   95  
Thumbnail and image viewing controls for Windows Forms, using C#.
#region gnu_license
/*
    Crystal Controls - C# control library containing the following tools:
        CrystalControl - base class
        CrystalGradientControl - a control that can either have a gradient background or be totally transparent.
        CrystalLabel - a homegrown label that can have a gradient or transparent background.
        CrystalPanel - a panel that can have a gradient or transparent background.
        CrystalTrackBar - a homegrown trackbar that can have a gradient or transparent background.
        CrystalToolStripTrackBar - a host for CrystalTrackBar that allows it to work in a ToolStrip.
        
        CrystalImageGridView - a control that hosts thumbnail images in a virtual grid.
        CrystalImageGridModel - a data model that holds a collection of CrystalImageItems
                                to feed to CrystalImageGridView.
        CrystalImageItem - a class that describes an Image file.
        CrystalThumbnailer - provides thumbnailing methods for images.

        CrystalCollector - a base class for a controller that links 
                            CrystalImageGridView to the CrystalImageGridModel.
        CrystalFileCollector - a controller that works on disk-based Image files.
        CrystalDesignCollector - a controller that works in Visual Studio toolbox designer.
        CrystalMemoryCollector - a controller that can be used to add images from memory.
        CrystalMemoryZipCollector - a controller that accesses images in zip files by streaming them into memory.
        CrystalZipCollector - a controller that accesses images in zip files by unpacking them.
        CrystalRarCollector - a controller that accesses images in rar files by unpacking them.

        CrystalPictureBox - a picture box control, derived from CrystalGradientControl.
        CrystalPictureShow - a control for viewing images and processing slideshows.
        CrystalComicShow - a control for viewing comic-book images in the CDisplay format.
 
    Copyright (C) 2006, 2008 Richard Guion
    Attilan Software Factory: http://www.attilan.com
    Contact: richard@attilan.com

   Version 1.0.0
        This is a work in progress: USE AT YOUR OWN RISK!  Interfaces/Methods may change!
 
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
#endregion

using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using Attilan.Crystal.Tools;
using ICSharpCode.SharpZipLib.Zip;

namespace Attilan.Crystal.Controls
{
    /// <summary>
    /// A Crystal Image collector variant that operates on images stored in zip archives.
    /// </summary>
    [ToolboxItem(false)]
    public class CrystalMemoryZipCollector : CrystalZipCollector
    {
        #region Methods

        /// <summary>
        /// Loads the full image and places it into the CrystalImageItem object.
        /// </summary>
        /// <param name="imageItem">The CrystalImageItem object with the Image information.</param>
        /// <returns>True if successful, false if an error occurred.</returns>
        public override bool LoadImage(ref CrystalImageItem imageItem)
        {
            if ((imageItem == null) || (imageItem.Tag == null))
                return false;

            ZipEntry zipEntry = (ZipEntry)imageItem.Tag;
            if (zipEntry != null)
            {
                ZipFile zipFile = (ZipFile)CompressedFile;

                if (zipFile != null)
                {
                    Stream imageStream = zipFile.GetInputStream(zipEntry);
                    imageItem.FullImage = Image.FromStream(imageStream);
                    imageStream.Close();
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Sets the tool tip text inside a CrystalImageItem object.
        /// </summary>
        /// <param name="theImage">CrystalImageItem object.</param>
        /// <param name="entry">Information about image object in the zip file.</param>
        protected virtual void SetToolTipText(ref CrystalImageItem theImage, ZipEntry entry)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(theImage.ImageName);
            builder.Append("\n");
            builder.Append(entry.DateTime.ToShortDateString());

            builder.Append("\nType: ");
            string ext = Path.GetExtension(entry.Name);
            if (ext != string.Empty)
                ext = ext.Remove(0, 1);
            theImage.ImageFormatString = ext.ToUpper();
            builder.Append(theImage.ImageFormatString);
            builder.Append(" Image");

            builder.Append("\nSize: ");
            theImage.ImageSize = CrystalTools.FormatFileSizeString(entry.Size);
            builder.Append(theImage.ImageSize);

            theImage.ToolTipText = builder.ToString();
        }

        /// <summary>
        /// Sets the image attributes into the CrystalImageItem object.
        /// </summary>
        /// <param name="theImage">CrystalImageItem object.</param>
        /// <param name="entry">Information about image object in the zip file.</param>
        protected virtual void SetImageAttributes(ref CrystalImageItem theImage, ZipEntry entry)
        {
            theImage.LastWriteTime = entry.DateTime;
            theImage.CreationTime = entry.DateTime;
            SetImageFormat(ref theImage, Path.GetExtension(entry.Name));
        }

        /// <summary>
        /// Collects the images at the ImageLocation into the model and then tells the view to display them.
        /// </summary>
        /// <returns>True if images were successfully collected, false otherwise.</returns>
        public override bool CollectImages()
        {
            if ((CompressedFileName == null) || (CompressedFileName == string.Empty) || (!File.Exists(CompressedFileName)))
                return false;

            if (GridView == null)
                return false;

            PurgeImages();

            _zipFile = null;

#if CRYSTAL_DEBUG
            CrystalLogger.LogDebug(
                string.Format("Total Memory before CrystalImage List = {0}", GC.GetTotalMemory(false)));
#endif

            _zipFile = (ZipFile)CompressedFile;
            List<CrystalImageItem> _crystalList = new List<CrystalImageItem>();

            foreach (ZipEntry entry in _zipFile)
            {
                /////////////////////////////////////////////////////
                // Only process images in the compressed file!
                if (entry.IsDirectory)
                    continue;

                // Check for '.' in first character, some broken archives have this.
                if ((entry.Name.Length > 0) && (entry.Name[0] == '.'))
                    continue;

                if (!CrystalTools.IsFileImage(entry.Name))
                    continue;
                /////////////////////////////////////////////////////

                CrystalImageItem theImage = CreateCrystalImage();
                theImage.ImageLocation = ImageLocation;
                theImage.ImageName = entry.Name;
                theImage.DisplayName = Path.GetFileNameWithoutExtension(theImage.ImageName);
                theImage.Tag = entry;
                SetToolTipText(ref theImage, entry);
                SetImageAttributes(ref theImage, entry);

                // Default border color is what was set in the view.
                if (GridView != null)
                    theImage.BorderColor = GridView.CellBorderColor;

                Thumbnailer.AdjustThumbLocation(theImage);

                _crystalList.Add(theImage);
            }

            // Sort the list by the image name
            SortCrystalList(CrystalSortType.DisplayName, true, _crystalList);

            // Replace the Crystal Image List in the model.
            _gridModel.AddList(_crystalList);

            // Have the model calculate its virtual size,
            // and the size/position of each image item.
            _gridModel.CalculateVirtualGrid();

#if CRYSTAL_DEBUG
            CrystalLogger.LogDebug(string.Format("Total Memory after CrystalImage List = {0}", GC.GetTotalMemory(false)));
#endif

            // Kill the background population if it is already running
            KillCollectionThread();

            // Kick off a background thread that thumbnails the images in our collection
            _collectThread = new Thread(CollectThumbnailImages);
            _collectThread.Start();

            // Tell the view to start drawing the image grid
            UpdateResizeVirtualGrid();

            return true;
        }

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
Software Developer (Senior)
United States United States
Richard has been working with Windows software since 1991. He has worked for Borland, Microsoft, Oracle, and various startup companies such as Livescribe. Currently he is developing projects in C#, Windows Forms, and Net Framework. Visit his blog Attilan (www.attilan.com) to learn more about his tools, projects and discoveries.

Comments and Discussions