我需要在.NET Core中裁剪图像。我使用了ImageSharp、CoreCompat和Microsoft.Windows.Compatibility,并扫描了能找到的所有方法。然而,我仍然无法找到一个裁剪图像的方法。虽然有调整大小的方法,但没有裁剪的方法。
如何根据左上角像素位置、宽度和高度在.NET Core中裁剪图像?
我需要在.NET Core中裁剪图像。我使用了ImageSharp、CoreCompat和Microsoft.Windows.Compatibility,并扫描了能找到的所有方法。然而,我仍然无法找到一个裁剪图像的方法。虽然有调整大小的方法,但没有裁剪的方法。
如何根据左上角像素位置、宽度和高度在.NET Core中裁剪图像?
int width = 0;
int height = 0;
image.Mutate(ctx => ctx.Crop(width, height));
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Advanced;
No you don't. You need SixLabors.ImageSharp.Processing
- James Southprivate async static Task CropImage()
{
using (var httpClient = new HttpClient())
{
var response = await httpClient.GetAsync("https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark.png")
.ConfigureAwait(false);
using (var inputStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
using (var image = Image.Load(inputStream))
{
var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "foo.png");
image.Clone(
ctx => ctx.Crop(560, 300)).Save(path);
}
}
}
}
System.Drawing.Common package
using SD = System.Drawing;
static byte[] Crop(string Img, int Width, int Height, int X, int Y)
{
try
{
using (SD.Image OriginalImage = SD.Image.FromFile(Img))
{
using (SD.Bitmap bmp = new SD.Bitmap(Width, Height))
{
bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
using (SD.Graphics Graphic = SD.Graphics.FromImage(bmp))
{
Graphic.SmoothingMode = SmoothingMode.AntiAlias;
Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
Graphic.DrawImage(OriginalImage, new SD.Rectangle(0, 0, Width, Height), X, Y, Width, Height, SD.GraphicsUnit.Pixel);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, OriginalImage.RawFormat);
return ms.GetBuffer();
}
}
}
}
catch (Exception Ex)
{
throw (Ex);
}
}
ms.GetBuffer()
,因为它可能是一个比写入的像素数据更大的字节数组。 - James South您可以使用Bitmap.Clone(Rectangle rect, PixelFormat format)方法,例如,作为Bitmap的扩展:
using System.Drawing;
static public class BitmapExtensions
{
static public Bitmap Crop(this Bitmap bitmap, Rectangle rect)
{
return bitmap.Clone(rect, bitmap.PixelFormat);
}
}
首先安装“System.Drawing.Common”包。
using System.Drawing;
using System.Drawing.Imaging;
...
public byte[] Crop(string path, int width, int height)
{
Image img = Image.FromFile(path);
Bitmap bmp = new Bitmap(width, height);
bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(img, 0, 0);
using (MemoryStream ms = new MemoryStream())
{
bmp.Save(ms, ImageFormat.Jpeg);
return ms.ToArray();
}
}