效果图(本来无边框,加了边框看方便)
1、原图
2、裁切后的图
3、话不多说、直接贴代码【控制台程序实例】
using System;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//原图
string savePath = @"C:\Users\Administrator\Desktop\1.jpg";
using (Image noneImage = Image.FromFile(savePath))
{
Bitmap bmp = new Bitmap(noneImage);
int width = noneImage.Width;
int height = noneImage.Height;
int topx = 0;
int topy = 0;
int bottomx = 0;
int bottomy = 0;
int i = 0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
Color color = bmp.GetPixel(x, y);
int r = color.R;
int g = color.G;
int b = color.B;
int a = color.A;
if (r == 253 &&
g == 253 &&
b == 253 &&
a == 255)
{
continue;
}
if (i == 0)
{
topx = x;
topy = y;
bottomx = x;
bottomy = y;
i++;
}
else
{
if (topx > x) topx = x;
if (topy > y) topy = y;
if (bottomx < x) bottomx = x;
if (bottomy < y) bottomy = y;
}
}
}
SaveCutPic(savePath, savePath.Replace(".jpg", "_m.jpg"), topx, topy, bottomx - topx, bottomy - topy, 0, 0);
}
}
/// <summary>
/// 裁剪图片
/// </summary>
/// <param name="nonePath"></param>
/// <param name="savePath"></param>
/// <param name="startX"></param>
/// <param name="startY"></param>
/// <param name="saveWidth"></param>
/// <param name="saveHeight"></param>
/// <param name="endX"></param>
/// <param name="endY"></param>
/// <returns></returns>
private static bool SaveCutPic(string nonePath, string savePath,
int startX, int startY, int saveWidth,
int saveHeight, int endX, int endY)
{
using (Image originalImg = Image.FromFile(nonePath))
{
try
{
Bitmap partImg = new Bitmap(saveWidth, saveHeight);
Graphics graphics = Graphics.FromImage(partImg);
//目标位置
Rectangle destRect = new Rectangle(new Point(endX, endY), new Size(saveWidth, saveHeight));
//原图位置(默认从原图中截取的图片大小等于目标图片的大小)
Rectangle origRect = new Rectangle(new Point(startX, startY), new Size(saveWidth, saveHeight));
///注释 文字水印
Graphics G = Graphics.FromImage(partImg);
//Font f = new Font("Lucida Grande", 6);
//Brush b = new SolidBrush(Color.Gray);
G.Clear(Color.White);
// 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。
G.InterpolationMode = InterpolationMode.HighQualityBicubic;
// 指定高质量、低速度呈现。
G.SmoothingMode = SmoothingMode.HighQuality;
graphics.DrawImage(originalImg, destRect, origRect, GraphicsUnit.Pixel);
//G.DrawString("Xuanye", f, b, 0, 0);
G.Dispose();
originalImg.Dispose();
if (File.Exists(savePath))
{
File.SetAttributes(savePath, FileAttributes.Normal);
File.Delete(savePath);
}
//效果图
partImg.Save(savePath, ImageFormat.Jpeg);
partImg.Dispose();
}
catch
{
return false;
}
}
return true;
}
}
}