[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How to create thumbnail

Posted on 2006-03-26
13
Medium Priority
?
4,177 Views
Last Modified: 2008-03-28
How to create thumbnail ?

and i need to create the thumbnail for a particular filename for every folder under a particular folder.

thanks
0
Comment
Question by:saimatkong
  • 5
  • 3
  • 3
  • +2
13 Comments
 
LVL 12

Expert Comment

by:AGBrown
ID: 16299135
You can do this with the System.IO.DirectoryInfo, System.IO.FileInfo and System.Drawing objects and namespaces. The Bitmap class in System.Drawing has a method called GetThumbnailImage which does what it says on the tin.

Roughly, it would go something like:
<psuedo>
Main()
{
-Get parentDirectory as DirectoryInfo
RecurseDirectories(parentDirectory)
}

RecurseDirectories(DirectoryInfo parentDirectory)
{
-for each directory in parentDirectory.GetDirectories()
    -RecurseDirectories(directory)

-for each file in parentDirectory.GetFiles("targetFileName")
}

CreateThumbnail(string FileInfoFullName)
{
using (System.Drawing.Bitmap bmp = new Bitmap(FileInfoFullName))
{
-manipulate bmp using bmp.GetThumbnailImage() and save it to a file
}
}
</psuedo>

Good references for doing the thumbnail creation:
http://www.codeproject.com/aspnet/thumbtools.asp

Andy
0
 

Author Comment

by:saimatkong
ID: 16300310
hmm that's asp.net what i mean is C# win app.

and can it be loading all the date from different xml in diff sub folder under one folder
and load all the title into a list and when a list is being clicked, the image and the details is being loaded.


thanks again.
0
 
LVL 12

Expert Comment

by:AGBrown
ID: 16300407
saimatkong,

Don't worry, the code is not asp.net specific, you can transfer it to windows and get it to work in c#. The code I have shown above just mapped out the psuedo-code/logic, you will need to do the specifics for your application. It shows three things:
1) A main function that starts the process of recursively going through the subdirectories
2) A recursive function that will go into each directory within a directory. If there are no directories, or once it returns from the subdirectories, then you can process the files.
3) A CreateThumbnail function that uses the filename along with the System.Drawing.Bitmap objects to generate the thumbnail.

You can use the System.IO objects to fill your list. Then, when you click a file in that list you can use the System.Drawing.Bitmap object to get or create a thumbnail. To load all the files in all sub folders into a list you will need a recursive function, much like I've shown.

Andy
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:saimatkong
ID: 16306770
thanks for ur help.
anyway it's not really the stuff that i'm looking for,
but really appriciate ur effort.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 16312054
What kind of thumbnails are you looking for?  Are you looking for the same type of thumbnails that Windows Explorer displays?

Bob
0
 

Author Comment

by:saimatkong
ID: 16316751
ya something like tat.

thanks
0
 
LVL 12

Expert Comment

by:AGBrown
ID: 16319888
saimatkong,

No problem. I'm not sure I fully understand your question if this isn't what you are looking for. As far as I know, there is no other way to generate thumbnails other than using the GDI+ objects in System.Drawing, either using the GetThumbnailImage or scaling an image yourself. I also don't know of any other way of loading a folder/file list into a list without using a recursive function with the System.IO objects. I'll watch with interest to see if anyone has a different solution.

Andy
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 150 total points
ID: 16321521
Here is a class that I converted from a VB.NET class to perform the same operation that Windows Explorer does:

using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

public class ShellThumbnail : IDisposable
{

  [Flags]
    private enum ESTRRET
  {
    STRRET_WSTR = 0,
    STRRET_OFFSET = 1,
    STRRET_CSTR = 2
  }

  [Flags]
    private enum ESHCONTF
  {
    SHCONTF_FOLDERS = 32,
    SHCONTF_NONFOLDERS = 64,
    SHCONTF_INCLUDEHIDDEN = 128,
  }

  [Flags]
    private enum ESHGDN
  {
    SHGDN_NORMAL = 0,
    SHGDN_INFOLDER = 1,
    SHGDN_FORADDRESSBAR = 16384,
    SHGDN_FORPARSING = 32768
  }

  [Flags]
    private enum ESFGAO
  {
    SFGAO_CANCOPY = 1,
    SFGAO_CANMOVE = 2,
    SFGAO_CANLINK = 4,
    SFGAO_CANRENAME = 16,
    SFGAO_CANDELETE = 32,
    SFGAO_HASPROPSHEET = 64,
    SFGAO_DROPTARGET = 256,
    SFGAO_CAPABILITYMASK = 375,
    SFGAO_LINK = 65536,
    SFGAO_SHARE = 131072,
    SFGAO_READONLY = 262144,
    SFGAO_GHOSTED = 524288,
    SFGAO_DISPLAYATTRMASK = 983040,
    SFGAO_FILESYSANCESTOR = 268435456,
    SFGAO_FOLDER = 536870912,
    SFGAO_FILESYSTEM = 1073741824,
    SFGAO_HASSUBFOLDER = -2147483648,
    SFGAO_CONTENTSMASK = -2147483648,
    SFGAO_VALIDATE = 16777216,
    SFGAO_REMOVABLE = 33554432,
    SFGAO_COMPRESSED = 67108864,
  }

  private enum EIEIFLAG
  {
    IEIFLAG_ASYNC = 1,
    IEIFLAG_CACHE = 2,
    IEIFLAG_ASPECT = 4,
    IEIFLAG_OFFLINE = 8,
    IEIFLAG_GLEAM = 16,
    IEIFLAG_SCREEN = 32,
    IEIFLAG_ORIGSIZE = 64,
    IEIFLAG_NOSTAMP = 128,
    IEIFLAG_NOBORDER = 256,
    IEIFLAG_QUALITY = 512
  }

  [StructLayout(LayoutKind.Sequential, Pack=4, Size=0, CharSet=CharSet.Auto)]
    private struct STRRET_CSTR
  {
    public ESTRRET uType;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=520)]
    public byte[] cStr;
  }

  [StructLayout(LayoutKind.Explicit, CharSet=CharSet.Auto)]
  private struct STRRET_ANY
  {
    [FieldOffset(0)]
    public ESTRRET uType;
    [FieldOffset(4)]
    public IntPtr pOLEString;
  }
  [StructLayoutAttribute(LayoutKind.Sequential)]
  private struct SIZE
  {
    public int cx;
    public int cy;
  }
 
  [ComImport(), Guid("00000000-0000-0000-C000-000000000046")]
  [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  private interface IUnknown
  {

    [PreserveSig()]
    IntPtr QueryInterface(ref Guid riid, ref IntPtr pVoid);

    [PreserveSig()]
    IntPtr AddRef();

    [PreserveSig()]
    IntPtr Release();
  }
 
  [ComImportAttribute()]
  [GuidAttribute("00000002-0000-0000-C000-000000000046")]
  [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
  private interface IMalloc
  {

    [PreserveSig()]
    IntPtr Alloc(int cb);

    [PreserveSig()]
    IntPtr Realloc(IntPtr pv, int cb);

    [PreserveSig()]
    void Free(IntPtr pv);

    [PreserveSig()]
    int GetSize(IntPtr pv);

    [PreserveSig()]
    int DidAlloc(IntPtr pv);

    [PreserveSig()]
    void HeapMinimize();
  }
 
  [ComImportAttribute()]
  [GuidAttribute("000214F2-0000-0000-C000-000000000046")]
  [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
  private interface IEnumIDList
  {

    [PreserveSig()]
    int Next(int celt, ref IntPtr rgelt, ref int pceltFetched);

    void Skip(int celt);

    void Reset();

    void Clone(ref IEnumIDList ppenum);
  }
 
  [ComImportAttribute()]
  [GuidAttribute("000214E6-0000-0000-C000-000000000046")]
  [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
  private interface IShellFolder
  {

    void ParseDisplayName(IntPtr hwndOwner, IntPtr pbcReserved,    
      [MarshalAs(UnmanagedType.LPWStr)]string lpszDisplayName,
      ref int pchEaten, ref IntPtr ppidl, ref int pdwAttributes);

    void EnumObjects(IntPtr hwndOwner,    
      [MarshalAs(UnmanagedType.U4)]ESHCONTF grfFlags,
      ref IEnumIDList ppenumIDList);

    void BindToObject(IntPtr pidl, IntPtr pbcReserved, ref Guid riid,
      ref IShellFolder ppvOut);

    void BindToStorage(IntPtr pidl, IntPtr pbcReserved, ref Guid riid, IntPtr ppvObj);

    [PreserveSig()]
    int CompareIDs(IntPtr lParam, IntPtr pidl1, IntPtr pidl2);

    void CreateViewObject(IntPtr hwndOwner, ref Guid riid,
      IntPtr ppvOut);

    void GetAttributesOf(int cidl, IntPtr apidl,    
      [MarshalAs(UnmanagedType.U4)]ref ESFGAO rgfInOut);

    void GetUIObjectOf(IntPtr hwndOwner, int cidl, ref IntPtr apidl, ref Guid riid, ref int prgfInOut, ref IUnknown ppvOut);

    void GetDisplayNameOf(IntPtr pidl,    
      [MarshalAs(UnmanagedType.U4)]ESHGDN uFlags,
      ref STRRET_CSTR lpName);

    void SetNameOf(IntPtr hwndOwner, IntPtr pidl,    
      [MarshalAs(UnmanagedType.LPWStr)]string lpszName,    
      [MarshalAs(UnmanagedType.U4)] ESHCONTF uFlags,
      ref IntPtr ppidlOut);
  }
  [ComImportAttribute(), GuidAttribute("BB2E617C-0920-11d1-9A0B-00C04FC2D6C1"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
  private interface IExtractImage
  {
    void GetLocation( [Out(), MarshalAs(UnmanagedType.LPWStr)]
      StringBuilder pszPathBuffer, int cch, ref int pdwPriority, ref SIZE prgSize, int dwRecClrDepth, ref int pdwFlags);

    void Extract(ref IntPtr phBmpThumbnail);
  }

  private class UnmanagedMethods
  {

    [DllImport("shell32", CharSet=CharSet.Auto)]
    internal extern static int SHGetMalloc(ref IMalloc ppMalloc);

    [DllImport("shell32", CharSet=CharSet.Auto)]
    internal extern static int SHGetDesktopFolder(ref IShellFolder ppshf);

    [DllImport("shell32", CharSet=CharSet.Auto)]
    internal extern static int SHGetPathFromIDList(IntPtr pidl, StringBuilder pszPath);

    [DllImport("gdi32", CharSet=CharSet.Auto)]
    internal extern static int DeleteObject(IntPtr hObject);

  }

  ~ShellThumbnail()
  {
    Dispose();
  }

  private IMalloc alloc = null;
  private bool disposed = false;
  private Size _desiredSize = new Size(100, 100);
  private Bitmap _thumbNail;

  public Bitmap ThumbNail
  {
    get
    {
      return _thumbNail;
    }
  }

  public Size DesiredSize
  {
    get { return _desiredSize; }
    set { _desiredSize = value; }
  }

  private IMalloc Allocator
  {
    get
    {
      if (!disposed)
      {
        if (alloc == null)
        {
          UnmanagedMethods.SHGetMalloc(ref alloc);
        }
      }
      else
      {
        Debug.Assert(false, "Object has been disposed.");
      }
      return alloc;
    }
  }

  public Bitmap GetThumbnail(string fileName)
  {
    if (!File.Exists(fileName) && !Directory.Exists(fileName))
    {
      throw new FileNotFoundException(string.Format("The file '{0}' does not exist", fileName), fileName);
    }
    if (_thumbNail != null)
    {
      _thumbNail.Dispose();
      _thumbNail = null;
    }
    IShellFolder folder = null;
    try
    {
      folder = getDesktopFolder;
    }
    catch (Exception ex)
    {
      throw ex;
    }
    if (folder != null)
    {
      IntPtr pidlMain = IntPtr.Zero;
      try
      {
        int cParsed = 0;
        int pdwAttrib = 0;
        string filePath = Path.GetDirectoryName(fileName);
        folder.ParseDisplayName(IntPtr.Zero, IntPtr.Zero, filePath, ref cParsed, ref pidlMain, ref pdwAttrib);
      }
      catch (Exception ex)
      {
        Marshal.ReleaseComObject(folder);
        throw ex;
      }
      if (pidlMain != IntPtr.Zero)
      {
        Guid iidShellFolder = new Guid("000214E6-0000-0000-C000-000000000046");
        IShellFolder item = null;
        try
        {
          folder.BindToObject(pidlMain, IntPtr.Zero, ref iidShellFolder, ref item);
        }
        catch (Exception ex)
        {
          Marshal.ReleaseComObject(folder);
          Allocator.Free(pidlMain);
          throw ex;
        }
        if (item != null)
        {
          IEnumIDList idEnum = null;
          try
          {
            item.EnumObjects(IntPtr.Zero, (ESHCONTF.SHCONTF_FOLDERS | ESHCONTF.SHCONTF_NONFOLDERS), ref idEnum);
          }
          catch (Exception ex)
          {
            Marshal.ReleaseComObject(folder);
            Allocator.Free(pidlMain);
            throw ex;
          }
          if (idEnum != null)
          {
            int hRes = 0;
            IntPtr pidl = IntPtr.Zero;
            int fetched = 0;
            bool complete = false;
            while (!complete)
            {
              hRes = idEnum.Next(1, ref pidl, ref fetched);
              if (hRes != 0)
              {
                pidl = IntPtr.Zero;
                complete = true;
              }
              else
              {
                if (_getThumbNail(fileName, pidl, item))
                {
                  complete = true;
                }
              }
              if (pidl != IntPtr.Zero)
              {
                Allocator.Free(pidl);
              }
            }
            Marshal.ReleaseComObject(idEnum);
          }
          Marshal.ReleaseComObject(item);
        }
        Allocator.Free(pidlMain);
      }
      Marshal.ReleaseComObject(folder);
    }
    return ThumbNail;
  }

  private bool _getThumbNail(string file, IntPtr pidl, IShellFolder item)
  {
    IntPtr hBmp = IntPtr.Zero;
    IExtractImage extractImage = null;
    try
    {
      string pidlPath = PathFromPidl(pidl);
      if (Path.GetFileName(pidlPath).ToUpper().Equals(Path.GetFileName(file).ToUpper()))
      {
        IUnknown iunk = null;
        int prgf = 0;
        Guid iidExtractImage = new Guid("BB2E617C-0920-11d1-9A0B-00C04FC2D6C1");
        item.GetUIObjectOf(IntPtr.Zero, 1, ref pidl, ref iidExtractImage, ref prgf, ref iunk);
        extractImage = (IExtractImage)iunk;
        if (extractImage != null)
        {
          Console.WriteLine("Got an IExtractImage object!");
          SIZE sz = new SIZE();
          sz.cx = DesiredSize.Width;
          sz.cy = DesiredSize.Height;
          StringBuilder location = new StringBuilder(260, 260);
          int priority = 0;
          int requestedColourDepth = 32;
          EIEIFLAG flags = EIEIFLAG.IEIFLAG_ASPECT | EIEIFLAG.IEIFLAG_SCREEN;
          int uFlags = (int)flags;
          extractImage.GetLocation(location, location.Capacity, ref priority, ref sz, requestedColourDepth, ref uFlags);
          extractImage.Extract(ref hBmp);
          if (hBmp != IntPtr.Zero)
          {
            _thumbNail = Bitmap.FromHbitmap(hBmp);
          }
          Marshal.ReleaseComObject(extractImage);
          extractImage = null;
        }
        return true;
      }
      else
      {
        return false;
      }
    }
    catch (Exception ex)
    {
      if (hBmp != IntPtr.Zero)
      {
        UnmanagedMethods.DeleteObject(hBmp);
      }
      if (extractImage != null)
      {
        Marshal.ReleaseComObject(extractImage);
      }
      throw ex;
    }
  }

  private string PathFromPidl(IntPtr pidl)
  {
    StringBuilder path = new StringBuilder(260, 260);
    int result = UnmanagedMethods.SHGetPathFromIDList(pidl, path);
    if (result == 0)
    {
      return string.Empty;
    }
    else
    {
      return path.ToString();
    }
  }

  private IShellFolder getDesktopFolder
  {
    get
    {
      IShellFolder ppshf = null;
      int r = UnmanagedMethods.SHGetDesktopFolder(ref ppshf);
      return ppshf;
    }
  }

  public void Dispose()
  {
    if (!disposed)
    {
      if (alloc != null)
      {
        Marshal.ReleaseComObject(alloc);
      }
      alloc = null;
      if (_thumbNail != null)
      {
        _thumbNail.Dispose();
      }
      disposed = true;
    }
  }

}
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 16321527
Here is an example form (2003):

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

  /// <summary>
  /// Summary description for formShellThumbnail.
  /// </summary>
public class formShellThumbnail : System.Windows.Forms.Form
{
  /// <summary>
  /// Required designer variable.
  /// </summary>
  private System.ComponentModel.Container components = null;

  public formShellThumbnail()
  {
    //
    // Required for Windows Form Designer support
    //
    InitializeComponent();

    //
    // TODO: Add any constructor code after InitializeComponent call
    //
  }

  /// <summary>
  /// Clean up any resources being used.
  /// </summary>
  protected override void Dispose( bool disposing )
  {
    if( disposing )
    {
      if(components != null)
      {
        components.Dispose();
      }
    }
    base.Dispose( disposing );
  }

  /// <summary>
  /// The main entry point for the application.
  /// </summary>
  [STAThread]
  static void Main()
  {
    Application.Run(new formShellThumbnail());
  }

  #region Windows 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.pictureBox1 = new System.Windows.Forms.PictureBox();
    this.SuspendLayout();
    //
    // pictureBox1
    //
    this.pictureBox1.Location = new System.Drawing.Point(44, 28);
    this.pictureBox1.Name = "pictureBox1";
    this.pictureBox1.Size = new System.Drawing.Size(112, 88);
    this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
    this.pictureBox1.TabIndex = 0;
    this.pictureBox1.TabStop = false;
    //
    // formShellThumbnail
    //
    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    this.ClientSize = new System.Drawing.Size(208, 162);
    this.Controls.Add(this.pictureBox1);
    this.Name = "formShellThumbnail";
    this.Text = "Shell Thumbnails";
    this.Load += new System.EventHandler(this.formShellThumbnail_Load);
    this.ResumeLayout(false);

  }
  #endregion

  private System.Windows.Forms.PictureBox pictureBox1;

  private ShellThumbnail _shell = new ShellThumbnail();

  private void formShellThumbnail_Load(object sender, System.EventArgs e)
  {
    this.pictureBox1.Image = _shell.GetThumbnail(@"C:\WINDOWS\Web\Wallpaper\Autumn.jpg");
 
  }
}

Bob
0
 

Author Comment

by:saimatkong
ID: 16323018
thansk anyway =)
0
 

Author Comment

by:saimatkong
ID: 16323033
wow so long the code.
how to execute or call it btw ?
thanks
0
 

Expert Comment

by:tony_duckett
ID: 21533798
This code doesnt seem to work for PDF files.  Any ideas why?
0
 
LVL 3

Expert Comment

by:ghayasurrehman
ID: 33689621
I am using ShellThumbnail in windows7 and it is returning folder thumbnail with black background, any help ???
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
Suggested Courses

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question