gpt4 book ai didi

wpf - 如何裁剪图像并保存到WPF中的ImageSource中?

转载 作者:行者123 更新时间:2023-12-04 16:32:02 25 4
gpt4 key购买 nike

我是WPF的新手。在这里我有一个问题。
我有一个图像,宽度:360,高度:360。在这里,我要裁剪此图像,如下所示:

(0,0)至(120,120)保存到第一个ImageSource对象,

(120,0)至(240,120)保存到第二个ImageSource对象,

(240,0)至(360,120)保存到第三个ImageSource对象;

……

请在下图中查看更多详细信息:

我的代码示例如下:

    private void CutImage(string img)
{
int iLeft = 0;
int iTop = 0;
int count = 0;

Image thisImg = new Image();
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(img, UriKind.Relative);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
thisImg.Source = src;

for (int i = 0; i < 3; i++)
{
iTop = i * 120;
for (int j = 0; j < 3; j++)
{
iLeft = j * 120;

Canvas canvas = new Canvas();

Rectangle destRect = new Rectangle();
destRect.SetValue(Canvas.LeftProperty, (double)0);
destRect.SetValue(Canvas.TopProperty,(double)0);
destRect.Width = destRect.Height = 120;

Rect srcRect = new Rect();
srcRect.X = iLeft;
srcRect.Y = iTop;
srcRect.Width = srcRect.Height = 120;


thisImg.Clip = new RectangleGeometry(srcRect);

thisImg.Clip.SetValue(Canvas.TopProperty, (double)iTop);
thisImg.Clip.SetValue(Canvas.LeftProperty, (double)iLeft);
thisImg.Clip.SetValue(Canvas.WidthProperty, (double)120);
thisImg.Clip.SetValue(Canvas.HeightProperty,(double)120);

objImg[count++] = (ImageSource)thisImg.GetValue(Image.SourceProperty);
}
}
}

但是它没有按我预期的那样工作,似乎所有ImageSource对象都存储相同的图像,而不是存储相应的部分。有人可以帮助我吗?谢谢。

最佳答案

使用CroppedBitmap可以做到这一点:

private void CutImage(string img)
{
int count = 0;

BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(img, UriKind.Relative);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();

for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
objImg[count++] = new CroppedBitmap(src, new Int32Rect(j * 120, i * 120, 120, 120));
}

关于wpf - 如何裁剪图像并保存到WPF中的ImageSource中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12257908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com