在WinRT中旋转图像

时间:2013-09-17 10:20:11

标签: c# windows-8 windows-runtime microsoft-metro winrt-xaml

我有一个Windows 8应用程序,我想在其中旋转图像文件。

在镜头中,我想打开一个图像文件,旋转它并将内容保存回文件。

WinRT可以吗?如果是这样,怎么样?感谢。

更新

根据Vasile的回答,我可以做一些工作。但是我不确定下一步该做什么:

    public static async Task RotateImage(StorageFile file)
    {
        if (file == null)
            return;

        var data = await FileIO.ReadBufferAsync(file);

        // create a stream from the file
        var ms = new InMemoryRandomAccessStream();
        var dw = new DataWriter(ms);
        dw.WriteBuffer(data);
        await dw.StoreAsync();
        ms.Seek(0);

        // find out how big the image is, don't need this if you already know
        var bm = new BitmapImage();
        await bm.SetSourceAsync(ms);

        // create a writable bitmap of the right size
        var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight);
        ms.Seek(0);

        // load the writable bitpamp from the stream
        await wb.SetSourceAsync(ms);
        wb.Rotate(90);

        //How should I save the image to the file now?
    }

2 个答案:

答案 0 :(得分:1)

当然有可能。您可以使用像素操作自行完成并创建新的WriteableBitmap对象,或者可以重用WriteableBitmapEx(WriteableBitmap Extensions)中已实现的功能。您可以通过NuGet

获取

Here您可以找到它提供的已实现功能的描述,以及一些简短的样本。

答案 1 :(得分:0)

使用此功能将WriteableBitmap保存到StorageFile

private async Task<StorageFile> WriteableBitmapToStorageFile(WriteableBitmap writeableBitmap)
{
    var picker = new FileSavePicker();
    picker.FileTypeChoices.Add("JPEG Image", new string[] { ".jpg" });
    StorageFile file = await picker.PickSaveFileAsync();
    if (file != null && writeableBitmap != null)
    {
        using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(
                BitmapEncoder.JpegEncoderId, stream);
            Stream pixelStream = writeableBitmap.PixelBuffer.AsStream();
            byte[] pixels = new byte[pixelStream.Length];
            await pixelStream.ReadAsync(pixels, 0, pixels.Length);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, 96.0, 96.0, pixels);
            await encoder.FlushAsync();
        }
        return file;
    }
    else
    {
        return null;
    }
}