Pregunta

I am trying to scale an existing image to 50% of its size using WinRT. It copies the image to the local folder, but doesn't change its size;

var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
    openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
    openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
    openPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);

    openPicker.pickSingleFileAsync().then(function (file) {
        file.copyAsync(Windows.Storage.ApplicationData.current.localFolder, file.name)
        .then(function (file) {
            return file.openAsync(Windows.Storage.FileAccessMode.readWrite);
        })
        .then(function (stream) {
            return Windows.Graphics.Imaging.BitmapDecoder.createAsync(stream);
        })
        .then(function (decoder) {
            fileStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            return Windows.Graphics.Imaging.BitmapEncoder.createForTranscodingAsync(fileStream, decoder);
        })
    .then(function (encoder) {
        encoder.bitmapTransform.scaledWidth = 50;
        encoder.bitmapTransform.scaledHeight = 50;
        return encoder.flushAsync();
    })
    .then(function () {
        fileStream.close();
    })
    .done(function () {
        // use image in the program
    });
});
¿Fue útil?

Solución

You almost have it--the one step you're missing is that you need to copy the fileStream (which is in memory) to the stream (connected to the file). Otherwise you're just throwing that encoded (and resized) memory stream away. Basically stick something like this between the flushAsync and the fileStream.close:

}).then(function () {
    // Overwrite the contents of the file with the updated image stream.
    fileStream.seek(0);
    stream.seek(0);
    stream.size = 0;
    return Windows.Storage.Streams.RandomAccessStream.copyAsync(fileStream, stream);

Also remember to call stream.close in addition to fileStream.close. (I recommend using memStream and fileStream instead of fileStream and stream to be clear in your code.)

For a fully operational example, refer to scenario 2 of the Simple Imaging sample in the SDK.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top