サムネイルを作成する

サムネイルを作る手順。


画像ファイルのサムネイルを作成する

画像ファイルからサムネイルを作るのは、そのためのメソッドがあるので割と簡単。
  1. Image img = Image.FromFile(path);
  2. Image th = img.GetThumbnailImage(100, 100, new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
  3. this.pictureBox.image = th;
  4.  
  5. // ThumbnailCallback は以下のメソッドを作っておけばOK。
  6. public bool ThumbnailCallback()
  7. {
  8. return false;
  9. }

画像の縦横の比率を考慮したサムネイルを作るC#コード

サムネイルを正方形にしたいときは、サイズを調整する必要がある。縦か横に余白を付けるわけです。
  1. Image doサムネイル作成(Image img, int w, int h)
  2. {
  3. Bitmap canvas = new Bitmap(w, h);
  4. Graphics g = Graphics.FromImage(canvas);
  5. g.FillRectangle(new SolidBrush(Color.White), 0, 0, w, h);
  6. float fh = h;
  7. float fw = w;
  8. int n = Math.Max(img.Width, img.Height);
  9. if (n > 0)
  10. {
  11. fw = (float)img.Width / n * w;
  12. fh = (float)img.Height / n * h;
  13. }
  14. // 余白があいたら中央寄せをするために開始位置をずらす
  15. DrawImage(img, (w - fw) / 2, (h - fh) / 2, fw, fh);
  16. g.Dispose();
  17. return canvas;
  18. }
参考元:
ListViewコントロールでサムネイル画像を一覧表示するには?

PDFファイルのサムネイルの作り方

Microsoft.WindowsAPICodePack を使うと、PDFファイルのサムネイルを作ることができる。次のメソッドは、PDFファイルのサムネイルをPNGファイルとアイコンファイルに保存する。どちらも256x256のサイズのファイルが保存される。

あと、ActobatReaderを事前にセットアップしておきましょう。

  1. using Microsoft.WindowsAPICodePack.Shell; 

  1. void doSaveサムネイルPDF(string p)
  2. {
  3. ShellObject sh = ShellObject.FromParsingName(p);
  4.  
  5. Image img2 = sh.Thumbnail.LargeBitmap;
  6. string f = System.IO.Path.GetDirectoryName(p) + "\\" + System.IO.Path.GetFileNameWithoutExtension(p) + ".png";
  7. img2.Save(f);
  8.  
  9. f = System.IO.Path.GetDirectoryName(p) + "\\" + System.IO.Path.GetFileNameWithoutExtension(p) + ".ico";
  10. Icon icon = sh.Thumbnail.LargeIcon;
  11. System.IO.StreamWriter os = new System.IO.StreamWriter(f);
  12. System.IO.Stream st = os.BaseStream;
  13. icon.Save(st);
  14. os.Close();
  15. }

PDFファイルと作成したサムネイルファイルをエクスプローラで見ると、以下のようになる。




コメント

このブログの人気の投稿

varchar をデータ型 numeric に変換中に、算術オーバーフロー エラーが発生しました。