从文件中裁剪图像并在C#中重新保存
本文关键字:新保存 保存 裁剪 文件 图像 | 更新日期: 2023-09-27 18:21:33
以前从未真正使用过Graphics。我环顾四周,从回答我问题的小部分中拼凑出了一些解决方案。但都没有奏效。
我想从文件中加载一个图像,该文件的大小将始终为320x240。然后我想裁剪它以获得240x240的图像,每侧的外部40px都经过修剪。完成后,我想保存为一个新的图像。
private void croptoSquare(string date)
{
//Location of 320x240 image
string fileName = Server.MapPath("~/Content/images/" + date + "contactimage.jpg");
//New rectangle of final size (I think maybe Point is where I would eventually specify where the crop square site i.e. (40, 0))
Rectangle cropRect = new Rectangle(new Point(0, 0), new Size(240, 240));
//Create a Bitmap with correct height/width.
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
//Load image from file
using (Image image = Image.FromFile(fileName))
{
//Create Graphics object from image
using (Graphics graphic = Graphics.FromImage(image))
{
//Not sure what this does, I found it on a post.
graphic.DrawImage(image,
cropRect,
new Rectangle(0, 0, target.Width, target.Height),
GraphicsUnit.Pixel);
fileName = Server.MapPath("~/Content/images/" + date + "contactimagecropped.jpg");
image.Save(fileName);
}
}
}
目前,它只是重新保存相同的图像,我不知道为什么。我已经将目标矩形指定为240x240,将src矩形指定为320x240。
正如我所说,我基本上对处理图形对象一无所知,所以我认为这是公然的。
有人能告诉我如何实现我想要的吗?
private void croptoSquare(string date)
{
//Location of 320x240 image
string fileName = Server.MapPath("~/Content/images/" + date + "contactimage.jpg");
// Create a new image at the cropped size
Bitmap cropped = new Bitmap(240,240);
//Load image from file
using (Image image = Image.FromFile(fileName))
{
// Create a Graphics object to do the drawing, *with the new bitmap as the target*
using (Graphics g = Graphics.FromImage(cropped) )
{
// Draw the desired area of the original into the graphics object
g.DrawImage(image, new Rectangle(0, 0, 240, 240), new Rectangle(40, 0, 240, 240), GraphicsUnit.Pixel);
fileName = Server.MapPath("~/Content/images/" + date + "contactimagecropped.jpg");
// Save the result
cropped.Save(fileName);
}
}
}
为什么不使用JCrop?http://www.programmerclubhouse.com/index.php/crop-image-using-jcrop-in-asp-net-c-shar/