图像未使用WinJS进行缩放

时间:2013-11-02 22:34:12

标签: javascript windows-runtime winjs image-scaling

我正在尝试使用WinRT将现有图像缩放到其大小的50%。 它将图像复制到本地文件夹,但不会更改其大小;

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
    });
});

1 个答案:

答案 0 :(得分:1)

您几乎拥有它 - 您缺少的一步是您需要将fileStream(在内存中)复制到流(连接到文件)。否则你只是抛弃那个编码(和调整大小)的内存流。基本上在flushAsync和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);

除了fileStream.close之外,还要记得调用stream.close。 (我建议在代码中使用memStream和fileStream而不是fileStream和stream。)

有关完全可操作的示例,请参阅Simple Imaging sample in the SDK的方案2。