Thursday, June 14, 2012

Thumbnail of images.

Yank thumbnail from image EXIF.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Drawing.Imaging; namespace Thumbs { public partial class Form1 : Form { private const int THUMBNAIL_DATA = 0x501B; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { Image thm = GetThumbnail(openFileDialog1.FileName); //now write that image to file thm.Save(openFileDialog1.FileName+".jpg", ImageFormat.Jpeg); } } Image GetThumbnail(string path) { FileStream fs = File.OpenRead(path); // Last parameter tells GDI+ not the load the actual image data Image img = Image.FromStream(fs, false, false); // GDI+ throws an error if we try to read a property when the image // doesn't have that property. Check to make sure the thumbnail property // item exists. bool propertyFound = false; for (int i = 0; i < img.PropertyIdList.Length; i++) if (img.PropertyIdList[i] == THUMBNAIL_DATA) { propertyFound = true; break; } if (!propertyFound) return null; PropertyItem p = img.GetPropertyItem(THUMBNAIL_DATA); fs.Close(); img.Dispose(); // The image data is in the form of a byte array. Write all // the bytes to a stream and create a new image from that stream byte[] imageBytes = p.Value; MemoryStream stream = new MemoryStream(imageBytes.Length); stream.Write(imageBytes, 0, imageBytes.Length); return Image.FromStream(stream); } } }