What is causing a OverflowException on TransformedBitmap.EndInit when trying to scale a bitmap in WPF?
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(Bit开发者_如何学编程mapFrame.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.
You already calculated the required scaling, 800/600. Don't multiply by the image size. Fix:
tbmp.Transform = new ScaleTransform(targetScale, targetScale);
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:
double scaleX = targetScale / bmps.PixelWidth;
double scaleY = targetScale / bmps.PixelHeight;
After all, I assume that if the original picture is bigger, you want to stretch is less, not more.
精彩评论