using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
namespace bitmaprerote
{
public partial class caijian : Form
{
public caijian()
{
InitializeComponent();
}
/// <summary>
/// 剪裁
/// </summary>
/// <param name="b">原始Bitmap</param>
/// <param name="StartX">开始坐标X</param>
/// <param name="StartY">开始坐标Y</param>
/// <param name="iWidth">宽度</param>
/// <param name="iHeight">高度</param>
/// <returns>剪裁后的Bitmap</returns>
public static Bitmap KiCut(Bitmap b, int StartX, int StartY, int iWidth, int iHeight)
{
if (b == null)
{
return null;
}
int w = b.Width;
int h = b.Height;
if (StartX >= w || StartY >= h)
{
return null;
}
if (StartX + iWidth > w)
{
iWidth = w - StartX;
}
if (StartY + iHeight > h)
{
iHeight = h - StartY;
}
try
{
Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(bmpOut);
g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel);
g.Dispose();
return bmpOut;
}
catch
{
return null;
}
}
private void button1_Click(object sender, EventArgs e)
{
Bitmap map = new Bitmap("F:\\hj.jpg");
map = KiCut(map, pictureBox1.Location.X, pictureBox1.Location.Y, 60, 60);
pictureBox1.Image = map;
}
}
}
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
namespace bitmaprerote
{
public partial class caijian : Form
{
public caijian()
{
InitializeComponent();
}
/// <summary>
/// 剪裁
/// </summary>
/// <param name="b">原始Bitmap</param>
/// <param name="StartX">开始坐标X</param>
/// <param name="StartY">开始坐标Y</param>
/// <param name="iWidth">宽度</param>
/// <param name="iHeight">高度</param>
/// <returns>剪裁后的Bitmap</returns>
public static Bitmap KiCut(Bitmap b, int StartX, int StartY, int iWidth, int iHeight)
{
if (b == null)
{
return null;
}
int w = b.Width;
int h = b.Height;
if (StartX >= w || StartY >= h)
{
return null;
}
if (StartX + iWidth > w)
{
iWidth = w - StartX;
}
if (StartY + iHeight > h)
{
iHeight = h - StartY;
}
try
{
Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(bmpOut);
g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel);
g.Dispose();
return bmpOut;
}
catch
{
return null;
}
}
private void button1_Click(object sender, EventArgs e)
{
Bitmap map = new Bitmap("F:\\hj.jpg");
map = KiCut(map, pictureBox1.Location.X, pictureBox1.Location.Y, 60, 60);
pictureBox1.Image = map;
}
}
}
这篇博客介绍了一个在WinForm应用中裁剪图片的C#方法。通过KiCut函数,可以指定原始Bitmap的开始坐标和裁剪尺寸,返回一个新的Bitmap对象。在示例中,当按钮被点击时,读取指定路径的图片,然后进行裁剪,并将裁剪后的图片显示在pictureBox1上。
2957

被折叠的 条评论
为什么被折叠?



