裁剪图像通用应用程序 c#
Posted
技术标签:
【中文标题】裁剪图像通用应用程序 c#【英文标题】:cropping image universal app c# 【发布时间】:2015-04-13 11:29:10 【问题描述】:我想在通用应用程序中用 x 和 y 裁剪图像, 我搜索了很多,没有发现任何有用的东西 我的想法是 我有一张图片,我想根据 start x , y - end x 和 y 裁剪矩形
我试过了
BitmapImage img = new BitmapImage(new Uri(file.Path));
WriteableBitmap topLeft = img.Crop(0, 0, halfWidth, halfHeight);
它说 BitmapImage 不包含裁剪的定义
另一件事: 如何在通用应用程序中将 BitmapImage 转换为 WriteableBitmap ?
【问题讨论】:
【参考方案1】:您是否尝试过 BitmapEncoder/BitmapDecoder 类?查看MSDN code sample.
【讨论】:
【参考方案2】: /// <summary>
/// Gets the cropped bitmap asynchronously.
/// </summary>
/// <param name="originalImage">The original image.</param>
/// <param name="startPoint">The start point.</param>
/// <param name="cropSize">Size of the corp.</param>
/// <param name="scale">The scale.</param>
/// <returns>The cropped image.</returns>
public static async Task<WriteableBitmap> GetCroppedBitmapAsync(IRandomAccessStream originalImage,
Point startPoint, Size cropSize, double scale)
if (double.IsNaN(scale) || double.IsInfinity(scale))
scale = 1;
// Convert start point and size to integer.
var startPointX = (uint)Math.Floor(startPoint.X * scale);
var startPointY = (uint)Math.Floor(startPoint.Y * scale);
var height = (uint)Math.Floor(cropSize.Height * scale);
var width = (uint)Math.Floor(cropSize.Width * scale);
// Create a decoder from the stream. With the decoder, we can get
// the properties of the image.
var decoder = await BitmapDecoder.CreateAsync(originalImage);
// The scaledSize of original image.
var scaledWidth = (uint)Math.Floor(decoder.PixelWidth * scale);
var scaledHeight = (uint)Math.Floor(decoder.PixelHeight * scale);
// Refine the start point and the size.
if (startPointX + width > scaledWidth)
startPointX = scaledWidth - width;
if (startPointY + height > scaledHeight)
startPointY = scaledHeight - height;
// Get the cropped pixels.
var pixels = await GetPixelData(decoder, startPointX, startPointY, width, height,
scaledWidth, scaledHeight);
// Stream the bytes into a WriteableBitmap
var cropBmp = new WriteableBitmap((int)width, (int)height);
var pixStream = cropBmp.PixelBuffer.AsStream();
pixStream.Write(pixels, 0, (int)(width * height * 4));
return cropBmp;
【讨论】:
以上是关于裁剪图像通用应用程序 c#的主要内容,如果未能解决你的问题,请参考以下文章
使用 c# 在 Windows Store App 中裁剪和保存图像(UIElement)