[C#]使用BitmapDecoder快速取用圖檔內含的縮圖
public Image GetThumbnail(string file) { var decoder = BitmapDecoder.Create(new Uri(file), BitmapCreateOptions.DelayCreation, BitmapCacheOption.None); var frame = decoder.Frames.FirstOrDefault();
return (frame.Thumbnail == null) ? null : frame.Thumbnail.GetBitmap();
} …
namespace WindowsFormsApplication33 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
public Image GetThumbnail(string file)
{
var decoder = BitmapDecoder.Create(new Uri(file), BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
var frame = decoder.Frames.FirstOrDefault();
return (frame.Thumbnail == null) ? null : frame.Thumbnail.GetBitmap();
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var file = openFileDialog1.FileName;
var sw = Stopwatch.StartNew();
pictureBox1.Image = GetThumbnail(file);
toolStripStatusLabel1.Text = String.Format("Elapsed {0} ms", sw.ElapsedMilliseconds.ToString());
}
}
}
}
public static class BitmapSourceExtension { public static Bitmap GetBitmap(this BitmapSource bitmapsource) { Bitmap bitmap; using (MemoryStream outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitmapsource)); enc.Save(outStream); bitmap = (new Bitmap(outStream)).Clone() as Bitmap; } return bitmap; } }