C# 如何在以拉伸模式显示图像的pictureBox中裁剪原始图像?
如何在以拉伸模式显示的pictureBox中裁剪图像 我在pictureBox中绘制了一个矩形:C# 如何在以拉伸模式显示图像的pictureBox中裁剪原始图像?,c#,image,bitmap,crop,picturebox,C#,Image,Bitmap,Crop,Picturebox,如何在以拉伸模式显示的pictureBox中裁剪图像 我在pictureBox中绘制了一个矩形: void pictureBox1_MouseUp(object sender, MouseEventArgs e) { //pictureBox1.Image.Clone(); xUp = e.X; yUp = e.Y; Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(
void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
//pictureBox1.Image.Clone();
xUp = e.X;
yUp = e.Y;
Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));
using (Pen pen = new Pen(Color.YellowGreen, 3))
{
pictureBox1.CreateGraphics().DrawRectangle(pen, rec);
}
rectCropArea = rec;
}
void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
pictureBox1.Invalidate();
xDown = e.X;
yDown = e.Y;
}
并使用以下命令裁剪所选零件:
private void btnCrop_Click(object sender, EventArgs e)
{
try
{
pictureBox3.Refresh();
//Prepare a new Bitmap on which the cropped image will be drawn
Bitmap sourceBitmap = new Bitmap(pictureBox1.Image, pictureBox1.Width, pictureBox1.Height);
Graphics g = pictureBox3.CreateGraphics();
//Draw the image on the Graphics object with the new dimesions
g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox3.Width, pictureBox3.Height), rectCropArea, GraphicsUnit.Pixel);
sourceBitmap.Dispose();
}
catch (Exception ex)
{
}
}
但是裁剪图像的质量非常低,因为它裁剪的是拉伸图像而不是原始图像。如何裁剪用户在pictureBox中绘制的矩形大小的原始图像?我将pictureBox1\u鼠标的代码更改为:
void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
xUp = e.X;
yUp = e.Y;
Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));
using (Pen pen = new Pen(Color.YellowGreen, 3))
{
pictureBox1.CreateGraphics().DrawRectangle(pen, rec);
}
xDown = xDown * pictureBox1.Image.Width / pictureBox1.Width;
yDown = yDown * pictureBox1.Image.Height / pictureBox1.Height;
xUp = xUp * pictureBox1.Image.Width / pictureBox1.Width;
yUp = yUp * pictureBox1.Image.Height / pictureBox1.Height;
rectCropArea = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));
}
而且成功了。感谢“Hans Passant”的回答。我将pictureBox1\u鼠标的代码更改为:
void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
xUp = e.X;
yUp = e.Y;
Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));
using (Pen pen = new Pen(Color.YellowGreen, 3))
{
pictureBox1.CreateGraphics().DrawRectangle(pen, rec);
}
xDown = xDown * pictureBox1.Image.Width / pictureBox1.Width;
yDown = yDown * pictureBox1.Image.Height / pictureBox1.Height;
xUp = xUp * pictureBox1.Image.Width / pictureBox1.Width;
yUp = yUp * pictureBox1.Image.Height / pictureBox1.Height;
rectCropArea = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));
}
而且成功了。感谢“Hans Passant”的回答。您必须将鼠标位置映射到图像坐标,以确定需要裁剪的内容。当您使用“拉伸”时,它只是x=e.x*image.Width/pictureBox.Width。谢谢Hans Passant,它成功了。您必须将鼠标位置映射到图像坐标,以确定需要剪切的内容。当你使用Stretch时,它只是x=e.x*image.Width/pictureBox.Width。谢谢你,Hans Passant,它成功了。