裁剪PNG图片透明部分

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;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace DXApplication1
{
public partial class Form1 : DevExpress.XtraEditors.XtraForm
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
ClipPng(Application.StartupPath + "\1.png");
}
/// <summary>
/// 裁剪PNG图片透明部分
/// </summary>
/// <param name="filepath"></param>
public static void ClipPng(string filepath)
{
FileInfo fileInfo = new FileInfo(filepath);
Bitmap bitmap = new Bitmap(filepath);
Rectangle rectangle = GetRectangle(bitmap);
Bitmap bakBitmap = bitmap.Clone(rectangle, bitmap.PixelFormat);
string bakFilePath = $@"{fileInfo.Directory}{fileInfo.Name}-bak{fileInfo.Extension}";
bakBitmap.Save(bakFilePath, ImageFormat.Png);
bitmap.Dispose();
fileInfo.Delete();
fileInfo = new FileInfo(bakFilePath);
fileInfo.CopyTo(filepath);
System.IO.File.Delete(bakFilePath);
}/// <summary>
/// 根据图片得到一个图片非透明部分的矩形范围
/// </summary>
/// <param name="bckImage"></param>
/// <returns></returns>
public static unsafe Rectangle GetRectangle(Bitmap bckImage)
{
int w = bckImage.Width;//原宽
int h = bckImage.Height;//原高
//x:原图左侧到非透明范围左侧的长度
//y:原图头部到非透明范围头部的高度
//width:裁剪后图片宽度
//height:裁剪后图片高度
int x = 0, y = 0, width = 0, height = 0;

BitmapData bckdata = null;
try
{
bckdata = bckImage.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
uint* bckInt = (uint*)bckdata.Scan0;
for (int j = 0; j < h; j++)
{
for (int i = 0; i < w; i++)
{
if ((*bckInt & 0xff000000) != 0)
{
if (x == 0 || i < x)
{
x = i;
}
if (y == 0 || j < y)
{
y = j;
}
if (width == 0 || i > width)
{
width = i;
}
if (height == 0 || j > height)
{
height = j;
}

}
bckInt++;
}
}
bckImage.UnlockBits(bckdata); bckdata = null;
}
catch
{
if (bckdata != null)
{
bckImage.UnlockBits(bckdata);
bckdata = null;
}
}
int border = 20;//边框大小
if (x > border)
{
x -= border;
}
if (y > border)
{
y -= border;
}
if ((w - width) > border)
{
width += border;
}
if ((h - height) > border)
{
height += border;
}
return new Rectangle(x, y, width - x, height - y);
}
}
}

原文地址:https://www.cnblogs.com/liushunli/p/14839283.html