简体   繁体   English

创建图形并将其另存为位图

[英]Create graphic and save it as Bitmap

I have two questions: 我有两个问题:

1) I have a PictureBox and its Dock is set to Fill. 1)我有一个PictureBox ,其Dock设置为Fill。 When I resize the Form I cannot create a Graphic on the part of the PictureBox that is extended. 当我调整Form大小时,我不能在PictureBox的扩展部分创建一个Graphic。 What is the problem? 问题是什么?

2) I want to convert the Graphic that is created on the PictureBox to Bitmap and save it as *.JPG or *.bmp. 2)我想将PictureBox上创建的Graphic转换为Bitmap ,并将其保存为* .JPG或* .bmp。 How can I do this? 我怎样才能做到这一点?

you can use the handle device to get the bitmap out of the picture box 您可以使用句柄设备从图片框中取出位图

Graphics g = pictureBox1.CreateGraphics();          
Bitmap bitMap = Bitmap.FromHbitmap(g.GetHdc());
bitMap.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);

or even better, if the pictureBox does`nt modify the image, you can directly get the image from the pictureBox control 甚至更好,如果pictureBox没有修改图像,你可以直接从pictureBox控件获取图像

pictureBox1.Image.Save("path", System.Drawing.Imaging.ImageFormat.Jpeg);

Try this, works fine for me... 试试这个,对我来说很好......

    private void SaveControlImage(Control ctr)
    {
        try
        {
            var imagePath = @"C:\Image.png";

            Image bmp = new Bitmap(ctr.Width, ctr.Height);
            var gg = Graphics.FromImage(bmp);
            var rect = ctr.RectangleToScreen(ctr.ClientRectangle);
            gg.CopyFromScreen(rect.Location, Point.Empty, ctr.Size);

            bmp.Save(imagePath);
            Process.Start(imagePath);

        }
        catch (Exception)
        {
            //
        }
    }

1) Your description is very vague. 1)您的描述非常模糊。 Do you get an exception? 你有例外吗? Does it display wrong results? 它显示错误的结果吗? What is happening? 怎么了?

2) You need to get the Image from the PictureBox and use its Save method . 2)您需要从PictureBox获取图像并使用其Save方法

When the Picturebox gets resized to fill the form, it seems it's Image property stays the same. 当Picturebox调整大小以填充表单时,它的Image属性似乎保持不变。

So what you need to do is handle the PictureBox.OnSizeChanged Event, and then use the following code to resize the image: 所以你需要做的是处理PictureBox.OnSizeChanged事件,然后使用以下代码来调整图像大小:

private void pictureBox1_SizeChanged(object sender, EventArgs e)
{
    if ((pictureBox1.Image != null))
    {
        pictureBox1.Image = new Bitmap(pictureBox1.Image, pictureBox1.Size);
    }
}

To save the image use: 要保存图像,请使用:

pictureBox1.Image.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);

Hope that helps! 希望有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM