请先阅读标题。这是主要的想法 问题是这个C#代码的问题在哪里?(没有编译或运行错误但是没有工作) 我跟踪它,发现甚至数组的位图都不是空的,并且该类正常工作;但是picturebox没有显示数组的值(位图)。
课程
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;
}
答案 0 :(得分:0)
你得到了DrawImage
错误的论点。检查参数描述。开头的x
和y
是绘制图像的坐标,与其他一些重载不同,矩形指定<的部分<将绘制的em>原始图像。
这意味着您当前的代码始终采用源图像的左上角,并且在处理(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);