将图像切成9块C#

who*_*one 9 c# image picturebox

可能重复:
图像分为9个部分

虽然我用Google搜索足够但很遗憾找不到帮助.此代码项目教程也无法满足我的实际需要.

我在WinForm中有一个Image和9 PictureBox.

Image img = Image.FromFile("media\\a.png"); // a.png has 312X312 width and height
//          some code help, to get
//          img1, img2, img3, img4, img5, img6, img7, img8, img9
//          having equal width and height
//          then...
pictureBox1.Image = img1;
pictureBox2.Image = img2;
pictureBox3.Image = img3;
pictureBox4.Image = img4;
pictureBox5.Image = img5;
pictureBox6.Image = img6;
pictureBox7.Image = img7;
pictureBox8.Image = img8;
pictureBox9.Image = img9;
Run Code Online (Sandbox Code Playgroud)

这是一个示例图像为您:

在此输入图像描述

这是我的Picture Puzzle类项目的一部分.我已经完成了photoshop图片,现在想动态剪切.

提前致谢.

Øyv*_*hen 17

首先,不使用img1,img2 ...使用大小为9的数组.然后使用这样的几个循环更容易做到这一点:

var imgarray = new Image[9];
var img = Image.FromFile("media\\a.png");
for( int i = 0; i < 3; i++){
  for( int j = 0; j < 3; j++){
    var index = i*3+j;
    imgarray[index] = new Bitmap(104,104);
    var graphics = Graphics.FromImage(imgarray[index]);
    graphics.DrawImage( img, new Rectangle(0,0,104,104), new Rectangle(i*104, j*104,104,104), GraphicsUnit.Pixel);
    graphics.Dispose();
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样填写你的盒子:

pictureBox1.Image = imgarray[0];
pictureBox2.Image = imgarray[1];
...
Run Code Online (Sandbox Code Playgroud)


Nik*_*vic 7

您可以尝试使用此代码.它基本上创建了一个图像矩阵(就像您在项目中需要的那样),并绘制Bitmap了大图像的每个适当部分.您可以使用相同的概念pictureBoxes并将它们放入矩阵中.

Image img = Image.FromFile("media\\a.png"); // a.png has 312X312 width and height
int widthThird = (int)((double)img.Width / 3.0 + 0.5);
int heightThird = (int)((double)img.Height / 3.0 + 0.5);
Bitmap[,] bmps = new Bitmap[3,3];
for (int i = 0; i < 3; i++)
    for (int j = 0; j < 3; j++)
    {
        bmps[i, j] = new Bitmap(widthThird, heightThird);
        Graphics g = Graphics.FromImage(bmps[i, j]);
        g.DrawImage(img, new Rectangle(0, 0, widthThird, heightThird), new Rectangle(j * widthThird, i * heightThird, widthThird, heightThird), GraphicsUnit.Pixel);
        g.Dispose();
    }
pictureBox1.Image = bmps[0, 0];
pictureBox2.Image = bmps[0, 1];
pictureBox3.Image = bmps[0, 2];
pictureBox4.Image = bmps[1, 0];
pictureBox5.Image = bmps[1, 1];
pictureBox6.Image = bmps[1, 2];
pictureBox7.Image = bmps[2, 0];
pictureBox8.Image = bmps[2, 1];
pictureBox9.Image = bmps[2, 2];
Run Code Online (Sandbox Code Playgroud)