DOBON.NET プログラミング道: .NET Framework, VB.NET, C#, Visual Basic, Visual Studio, インストーラ, ...

DOBON.NET

画像を動的に作成する

補足:画像の表示方法が分からないという方は、まず「画像ファイルを表示する」をご覧ください。

画像をファイルから読み込むのではなく、動的に(プログラムで)作成する簡単な方法を紹介します。

まず、作成する画像の大きさを指定して、Bitmapオブジェクトを作成します。Bitmapオブジェクトに図形や画像を描画するには、Graphics.FromImageメソッドにより取得できるGraphicsオブジェクトを使用します。またBitmap.SetPixelメソッドにより、任意の点の色を変えることも出来ます。

[VB.NET]
'大きさを指定してBitmapオブジェクトの作成
Dim img As New Bitmap(200, 100)

'imgのGraphicsオブジェクトを取得
Dim g As Graphics = Graphics.FromImage(img)

'白に塗りつぶす
g.FillRectangle(Brushes.White, g.VisibleClipBounds)

'ノイズを入れる
'(適当な色の点を適当な位置にうちまくる)
Dim rnd As New Random
Dim i As Integer
For i = 0 To 2000
    '色の作成
    Dim col As Color = _
        Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256))
    '1つのピクセルの色を変える
    img.SetPixel(rnd.Next(img.Width), rnd.Next(img.Height), col)
Next i

'文字列の描画
Dim fnt As New Font("Arial", 18)
Dim sf As New StringFormat
sf.Alignment = StringAlignment.Center
sf.LineAlignment = StringAlignment.Center
g.DrawString("DOBON.NET", fnt, Brushes.Blue, g.VisibleClipBounds, sf)

'作成した画像を表示する
Dim pg As Graphics = PictureBox1.CreateGraphics()
pg.DrawImage(img, g.VisibleClipBounds)

'リソースを開放する
img.Dispose()
fnt.Dispose()
g.Dispose()
pg.Dispose()
[C#]
//大きさを指定してBitmapオブジェクトの作成
Bitmap img = new Bitmap(200, 100);

//imgのGraphicsオブジェクトを取得
Graphics g = Graphics.FromImage(img);

//白に塗りつぶす
g.FillRectangle(Brushes.White, g.VisibleClipBounds);

//ノイズを入れる
//(適当な色の点を適当な位置にうちまくる)
Random rnd = new Random();
for (int i = 0; i < 2000; i++)
{
    //色の作成
    Color col = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));
    //1つのピクセルの色を変える
    img.SetPixel(rnd.Next(img.Width), rnd.Next(img.Height), col);
}

//文字列の描画
Font fnt = new Font("Arial", 18);
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
g.DrawString("DOBON.NET", fnt, Brushes.Blue, g.VisibleClipBounds, sf);

//作成した画像を表示する
Graphics pg = PictureBox1.CreateGraphics();
pg.DrawImage(img, g.VisibleClipBounds);

//リソースを開放する
img.Dispose();
fnt.Dispose();
g.Dispose();
pg.Dispose();

注意:この記事では、基本的な事柄の説明が省略されているかもしれません。初心者の方は、特に以下の点にご注意ください。

  • このサイトで紹介されているコードの多くは、例外処理が省略されています。例外処理については、こちらをご覧ください。