Solved

Display thumbnail of images in folder c#

Posted on 2014-07-25
7
997 Views
Last Modified: 2014-07-30
Hi all,

I want to read all image contained in a folder and display in a repeater.

Now as the images could be quite large I was hoping to generate thumbnails rather than using the whole image.

any ideas on how I can achieve this?

I currently get the images as follows;

            string[] list = Directory.GetFiles(Server.MapPath("images"));
            var aList = from fileName in Directory.GetFiles(Server.MapPath("images")) select string.Format("/images/{0}", Path.GetFileName(fileName));
            ImageUploadRepeater.DataSource = aList;
            ImageUploadRepeater.DataBind(); 

Open in new window

0
Comment
Question by:flynny
  • 4
  • 2
7 Comments
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40219327
0
 
LVL 1

Expert Comment

by:Sameer Rakshe
ID: 40219330
Bind to a node in Active Directory Domain Services with the DirectoryEntry class
Use the DirectorySearcher class to specify a search filter and find the desired user
Extract the image bytes from the user properties
Convert the bytes to a usable format.

Go through below code:

private void GetUserPicture(string userName)
{
    var directoryEntry = new DirectoryEntry("LDAP://YourDomain");
    var directorySearcher = new DirectorySearcher(directoryEntry);
    directorySearcher.Filter = string.Format("(&(SAMAccountName={0}))", userName);
    var user = directorySearcher.FindOne();

    var bytes = user.Properties["thumbnailPhoto"][0] as byte[];

    using (var ms = new MemoryStream(bytes))
    {
        var imageSource = new BitmapImage();
        imageSource.BeginInit();
        imageSource.StreamSource = ms;
        imageSource.EndInit();

        uxPhoto.Source = imageSource;
    }
}

Open in new window

0
 

Author Comment

by:flynny
ID: 40219401
kaufmed,

many thanks for your reply.

Is it possible to just send a thumbnail client side and not alter or store an additional image?

for example if i upload a 900px by 400px image. When I display this image i would like to get the thumbnail snap shot and simply bind it to my repeater?

the example code you show saves a copy of the downgraded image?

is the only alternative to maybe save a _thumbnail copy of the image in the same folder? If this is the case how can i filter out the large images and just select the thumbnails.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 40219481
Anything on the web has to have a URI in order to be retrieved by a browser. You don't necessarily have to have a physical file in order to server something to a browser, but you do have to have a URI. You could create a second "page" whose only job is to serve files. The downside is that you have one URI to (most likely) serve multiple images, so you'll end up losing caching. However, I believe you can work around this by adding in a querystring.

As an example, the new page that I refer to would be a generic handler (.ashx). It could look like this:

Markup
<%@ WebHandler Language="C#" CodeBehind="GetThumbnail.ashx.cs" Class="WebApplication2.GetThumbnail1" %>

Open in new window


Code Behind
using System;
using System.IO;
using System.Web;

namespace WebApplication2
{
    public class GetThumbnail1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string filename = context.Request.QueryString["filename"];

            if (!string.IsNullOrWhiteSpace(filename))
            {
                string mappedPath = context.Server.MapPath(Path.Combine("Images/", filename));

                if (File.Exists(mappedPath))
                {
                    System.Drawing.Image source = System.Drawing.Image.FromFile(mappedPath);
                    System.Drawing.Image thumbnail = source.GetThumbnailImage(100, 100, null, IntPtr.Zero);
                    MemoryStream imgData = new MemoryStream();

                    thumbnail.Save(imgData, System.Drawing.Imaging.ImageFormat.Png);

                    context.Response.Clear();
                    context.Response.Headers["Content-Type"] = "image/png";
                    context.Response.BinaryWrite(imgData.ToArray());
                    context.Response.Flush();
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

Open in new window


Then, in your main page do something like:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <asp:Image ImageUrl="~/GetThumbnail.ashx?filename=orderedList9.png" runat="server" />
</asp:Content>

Open in new window


The Image object points to the new handler that was created. The querystring allows you to change which image is served without having to implement a handler for each image on your server (yikes!).
0
 

Author Comment

by:flynny
ID: 40219491
thats great.

how would this stand from a performance perspective? as whilst its ideal in that there are no scaled images stored on the machine, it is essentially creating these images on the fly?

woul dyou go with this or just store thumbnails and access these?
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40219492
P.S.

You may need to fiddle with lines 24 and 27 if you are working with image format other than PNG. I just used PNG as an example (since that was what my Images folder already contained).
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40219499
it is essentially creating these images on the fly?
Yes.

woul dyou go with this or just store thumbnails and access these?
I haven't worked on anything yet that has had this requirement, so I'd probably be the wrong person to ask for an opinion. The only thing I could say would be that you can benchmark both approaches and see what works better for you. If you have a low to moderate traffic site, then this may not be a big deal. If you're serving Google-level traffic, and you don't have distributed architecture, then this might not be so hot.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
This video discusses moving either the default database or any database to a new volume.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

758 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now