我正在做的是制作一个设计卡并实时显示图像的程序.我已经完成了这一部分,并且效果很好.现在,我需要裁剪图像并将其保存为atm的方式进行保存,顶部和底部有2个白色条.这是我现在用于保存的代码.
private void SaveCardbtn_Click(object sender, EventArgs e)
{
//Open the saveFileDialog
if (saveWork.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
CardImg.Image.Save(saveWork.FileName, ImageFormat.Jpeg);
}
}
谢谢.
解决方法:
我已经在ASP.NET论坛中发布了这个答案.
请试试这个 –
以下裁剪功能将接受4个参数:
>宽度:这是裁剪图像的宽度.
>高度:这是裁剪图像的高度.
>源图像文件路径:这将是源图像文件的完整路径.
>保存裁剪的图像文件路径:这将是保存裁剪的图像文件的完整路径.
public static void CropImage(int Width, int Height, string sourceFilePath, string saveFilePath) {
// variable for percentage resize
float percentageResize = 0;
float percentageResizeW = 0;
float percentageResizeH = 0;
// variables for the dimension of source and cropped image
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
// Create a bitmap object file from source file
Bitmap sourceImage = new Bitmap(sourceFilePath);
// Set the source dimension to the variables
int sourceWidth = sourceImage.Width;
int sourceHeight = sourceImage.Height;
// Calculate the percentage resize
percentageResizeW = ((float)Width / (float)sourceWidth);
percentageResizeH = ((float)Height / (float)sourceHeight);
// Checking the resize percentage
if (percentageResizeH < percentageResizeW) {
percentageResize = percentageResizeW;
destY = System.Convert.ToInt16((Height - (sourceHeight * percentageResize)) / 2);
} else {
percentageResize = percentageResizeH;
destX = System.Convert.ToInt16((Width - (sourceWidth * percentageResize)) / 2);
}
// Set the new cropped percentage image
int destWidth = (int)Math.Round(sourceWidth * percentageResize);
int destHeight = (int)Math.Round(sourceHeight * percentageResize);
// Create the image object
using (Bitmap objBitmap = new Bitmap(Width, Height)) {
objBitmap.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
using (Graphics objGraphics = Graphics.FromImage(objBitmap)) {
// Set the graphic format for better result cropping
objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
objGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
objGraphics.DrawImage(sourceImage, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel);
// Save the file path, note we use png format to support png file
objBitmap.Save(saveFilePath, ImageFormat.Png);
}
}
}
通过使用以下代码调用上述CropImage方法:
CropImage(100, 100, "c://destinationimage.jpg", "c://newcroppedimage.jpg");
希望这个能对您有所帮助!