我从光盘加载图像:
var img = Image.FromFile("foo");
var bmp = new Bitmap(img);
我写了将图像分成几部分的方法:
public static IEnumerable<Bitmap> VerticalSplit(this Bitmap src, int pixels)
{
var bmps = new List<Bitmap>();
for (int i = 0; i < src.Width; i+=pixels)
{
var dst = new Bitmap(pixels, src.Height);
using (var grD = Graphics.FromImage(dst))
{
grD.DrawImage(src, new Rectangle(i, 0, pixels, src.Height), new Rectangle(0,0,pixels,src.Height), GraphicsUnit.Pixel);
bmps.Add(dst);
}
}
return bmps;
}
这是用法:
var parts = bmp.VerticalSplit(10);
for (int i = 0; i < parts.Count(); i++)
{
parts[i].Save(@"output/" + i + ".jpg");
}
问题是除1之外的每个图像都是空白。为什么会发生这种情况?
答案 0 :(得分:2)
请参阅DrawImage,其签名为:
public void DrawImage(System.Drawing.Image图像, System.Drawing.Rectangle destRect,System.Drawing.Rectangle srcRect, System.Drawing.GraphicsUnit srcUnit);
请注意,第二个参数是“ destRect”,第三个参数是“ srcRect”。您的代码具有目标矩形和源矩形向后。
更改:
grD.DrawImage(src, new Rectangle(i, 0, pixels, src.Height), new Rectangle(0,0,pixels,src.Height), GraphicsUnit.Pixel);
收件人:
grD.DrawImage(src, new Rectangle(0,0,pixels,src.Height), new Rectangle(i, 0, pixels, src.Height), GraphicsUnit.Pixel);