''' <summary>
''' 指定したImageを分割する。
''' </summary>
''' <param name="originalImage">オリジナルImage</param>
''' <param name="verticalNum">分割数(垂直)</param>
''' <param name="horizontalNum">分割数(水平)</param>
''' <returns>分割済Image</returns>
''' <remarks></remarks>
Public Shared Function DivideImage( _
ByVal originalImage As Image, _
ByVal verticalNum As Integer, ByVal horizontalNum As Integer _
) As Image()()
'引数チェック
If originalImage Is Nothing Then
Throw New ArgumentNullException("originalImage is null")
End If
If verticalNum < 1 Then
Throw New ArgumentOutOfRangeException("verticalNum < 1")
End If
If horizontalNum < 1 Then
Throw New ArgumentOutOfRangeException("horizontalNum < 1")
End If
Dim g As Graphics = Nothing
Dim rtnImage()() As Image = New Image(verticalNum - 1)() {}
For i As Integer = 0 To verticalNum - 1
rtnImage(i) = New Image(horizontalNum - 1) {}
Next
Dim originalSize As Size = originalImage.Size
Dim divWidth As Integer = originalSize.Width / horizontalNum
Dim divHeight As Integer = originalSize.Height / verticalNum
For vCnt As Integer = 0 To verticalNum - 1
For hCnt As Integer = 0 To horizontalNum - 1
Try
'空のImageを作成
rtnImage(vCnt)(hCnt) = New Bitmap(divWidth, divHeight)
'Imageを描画する為のGraphicsオブジェクトを作成
g = System.Drawing.Graphics.FromImage( _
rtnImage(vCnt)(hCnt))
'オリジナルImageから描画対象の領域を算出
'[補足]
' 領域の開始座標を
' ・hCnt * divWidth
' ・vCnt * divHeight
' ではなく、
' ・hCnt * originalSize.Width / horizontalNum
' ・vCnt * originalSize.Height / verticalNum
' にしているのは、誤差を軽減する為です。
Dim rect As New Rectangle( _
hCnt * originalSize.Width / horizontalNum, _
vCnt * originalSize.Height / verticalNum, _
divWidth, _
divHeight _
)
'オリジナルImageの内容を描画
g.DrawImage( _
originalImage, 0, 0, rect, GraphicsUnit.Pixel)
Finally
If Not (g Is Nothing) Then
'Graphicsオブジェクトを解放
g.Dispose()
End If
End Try
Next
Next
Return rtnImage
End Function
[VB.NET]Imageを分割する例
/// <summary>
/// 指定したImageを分割する。
/// </summary>
/// <param name="originalImage">オリジナルImage</param>
/// <param name="verticalNum">分割数(垂直)</param>
/// <param name="horizontalNum">分割数(水平)</param>
/// <returns>分割済Image</returns>
/// <remarks></remarks>
public static Image[][] DivideImage(
Image originalImage, int verticalNum, int horizontalNum)
{
//引数チェック
if (originalImage == null) {
throw new ArgumentNullException("originalImage is null");
}
if (verticalNum < 1) {
throw new ArgumentOutOfRangeException("verticalNum < 1");
}
if (horizontalNum < 1) {
throw new ArgumentOutOfRangeException("horizontalNum < 1");
}
Graphics g = null;
Image[][] rtnImage = new Image[verticalNum][];
for (int i = 0; i <= verticalNum - 1; i++) {
rtnImage(i) = new Image[horizontalNum];
}
Size originalSize = originalImage.Size;
int divWidth = originalSize.Width / horizontalNum;
int divHeight = originalSize.Height / verticalNum;