如何根据图片框的大小生成图片

本文关键字:生成图片 何根 | 更新日期: 2023-09-27 18:03:48

我根据图片框的大小生成图片,并将图片设置为大小模式为正常但全图不显示的图片框,而图片的少部分区域被截断。我想以这样一种方式生成图片,结果当我将图片设置在图片框上时,应该显示完整的图像。下面是生成图片

的代码
    new Bitmap _lastSnapshot = new Bitmap(261, 204);
    this.DrawToBitmap((Bitmap)_lastSnapshot, new Rectangle(Point.Empty, ((Bitmap)_lastSnapshot).Size));

261,204为图片框的大小,图片大小模式为正常。我在生成后将lastSnapshot分配给图片框,但没有显示全图。

我得到了一个例程来根据图片框的大小调整图像的大小。它工作得很好,但图像看起来模糊不清。我必须设置图片框的大小模式拉伸,以填充图片到PIC框。

下面是我用来根据图片框大小调整图片大小的例程。
public static Image ResizeImage(Image image, Size size, 
    bool preserveAspectRatio = true)
{
    int newWidth;
    int newHeight;
    if (preserveAspectRatio)
    {
        int originalWidth = image.Width;
        int originalHeight = image.Height;
        float percentWidth = (float)size.Width / (float)originalWidth;
        float percentHeight = (float)size.Height / (float)originalHeight;
        float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
        newWidth = (int)(originalWidth * percent);
        newHeight = (int)(originalHeight * percent);
    }
    else
    {
        newWidth = size.Width;
        newHeight = size.Height;
    }
    Image newImage = new Bitmap(newWidth, newHeight);
    using (Graphics graphicsHandle = Graphics.FromImage(newImage))
    {
        graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
    }
    return newImage;
}

调用例程

ResizeImage(value,pictureBox1.Size,true);

谁能给一些建议,以生成和调整图片的大小适合图片框与良好的水晶清晰的图像。由于

如何根据图片框的大小生成图片

如果你想根据picturebox的大小预览图片,那么:修改PictureBox属性的SizeMode为Zoom

pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;