尝试在 WPF 中缩放位图时,是什么导致 TransformedBitmap.EndInit 上出现 OverflowException?
我有以下代码:
private void Process(string path)
{
using (FileStream fs = File.OpenRead(path))
{
JpegBitmapDecoder decoder = new JpegBitmapDecoder(fs,BitmapCreateOptions.PreservePixelFormat,BitmapCacheOption.Default);
BitmapSource bmps = decoder.Frames.First();
double targetScale = 800.0/600.0;
double scaleX = bmps.PixelWidth*targetScale;
double scaleY = bmps.PixelHeight*targetScale;
TransformedBitmap tbmp = new TransformedBitmap();
tbmp.BeginInit();
tbmp.Source = bmps;
tbmp.Transform = new ScaleTransform(scaleX, scaleY);
tbmp.EndInit();
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(tbmp));
using (FileStream fs2 = File.OpenWrite(path+".jpg"))
{
Debug.WriteLine(path+".jpg");
encoder.Save(fs2);
}
}
}
它在 tbmp.EndInit();
处抛出 OverflowException
知道为什么吗?
更新:可能值得一提的是,该方法是通过 ParallelQuery 调用的。但它并不依赖于不同线程中的任何内容。
I have the following code:
private void Process(string path)
{
using (FileStream fs = File.OpenRead(path))
{
JpegBitmapDecoder decoder = new JpegBitmapDecoder(fs,BitmapCreateOptions.PreservePixelFormat,BitmapCacheOption.Default);
BitmapSource bmps = decoder.Frames.First();
double targetScale = 800.0/600.0;
double scaleX = bmps.PixelWidth*targetScale;
double scaleY = bmps.PixelHeight*targetScale;
TransformedBitmap tbmp = new TransformedBitmap();
tbmp.BeginInit();
tbmp.Source = bmps;
tbmp.Transform = new ScaleTransform(scaleX, scaleY);
tbmp.EndInit();
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(tbmp));
using (FileStream fs2 = File.OpenWrite(path+".jpg"))
{
Debug.WriteLine(path+".jpg");
encoder.Save(fs2);
}
}
}
It throws an OverflowException
at tbmp.EndInit();
Any idea why?
UPDATE: It might be worth mentioning that this method is called through a ParallelQuery. It doesn't depend on anything that could be in a different thread though.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已经计算出所需的缩放比例 800/600。不要乘以图像大小。使固定:
You already calculated the required scaling, 800/600. Don't multiply by the image size. Fix:
我的猜测是因为你的规模很大。例如,假设原始图片为 1600x1200...然后将其缩放 2,133.33333x1600 倍,最终图片大小为 3,413,333 x 1,920,000 - 这是一张相当大的图片!
我怀疑你想要:
毕竟,我假设如果原始图片更大,你想要拉伸的是更少,而不是更多。
My guess is that it's because your scale is huge. For example, suppose the original picture is 1600x1200... you're then scaling it by a factor of 2,133.33333x1600, giving you a final picture size of 3,413,333 x 1,920,000 - which is a pretty huge picture!
I suspect you wanted:
After all, I assume that if the original picture is bigger, you want to stretch is less, not more.