Kalpesh
Kalpesh

Reputation: 113

Error saving resized image

I have the following code

int oswidth = 0;
int osheight = 0;

        if (comboBox3.SelectedIndex == 0)
        {
            oswidth = Convert.ToInt32(textBox5.Text.ToString());
            osheight = Convert.ToInt32(textBox6.Text.ToString());
        }
        else if (comboBox3.SelectedIndex == 1)
        {
            oswidth = 38 * Convert.ToInt32(textBox5.Text.ToString());
            osheight = 38 * Convert.ToInt32(textBox6.Text.ToString());


        }

        Bitmap oldimg = new Bitmap(pictureBox3.Image);
        Bitmap objBitmap = new Bitmap(oldimg, new Size(oswidth, osheight));
        objBitmap.Save(pictureBox3.ImageLocation.ToString(), ImageFormat.Jpeg);

The problem is when the selected index is 0 it works fine but when the selected index is 1 i get a error "Parameter is not valid."
i tried different images but same error. is it the multiply by 32 thing

Upvotes: 0

Views: 121

Answers (2)

Greg
Greg

Reputation: 11480

You could utilize the following method:

private static void ResizeImage(string file, double vscale, double hscale, string output)
{
     using(var source = Image.FromFile(file))
     {
          var width = (int)(source.Width * vscale);
          var height = (int)(source.Height * hscale);
          using(var image = new Bitmap(width, height, PixelFormat.Format24bppRgb))
               using(var graphic = Graphics.FromImage(image))
               {
                    graphic.SmoothingMode = SmoothingMode.AntiAlias;
                    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    graphic.DrawImage(source, new Rectangle(0, 0, width, height));
                    image.Save(output);
               }
     }
}

You can tailor this however you'd like, but it should meet your needs.

Important: The reason vscale and hscale are separate is to not follow scaling. You can easily combine them so you can scale accordingly. The other thing to remember, is your using a value of 32. Try using a value of .32 which will treat it more like a percent, which will scale. Also it won't increase the memory drastically causing your error.

Upvotes: 1

Tharwen
Tharwen

Reputation: 3107

The Parameter is not valid error message when trying to create a Bitmap usually means that you are trying to allocate too much memory to it. The bitmap requires bit-depth*width*height/8 bytes of contiguous memory, and there just isn't enough available to satisfy that.

In this case, it looks like it's because you're multiplying its dimensions by 38 (and therefore multiplying the size in memory by 38^2).

Upvotes: 2

Related Questions