0

我有以下代码

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);

问题是当所选索引为0时,它可以正常工作,但是当所选索引为1时,我会遇到一个错误“参数无效”。
我尝试了不同的图像但同样的错误。是乘以 32 的东西吗

4

2 回答 2

2

尝试创建位图时的Parameter is not valid错误消息通常意味着您试图为其分配过多的内存。位图需要bit-depth*width*height/8字节的连续内存,并且没有足够的可用空间来满足这一点。

在这种情况下,看起来是因为您将其尺寸乘以 38(因此将内存中的大小乘以 38^2)。

于 2014-09-08T14:16:09.473 回答
1

您可以使用以下方法:

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);
               }
     }
}

您可以随意调整它,但它应该满足您的需求。

重要:vscalehscale分开的原因是不遵循缩放。您可以轻松地将它们组合起来,以便相应地进行扩展。要记住的另一件事是您使用32. 尝试使用一个值,.32它将把它更像一个百分比,它会缩放。此外,它不会大幅增加内存,从而导致您的错误。

于 2014-09-08T15:02:15.670 回答