【问题标题】:Saving Image from a picture box ,image was drawn by graphics object从图片框中保存图像,图像是由图形对象绘制的
【发布时间】:2013-10-03 15:52:09
【问题描述】:

我有这段代码在“pictureBox2.Image.Save(st + "patch1.jpg");" 上抛出异常我认为 pictureBox2.Image 上没有保存任何内容,但我在其上创建了图形 g。 如何保存pictureBox2.Image的图像?

        Bitmap sourceBitmap = new Bitmap(pictureBox1.Image, pictureBox1.Width, pictureBox1.Height);
        Graphics g = pictureBox2.CreateGraphics();
        g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox2.Width, pictureBox2.Height),rectCropArea, GraphicsUnit.Pixel);
        sourceBitmap.Dispose();
        g.Dispose();
        path = Directory.GetCurrentDirectory();
        //MessageBox.Show(path);
        string st = path + "/Debug";
        MessageBox.Show(st);
        pictureBox2.Image.Save(st + "patch1.jpg");

【问题讨论】:

    标签: c# graphics bitmap picturebox


    【解决方案1】:

    几个问题。

    首先,CreateGraphics 是一个临时的绘图表面,不适合保存任何东西。我怀疑您实际上想创建一个新图像并将其显示在第二个 PictureBox 中:

    Bitmap newBitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
    using (Graphics g = Graphics.FromImage(newBitmap)) {
      g.DrawImage(pictureBox1.Image, new Rectangle(0, 0, pictureBox2.Width, pictureBox2.Height), rectCropArea, GraphicsUnit.Pixel);
    }
    pictureBox2.Image = newBitmap;
    

    其次,使用 Path.Combine 函数来创建你的文件字符串:

    string file = Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Debug", "patch1.jpg" });
    newBitmap.Save(file, ImageFormat.Jpeg);
    

    该路径必须存在,否则 Save 方法将引发 GDI+ 异常。

    【讨论】:

    • 我可能比 OP 晚了 3 年,但感谢您花了我几个小时才找到的答案。
    【解决方案2】:

    Graphics g = pictureBox2.CreateGraphics();

    您应该阅读有关您正在调用的此方法的文档,这根本不是您想要的。它用于绘制到 OnPaint 之外的控件,这是不好的做法,会被下一个 OnPaint 覆盖,并且与 PictureBox.Image 属性无关,绝对没有。

    你实际上想做什么?您想保存在 PictureBox 控件中显示的图像的裁剪吗?将裁剪操作保存到磁盘之前是否需要预览?裁剪矩形更改时是否需要更新此预览?提供更多详细信息。

    【讨论】:

      【解决方案3】:

      反过来做。为该位图创建一个目标位图和一个 Graphics 实例。然后将源图片框图像复制到该位图中。最后,将该位图分配给第二个图片框

      Rectangle rectCropArea = new Rectangle(0, 0, 100, 100);
      Bitmap destBitmap = new Bitmap(pictureBox2.Width, pictureBox2.Height);
      Graphics g = Graphics.FromImage(destBitmap);
      g.DrawImage(pictureBox1.Image, new Rectangle(0, 0, pictureBox2.Width, pictureBox2.Height), rectCropArea, GraphicsUnit.Pixel);
      g.Dispose();
      pictureBox2.Image = destBitmap;
      pictureBox2.Image.Save(@"c:\temp\patch1.jpg");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多