Ashish Rathore
Ashish Rathore

Reputation: 2696

How to show image in datagridview as thumbnail

I have a windows application form and i need to show the image thumbnails in datagridview.

The images are stored as binary data in SQL Server 2005.

Is there any method to show image's thumbnails without storing image as file on disc.

Please reply as soon as possible.

Upvotes: 0

Views: 3382

Answers (2)

user3686869
user3686869

Reputation: 26

Just add a datagridviewimage column set width of the column and set data-source after that loop through each row and set row height.

Example

dgvEmpInfo.DataSource = ds.Tables[0];

       foreach (DataGridViewRow dgvRow in dgvEmpInfo.Rows)
       {
           dgvRow.Height = 100;
       }

Upvotes: 1

Stokke
Stokke

Reputation: 2011

Yes.I'll assume you have the images stored in a byte array:

byte[] bArray = GetRawImageBytes();

// Get an image object from the byte-array
Image ddbImage;
using (var ms = new MemoryStream(bArray, 0, bArray.Length))
{
    ms.Write(bArray, 0, bArray.Length);
    ddbImage = Image.FromStream(ms, true);
}

// Create a 100x100 thumbnail from the image
var ThumbnailSize = new Size(100, 100);
var thumb = ddbImage.GetThumbnailImage(
            ThumbnailSize.Height, 
            ThumbnailSize.Width, 
            null, IntPtr.Zero);

// Create an image column for the datagridview
var imgColumn = new DataGridViewImageColumn
{
    HeaderText = "Image", 
    Name = "img"
};

dataGridView1.Columns.Add(imgColumn);

// Add the first row, using this image
dataGridView1.Rows.Add();
dataGridView1.Rows[0].Cells[0].Value = thumb;

// lets set the gridview-height to the thumbnail height
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    row.Height = ThumbnailSize.Height;
}

Edit: For convenient cut & paste code for testing, here is a dummy function that will return a byte-array of an image stored on disk:

private byte[] GetRawImageBytes()
{
    var img = Image.FromFile(PATH_TO_TEST_IMAGE);
    byte[] bArray;
    using (var ms = new MemoryStream())
    {
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        bArray = ms.GetBuffer();
    }
    return bArray;
}

Upvotes: 1

Related Questions