我想在c#中裁剪图像。和大多数照片编辑软件一样,我想使用矩形框,可以通过鼠标调整大小和重新定位。另外,我想知道如何突出显示裁剪区域,如this photo中所示。
答案 0 :(得分:1)
您的图片链接不再可用。
因此,假设在一个面板中,您的图片框中包含要裁剪的图像。
首先,您需要为鼠标操作创建事件处理程序,以便能够绘制您想要裁剪的矩形区域:
private void picBox_MouseDown(object sender, MouseEventArgs e)
{
Cursor = Cursors.Default;
if (Makeselection)
{
try
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
Cursor = Cursors.Cross;
cropX = e.X;
cropY = e.Y;
cropPen = new Pen(Color.Crimson, 1);
cropPen.DashStyle = DashStyle.Solid;
}
picBox.Refresh();
}
catch (Exception ex)
{
}
}
}
private void picBox_MouseUp(object sender, MouseEventArgs e)
{
if (Makeselection)
{
Cursor = Cursors.Default;
}
}
private void picBox_MouseMove(object sender, MouseEventArgs e)
{
Cursor = Cursors.Default;
if (Makeselection)
{
picBox.Cursor = Cursors.Cross;
try
{
if (picBox.Image == null)
return;
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
picBox.Refresh();
cropWidth = e.X - cropX;
cropHeight = e.Y - cropY;
picBox.CreateGraphics().DrawRectangle(cropPen, cropX, cropY, cropWidth, cropHeight);
}
}
catch (Exception ex)
{
}
}
}
private void picBox_MouseLeave(object sender, EventArgs e)
{
tabControl.Focus();
}
private void picBox_MouseEnter(object sender, EventArgs e)
{
picBox.Focus();
}
现在,按钮点击功能可以裁剪图像:
private void btnCrop_Click_1(object sender, EventArgs e)
{
Cursor = Cursors.Default;
try
{
if (cropWidth < 1)
{
return;
}
Rectangle rect = new Rectangle(cropX, cropY, cropWidth, cropHeight);
//First we define a rectangle with the help of already calculated points
Bitmap OriginalImage = new Bitmap(picBoxScreenshot.Image, picBoxScreenshot.Width, picBoxScreenshot.Height);
//Original image
Bitmap _img = new Bitmap(cropWidth, cropHeight);
// for cropinfo image
Graphics g = Graphics.FromImage(_img);
// create graphics
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
//set image attributes
g.DrawImage(OriginalImage, 0, 0, rect, GraphicsUnit.Pixel);
picBox.Image = _img;
picBox.Width = _img.Width;
picBox.Height = _img.Height;
PictureBoxLocation();
cropWidth = 0;
}
catch (Exception ex){}
}
private void PictureBoxLocation()
{
int _x = 0;
int _y = 0;
if (panel1.Width > picBox.Width)
{
_x = (panel1.Width - picBox.Width) / 2;
}
if (panel1.Height > picBox.Height)
{
_y = (panel1.Height - picBox.Height) / 2;
}
picBox.Location = new Point(_x, _y);
picBox.Refresh();
}
答案 1 :(得分:0)
选择框的外部似乎有一个黑色图像,其alpha值约为30%。要做到这一点,您只需将每个像素放在内容区域之外,然后在其上绘制一个30%alpha的黑色像素。这将产生所需的暗淡效果。
至于如何在C#中使矩形可动态选择。
答案 2 :(得分:0)
为了将照片绘制得更亮或更暗(或以任何方式改变颜色),您可以使用 ColorMatrix ,例如this。