Alireza Noori
Alireza Noori

Reputation: 15253

Rotating images in WinRT

I have a Windows 8 app in which I want to rotate an image file.

In shot, I want to open an image file, rotate it and save the content back to the file.

Is that possible in WinRT? If so, how? Thanks.

Update:

Base on Vasile's answer, I could do some work on this. However I'm not sure what to do next:

    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?
    }

Upvotes: 0

Views: 1098

Answers (2)

Farhan Ghumra
Farhan Ghumra

Reputation: 15296

Use this to save WriteableBitmap to 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;
    }
}

Upvotes: 0

VasileF
VasileF

Reputation: 2916

Ofcourse it is possible. You can do it yourself with a pixel manipulation and create a new WriteableBitmapObject or, you could reuse the already implemented functionality from the WriteableBitmapEx (WriteableBitmap Extensions). You can get it via NuGet.

Here you can find a description of the implemented functionality which it offers, and few short samples.

Upvotes: 1

Related Questions