我需要从 UWP 应用程序的照片中裁剪 .png 图像中定义的特定形状(透明背景和顶部的白色形状)。
我找到的唯一代码是用于裁剪圆形或方形等形状的代码,我需要裁剪创建为 png 图像的自定义形状,这在任何文档或论坛上都没有,所以我无法向您展示可行的代码像那样。
更具体地说,我需要接收两个 png 文件的功能,一个是照片,第二个是应该从照片中裁剪的形状,然后将具有透明背景的裁剪部分保存到指定位置作为 .png 文件
好吧,我找到了使用
SixLabors.ImageSharp
nuget 包的解决方案(两个图像的大小应该相同)。
private static async Task<string> CropShapeFromImage(string sourceImagePath, string maskImagePath)
{
using var sourceImage = Image.Load<Rgba32>(sourceImagePath);
var outputImage = new Image<Rgba32>(sourceImage.Width, sourceImage.Height);
// Some workaround for acces deined to file error
var maskFile = await StorageFile.GetFileFromPathAsync(maskImagePath);
var tempFolder = ApplicationData.Current.TemporaryFolder;
var tempMaskFile = await maskFile.CopyAsync(tempFolder, maskFile.Name, NameCollisionOption.ReplaceExisting);
using var maskImage = Image.Load<Rgba32>(tempMaskFile.Path);
// Ensure that the source image and mask image have the same dimensions
var width = Math.Min(sourceImage.Width, maskImage.Width);
var height = Math.Min(sourceImage.Height, maskImage.Height);
// Iterate over each pixel and apply the mask
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
// Verify that the coordinates are within the valid range
if (x >= sourceImage.Width || y >= sourceImage.Height || x >= maskImage.Width || y >= maskImage.Height) continue;
var maskPixel = maskImage[x, y];
// Set the alpha channel of the output image based on the mask
outputImage[x, y] = new Rgba32(sourceImage[x, y].R, sourceImage[x, y].G, sourceImage[x, y].B, maskPixel.A);
}
}
// Save the output image to a file with a transparent background
var outputImagePath = Path.Combine(tempFolder.Path, "output.png");
await outputImage.SaveAsync(outputImagePath);
return outputImagePath;
}