C# 图像裁剪、分割、保存
如主题中所述,我有一个图像:
private Image testing;
testing = new Bitmap(@"sampleimg.jpg");
我想将其分成 3 x 3 矩阵,即总共 9 个图像并保存它。有什么技巧或技巧可以做到这一点吗?我正在使用 Visual Studio 2008 并在智能设备上工作。尝试了一些方法,但我无法得到它。这是我尝试过的:
int x = 0;
int y = 0;
int width = 3;
int height = 3;
int count = testing.Width / width;
Bitmap bmp = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bmp);
for (int i = 0; i < count; i++)
{
g.Clear(Color.Transparent);
g.DrawImage(testing, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
bmp.Save(Path.ChangeExtension(@"C\AndrewPictures\", String.Format(".{0}.bmp",i)));
x += width;
}
as stated in subject, i have an image:
private Image testing;
testing = new Bitmap(@"sampleimg.jpg");
I would like to split it into 3 x 3 matrix meaning 9 images in total and save it.Any tips or tricks to do this simple? I'm using visual studios 2008 and working on smart devices. Tried some ways but i can't get it. This is what i tried:
int x = 0;
int y = 0;
int width = 3;
int height = 3;
int count = testing.Width / width;
Bitmap bmp = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bmp);
for (int i = 0; i < count; i++)
{
g.Clear(Color.Transparent);
g.DrawImage(testing, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
bmp.Save(Path.ChangeExtension(@"C\AndrewPictures\", String.Format(".{0}.bmp",i)));
x += width;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 .NET 版本,您可以执行以下操作之一进行裁剪:
.NET 2.0
或 .NET 3.5+
正如您所看到的,它比您正在做的要简单一些。第一个示例克隆当前图像并获取其子集;第二个示例使用
CroppedBitmap
,它支持直接从构造函数获取图像的一部分。分割部分是简单的数学运算,只需将图像分割成 9 组坐标并将它们传递给构造函数即可。
Depending on the .NET version, you could do one of the following to crop:
.NET 2.0
Or .NET 3.5+
As you can see, it's a bit more simple than what you're doing. The first example clones the current image and takes a subset of it; the second example uses
CroppedBitmap
, which supports taking a section of the image right from the constructor.The splitting part is simple maths, just splitting the image into 9 sets of coordinates and passing them into the constructor.