2012-11-29 33 views
9

thể trùng lặp:
Image splitting into 9 piecesCắt một hình ảnh thành 9 mảnh C#

Mặc dù tôi googled đủ nhưng tiếc là không tìm thấy một sự giúp đỡ. Điều này Code Project Tutorial cũng không phục vụ cho tôi những gì tôi thực sự cần.

Tôi có một ImageBox và 9 PictureBox (s) trong một WinForm.

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; 

Dưới đây là một ví dụ hình ảnh cho bạn:

enter image description here

Đây là một phần của dự án Puzzle lớp Ảnh của tôi. Tôi đã làm với hình ảnh photoshop, bây giờ muốn tự động cắt.

Xin cảm ơn trước.

Trả lời

13

Trước hết, thay vì sử dụng img1, img2 ... sử dụng một mảng với kích thước của 9. Sau đó, nó dễ dàng hơn để làm điều này bằng một vài vòng như thế này:

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(); 
    } 
} 

Sau đó, bạn có thể điền vào các ô của bạn như sau:

pictureBox1.Image = imgarray[0]; 
pictureBox2.Image = imgarray[1]; 
... 
7

Bạn có thể thử với mã này. Về cơ bản, nó tạo ra một ma trận hình ảnh (giống như bạn cần trong dự án của bạn) và vẽ trên mỗi phần hình ảnh lớn một phần đầy đủ của Bitmap. Khái niệm tương tự bạn có thể sử dụng cho pictureBoxes và đặt chúng vào ma trận.

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];