2

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.

1
  • 1
    scaleX and scaleY are gonna be huge. It's maybe that. Commented Dec 17, 2010 at 10:55

2 Answers 2

3

You already calculated the required scaling, 800/600. Don't multiply by the image size. Fix:

  tbmp.Transform = new ScaleTransform(targetScale, targetScale);
Sign up to request clarification or add additional context in comments.

2 Comments

You changed your question. This answer tells you why you got the exception, your original question.
Oh right, my bad, I seem to loose track of that sometimes, I'll change it back and open a new topic :)
1

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.

1 Comment

I changed it to that but now I get images that are 1 x 1 and black (1 black pixel).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.