[英]splitting a bitmap into array of bitmaps
請先閱讀標題。 這是主要思想。問題是此C#代碼的問題在哪里?(沒有編譯或運行后錯誤,但不起作用)我對其進行了跟蹤,發現甚至位圖數組也不為空並且該類正常工作; 但是picturebox不顯示array(bitmap)的值。
班級
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GRID
{
class MasterSplitter
{
public BitmapArray_Block[] BMP2Array(Bitmap inp, Point BlockSize)
{
if (BlockSize.X > inp.Width || BlockSize.Y > inp.Height)
BlockSize.X = BlockSize.Y = 100;
int NW =0, NH = 0;
int tx =1, ty = 1;
if (((inp.Width%BlockSize.X) == 0) && ((inp.Height%BlockSize.Y) == 0))
{
NW = inp.Width;
NH = inp.Height;
}
else
{
tx= inp.Width / BlockSize.X;
NW = (BlockSize.X*tx) +BlockSize.X;
ty = inp.Height / BlockSize.Y;
NH = (BlockSize.Y * ty) + BlockSize.Y;
}
//Operations for making an exact bitmap size
Bitmap Temp = new Bitmap(NW, NH);
Graphics g = Graphics.FromImage(Temp);
g.DrawImage(inp, 0, 0, new Rectangle(0,0,Temp.Width, Temp.Height), GraphicsUnit.Pixel);
g.Dispose(); //Cleaning up; Temp now has the exact bitmap size of what input BMP should has for devision.
BitmapArray_Block[] T = new BitmapArray_Block[(tx * ty) + 1]; //Array for Bitmap MatriX
int Xpos = 0, Ypos;
int counter =0;
for (int i=0; i<tx; i++)
{
Ypos = 0;
for (int j=0;j<ty;j++)
{
BitmapArray_Block t = new BitmapArray_Block();
t.start_location = new Point(Xpos,Ypos);
t.BMP = new Bitmap(BlockSize.X,BlockSize.Y);
Graphics gt = Graphics.FromImage(t.BMP);
gt.DrawImage(Temp, Xpos, Ypos, new Rectangle(0, 0, t.BMP.Width, t.BMP.Height), GraphicsUnit.Pixel);
gt.Dispose();
T[counter] = t;
Ypos += BlockSize.Y;
counter+=1;
}
Xpos += BlockSize.X;
}
return T;
}
public class BitmapArray_Block
{
public Point start_location;
public Bitmap BMP;
}
}
顯示結果的代碼:
private void button1_Click(object sender, EventArgs e)
{
MasterSplitter M = new MasterSplitter();
BitmapArray_Block[] T =M.BMP2Array(new Bitmap(pictureBox1.Image),new Point(100,100));
pictureBox1.Image = T[1].BMP;
}
您將DrawImage
的參數弄錯了。 檢查參數說明。 開頭的x
和y
是繪制圖像的坐標,並且矩形(與某些其他重載不同)指定將要繪制的原始圖像部分。
這意味着您當前的代碼始終使用源圖像的左上角,並且在處理了(0,0)的第一個塊之后,您嘗試繪制的部分將簡單地繪制在可用框架的外部。 如果您已經在T[0].BMP
上進行過測試,則它實際上可以工作,但是從索引1開始,所有圖像將為空。
正確的代碼應為:
// "using" will automatically dispose the resource after use, even in case of exceptions.
using(Graphics gt = Graphics.FromImage(t.BMP))
gt.DrawImage(Temp, 0, 0, new Rectangle(Xpos, Ypos, BlockSize.X, BlockSize.Y), GraphicsUnit.Pixel);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.