画像の拡大・縮小 (イメージのリサイズ) - C#
C#で画像の拡大・縮小の手順を紹介します。
コード (form_main.cs)
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;
namespace ImageResize
{
public partial class Form_Main : Form
{
public Form_Main()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
textBox1.Text = openFileDialog1.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(textBox1.Text);
int resizeWidth = 160;
int resizeHeight = (int)(bmp.Height * ((double)resizeWidth / (double)bmp.Width));
Bitmap resizeBmp = new Bitmap(resizeWidth, resizeHeight);
Graphics g = Graphics.FromImage(resizeBmp);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
//g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
g.DrawImage(bmp, 0, 0, resizeWidth, resizeHeight);
g.Dispose();
Graphics pg = Graphics.FromHwnd(panel1.Handle);
pg.DrawImage(resizeBmp, new Point(0, 0));
}
}
}
フォーム
解説
Bitmap bmp = new Bitmap(textBox1.Text);
にてTextBoxに入力されたパスの画像ファイルを読み込みます。
int resizeWidth = 160;
int resizeHeight = (int)(bmp.Height * ((double)resizeWidth / (double)bmp.Width));
にて縮小画像のサイズを計算します。今回は縮小画像は横160pixelとします。縦は元画像の縦横比をもとに計算します。
Bitmap resizeBmp = new Bitmap(resizeWidth, resizeHeight);
先に計算された画像サイズをもつ縮小画像のBitmapを作成します。
Graphics g = Graphics.FromImage(resizeBmp);
縮小画像のGraphicsオブジェクトを取得します。
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
画像を縮小する際のアルゴリズムを設定します。
g.DrawImage(bmp, 0, 0, resizeWidth, resizeHeight);
元画像を縮小画像に縮小して描画します。
Graphics pg = Graphics.FromHwnd(panel1.Handle);
pg.DrawImage(resizeBmp, new Point(0, 0));
PanelのGraphicsオブジェクトを取得し縮小画像をPanel1に描画します。
実行結果
画像ファイルのファイル名をテキストボックスに入力してButton2をクリックすると縮小画像をフォームに表示します。
InterpolationMode.HighQualityBicubic の場合
InterpolationMode.NearestNeighborの場合
このページのキーワード
- C#
- 画像の拡大
- 画像の縮小
- 画像のリサイズ
- イメージのリサイズ
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用