|
|
|
|
|
|
|
Technologies:
.NET 3.0 and 3.5, WPF, XAML,Visual C# .NET
|
|
Total downloads :
|
121
|
|
Total page views :
|
3922
|
|
Rating :
|
|
5/5
|
|
This article has been rated :
|
1 times
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
Related EbooksTop Videos
|
|
|
Description
|
|
This book covers from installation to application design and implementation to deployment. One of the most detailed books on new WPF technology, it provides you with the no-nonsense, practical advice you need in order to build high-quality WPF applications quickly and easily.
|
|
|
|
|
|
|
|
|
|
|
|
|
Introduction
This article describes FileToIconConverter, which is a MultiBinding Converter that can retrieve an Icon from system based on a filename(exist or not) and size.
Background
I am working on a file explorer, which shows a file list, inside the filelist, which require to place a file icon next to each file in a folder. In my first implementation, I added a Icon property in the data model of the file, it works fine. When I implements the Icon View, I added a Large Icon property, then when I add Thumbnail property for the Thumbnail view support.
This implementation has a number of problems,
- Three Bitmaps (Icon, LargeIcon, Thumbnail), Five if include ExtraLarge and Jumbo is holds in the Datamodel, they are usually duplicated (e.g. folder with jpgs), and unused (who will change views regularly anyway)
- Those code are not related to the DataModel, it shoudnt be placed there.
- Icon resize (like the slidebar in vista explorer) become very difficult, as there are 3-5 properties to bind with. So I changed by design, I believe a converter with cache is best suite for this purpose
- Icons are cached in a dictionary, files with same extension occupied only one copy of memory.
- Load on demand, (e.g. if the view need Icon, then load Icon only).
- Reusable, coder just need to bind filename and size Thumbnails are loaded in separate thread (no longer jam the UI), Jumbo icon are shown before the thumbnail is loaded.
How to use?
The converter is a MultiBinding Converter, which takes 2 parameters, filename and size,
- Filename is not necessary to be exists (e.g. abc.txt works),
- Size determine which icon to obtain (Optional)
- <= 16 - Small
- <= 32 - Large
- <= 48 - Extra Large
- <= 100 - Jumbo
- Otherwise, Thumbnail if is an image, Jumbo if not an image.
How it works?
MultiBinding Converter is similar to the normal Binding IValueConverter except it takes multiple value to convert, the Convert is like below :
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
int size = defaultSize;
if (values.Length > 1 && values[1] is double)
size = (int)(float)(double)values[1];
if (values[0] is string)
return imageDic[getIconKey(values[0] as string, size)];
else return imageDic[getIconKey("", size)];
}
- parameter 2 is convert to a local variable named size.
- parameter 1 is convert to a Icon in imageDic with a key (getIconKey() method, see below) Icon are retrieved based on Size and Extensions
- Thumbnail
- Image - Return WritableBitmap (new in dotNet 3.5), which acts like BitmapImage but allow change after initalization.
- otherwise - treat as Icon
- Jumbo / ExtraLarge
- all (include exe) - load from SystemImageList
- Small / Large
- Load using SHGetFileInfo (Win32 api) directly.
I try to avoid SystemImageList because it have it's own cache system which will cause some overhead. There are two cache, iconCache and thumbnailCache, all Icons and thumbnail are stored in cache.
- iconCache is static, for small - Jumbo Icons, common for all FileToIconConverter.
- thumbnailCache is instanced, for thumbnail, you can call ClearInstanceCache() method to clear this cache.
- addToDic() method will add the Icon or Thumbnail (from getImage()) to it's cache
- returnKey() method will return a key for dictionary based on fileName and size,
- e.g. (".txt+L" for Large Text Icon, ".jpg+S" for Small JPEG icon)
- loadBitmap() method takes a Bitmap and return a BitmapSource, it's actually calling Imaging.CreateBitmapSourceFromHBitmap() method, and is required because Image UIelement dont take a bitmap directly. getImage() method retrieve Icon and Thumbnail, it's thumbnail loading code looks like below :
//Load as jumbo icon first. WriteableBitmap bitmap = new WriteableBitmap(addToDic(fileName, IconSize.jumbo) as BitmapSource); ThreadPool.QueueUserWorkItem(new WaitCallback(PollThumbnailCallback), new thumbnailInfo(bitmap, fileName)); return bitmap;
- The code will try to load the jumbo icon first, which usually cached already, and much faster to load even not cache, then when the processor is free, it will call PollThumbnailCallback() in background thread. This implementation will prevent UI thread hogging problem. PollThumbnailCallback() method is not too complicate, it's actually get and resize the thumbnail bitmap (line 4-8), turn it to BitmapSource (Line 9-C), and Write it to the WriteableBitmap obtained (Line 6, D-Q), Line M to Line Q is executed in UI thread, so only work that required to process the writeBitmap is placed there.
1) private void PollThumbnailCallback(object state)
2) {
3) //Non UIThread
4) thumbnailInfo input = state as thumbnailInfo;
5) string fileName = input.fullPath;
6) WriteableBitmap writeBitmap = input.bitmap;
7) Bitmap origBitmap = new Bitmap(fileName);
8) Bitmap inputBitmap = resizeImage(origBitmap, new System.Drawing.Size(256, 256));
9) BitmapSource inputBitmapSource = Imaging.CreateBitmapSourceFromHBitmap(inputBitmap.GetHbitmap(),
A) IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
B) origBitmap.Dispose();
C) inputBitmap.Dispose();
D) int width = inputBitmapSource.PixelWidth;
E) int height = inputBitmapSource.PixelHeight;
F) int stride = width * ((inputBitmapSource.Format.BitsPerPixel + 7) / 8);
G) byte[] bits = new byte[height * stride];
H) inputBitmapSource.CopyPixels(bits, stride, 0);
I) inputBitmapSource = null;
J) writeBitmap.Dispatcher.Invoke(DispatcherPriority.Background,
K) new ThreadStart(delegate
L) {
M) //UI Thread
N) Int32Rect outRect = new Int32Rect(0, (int)(writeBitmap.Height - height) / 2, width, height);
O) writeBitmap.WritePixels(outRect, bits, stride, 0);
P) }));
Q) }
Issues
The component is still very resource hogging. , fixed, I just noticed I have to clear the created object myself using DeleteObject if I called Bitmap.GHbitmap, like below
IntPtr hBitmap = source.GetHbitmap();
return Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
DeleteObject(hBitmap);
References
- System Image List (Steve McMahon, vbaccelerator)
- ResizeImage routine
- How to dispose BitmapSource
History
- 26-12-08 Initial version 28-12-08 version 1, load thumbnail in thread,.
- 28-12-08 version 2, component updated, demo updated.
- 28-12-08 article updated.
- 28-12-08 Version 3, border added for thumbnail, and extra large icon.
- 29-12-08 Version 4, folder support, memory usage reduced.
- 30-12-08 Version 5, fixed memory leak, thread exe icon loading.
License
This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License.
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional
consulting company, our consultants are well-known experts in .NET and many of them
are MVPs, authors, and trainers. We specialize in Microsoft .NET development and
utilize Agile Development and Extreme Programming practices to provide fast pace
quick turnaround results. Our software development model is a mix of Agile Development,
traditional SDLC, and Waterfall models.
|
|
Click here to learn more about C# Consulting. |
|
|
|
|
|
|
|
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon.
Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees.
As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
|
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other
Visual Studio release. Work more productively and collaboratively-with
greater control over your work at every step. The Beta 2 can give you a
head start on achieving efficiency.
|
|
|
|
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|