gpt4 book ai didi

c# - UWP/C# 旋转 BMP

转载 作者:行者123 更新时间:2023-12-04 01:31:08 28 4
gpt4 key购买 nike

这个问题好像已经有人问过了,但是我找不到相关的答案。

我正在将 BMP 图像加载到 UWP 应用程序的内存中,我想将其旋转 90、180 或 270,但我就是找不到执行此操作的方法。

imgSource.rotate() 似乎不存在了RotateTransform 适用于 xaml....

有没有人可以偶然添加缺少的代码?

public async Task LoadImage()
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("test.bmp");
using (var stream = await file.OpenAsync(FileAccessMode.Read))
{
var decoder = await BitmapDecoder.CreateAsync(stream);
bitmap = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
var imgSource = new WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight);

// Code to rotate image by 180 to be added

bitmap.CopyToBuffer(imgSource.PixelBuffer);
}
}

最佳答案

The RotateTransform works with xaml

如您所知,RotateTransform用于 uwp 应用程序 XAML 中的旋转变换。 RotateTransformAngle 定义通过围绕点 CenterX、CenterY 的圆弧旋转对象。但是转换通常用于填充 UIElement.RenderTransform属性,因此如果您将图像源加载到 ImageControl ,您可以旋转 ImageControl,因为它是一个 UIElement。例如,如果我们有如下 ImageControl:

<Image x:Name="PreviewImage" Height="400" Width="300" AutomationProperties.Name="Preview of the image"  Stretch="Uniform" HorizontalAlignment="Center" VerticalAlignment="Center"/> 

我们可以通过代码简单地通过angle属性旋转它:

RotateTransform m_transform = new RotateTransform(); 
PreviewImage.RenderTransform = m_transform;
m_transform.Angle = 180;

如果您需要旋转图像文件而不是 UIElement,您可能需要像您已经执行的那样解码图像文件,然后通过设置 BitmapTransform.Rotation 对文件进行编码。属性(property)。代码如下:

  double m_scaleFactor;
private async void btnrotatefile_Click(object sender, RoutedEventArgs e)
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("test.bmp");
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite),
memStream = new InMemoryRandomAccessStream())
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
uint originalWidth = decoder.PixelWidth;
uint originalHeight = decoder.PixelHeight;
BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memStream, decoder);
if (m_scaleFactor != 1.0)
{
encoder.BitmapTransform.ScaledWidth = (uint)(originalWidth * m_scaleFactor);
encoder.BitmapTransform.ScaledHeight = (uint)(originalHeight * m_scaleFactor);
encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
}

//Rotate 180
encoder.BitmapTransform.Rotation = BitmapRotation.Clockwise180Degrees;
await encoder.FlushAsync();
memStream.Seek(0);
fileStream.Seek(0);
fileStream.Size = 0;
await RandomAccessStream.CopyAsync(memStream, fileStream);
}
}

有关图像文件旋转的更多功能,您可以使用 Windows.Graphics.Imaging 下的其他 APIS命名空间。和SimpleImaging 的场景2官方示例提供了完整的图像旋转示例,您可以引用。

关于c# - UWP/C# 旋转 BMP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42057997/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com