![](/img/trans.png)
[英]How to save SoftwareBitmap object to bmp file C#, UWP
[英]UWP / C# Rotating BMP
這個問題似乎已經被問到了,但是我找不到相關的答案。
我正在將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);
}
}
RotateTransform與xaml一起使用
如您所知, RotateTransform
用於uwp應用XAML中的旋轉變換。 RotateTransform
由一個角度定義,該角度使對象繞RotateTransform
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
屬性對文件進行編碼。 代碼如下:
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提供了有關圖像旋轉的完整示例,您可以參考該圖像旋轉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.