サムネイルを作成する
サムネイルを作る手順。
画像ファイルのサムネイルを作成する
画像ファイルからサムネイルを作るのは、そのためのメソッドがあるので割と簡単。
- Image img = Image.FromFile(path);
- Image th = img.GetThumbnailImage(100, 100, new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
- this.pictureBox.image = th;
- // ThumbnailCallback は以下のメソッドを作っておけばOK。
- public bool ThumbnailCallback()
- {
- return false;
- }
画像の縦横の比率を考慮したサムネイルを作るC#コード
サムネイルを正方形にしたいときは、サイズを調整する必要がある。縦か横に余白を付けるわけです。
参考元:
- Image doサムネイル作成(Image img, int w, int h)
- {
- Bitmap canvas = new Bitmap(w, h);
- Graphics g = Graphics.FromImage(canvas);
- g.FillRectangle(new SolidBrush(Color.White), 0, 0, w, h);
- float fh = h;
- float fw = w;
- int n = Math.Max(img.Width, img.Height);
- if (n > 0)
- {
- fw = (float)img.Width / n * w;
- fh = (float)img.Height / n * h;
- }
- // 余白があいたら中央寄せをするために開始位置をずらす
- DrawImage(img, (w - fw) / 2, (h - fh) / 2, fw, fh);
- g.Dispose();
- return canvas;
- }
ListViewコントロールでサムネイル画像を一覧表示するには?
PDFファイルのサムネイルの作り方
Microsoft.WindowsAPICodePack を使うと、PDFファイルのサムネイルを作ることができる。次のメソッドは、PDFファイルのサムネイルをPNGファイルとアイコンファイルに保存する。どちらも256x256のサイズのファイルが保存される。あと、ActobatReaderを事前にセットアップしておきましょう。
- using Microsoft.WindowsAPICodePack.Shell;
- void doSaveサムネイルPDF(string p)
- {
- ShellObject sh = ShellObject.FromParsingName(p);
- Image img2 = sh.Thumbnail.LargeBitmap;
- string f = System.IO.Path.GetDirectoryName(p) + "\\" + System.IO.Path.GetFileNameWithoutExtension(p) + ".png";
- img2.Save(f);
- f = System.IO.Path.GetDirectoryName(p) + "\\" + System.IO.Path.GetFileNameWithoutExtension(p) + ".ico";
- Icon icon = sh.Thumbnail.LargeIcon;
- System.IO.StreamWriter os = new System.IO.StreamWriter(f);
- System.IO.Stream st = os.BaseStream;
- icon.Save(st);
- os.Close();
- }
PDFファイルと作成したサムネイルファイルをエクスプローラで見ると、以下のようになる。
*
コメント
コメントを投稿