我试图在Windows窗体应用程序中打开一个.jpg,在其上绘制一个矩形并用矩形保存。 在下面的代码中,我可以加载.jpg并在pictureBox中绘制一个矩形,但不能用矩形保存.jpg。有人知道这个问题吗?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace EditScreen
{
public partial class Form1 : Form
{
Rectangle mRect;
Image mainimage;
Bitmap newBitmap;
Graphics g;
Boolean opened = false;
OpenFileDialog ofd = new OpenFileDialog();
SaveFileDialog sfd = new SaveFileDialog();
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
mainimage = Image.FromFile(ofd.FileName);
newBitmap = new Bitmap(ofd.FileName);
pictureBox1.Image = mainimage;
opened = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult dr = sfd.ShowDialog();
if (opened)
{
mainimage.Save(sfd.FileName);
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
mRect = new Rectangle(e.X, e.Y, 0, 0);
pictureBox1.Invalidate();
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mRect = new Rectangle(mRect.Left, mRect.Top, e.X - mRect.Left, e.Y - mRect.Top);
pictureBox1.Invalidate();
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
using (Pen pen = new Pen(Color.Red, 2))
{
Graphics g = e.Graphics;
g.DrawRectangle(pen, mRect);
}
}
}
}
我听说我必须在位图上绘画,但是当我这样做时,我不知道如何使用PaintEventArgs。你能给我一个代码来举例来保存它吗?