2013-11-02 45 views
0

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

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

你几乎有它 - 一步法你缺少的是你需要的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); 

还记得打电话stream.close除了fileStream.close。 (我推荐使用memStream和fileStream代替文件流和流,以便在您的代码中清除。)

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