2012-04-19 54 views
2

在用JS编写的Windows 8 Metro应用程序中,我打开一个文件,获取流,使用'promise - .then'模式向其中写入一些图像数据。它工作正常 - 文件已成功保存到文件系统,除了在使用BitmapEncoder刷新文件流之后,流仍处于打开状态。即;在我杀死应用程序之前我无法访问该文件,但'流'变量超出了我的引用范围,所以我无法关闭它()。是否有可与C#使用语句相媲美的东西?在WinJS Metro应用程序中使用BitmapEncoder后关闭流

...then(function (file) { 
       return file.openAsync(Windows.Storage.FileAccessMode.readWrite); 
      }) 
.then(function (stream) { 
       //Create imageencoder object 
       return Imaging.BitmapEncoder.createAsync(Imaging.BitmapEncoder.pngEncoderId, stream); 
      }) 
.then(function (encoder) { 
       //Set the pixel data in the encoder ('canvasImage.data' is an existing image stream) 
       encoder.setPixelData(Imaging.BitmapPixelFormat.rgba8, Imaging.BitmapAlphaMode.straight, canvasImage.width, canvasImage.height, 96, 96, canvasImage.data); 
       //Go do the encoding 
       return encoder.flushAsync(); 
       //file saved successfully, 
       //but stream is still open and the stream variable is out of scope. 
      }; 

回答

1

来自Microsoft的simple imaging sample可能会对您有所帮助。下面复制。

在你的情况下,你需要在调用then调用链之前声明流,确保你的名字不会与你的参数碰撞到接受流的函数中(注意它们所在的部分_stream = stream),并添加一个then调用来关闭流。

function scenario2GetImageRotationAsync(file) { 
    var accessMode = Windows.Storage.FileAccessMode.read; 

    // Keep data in-scope across multiple asynchronous methods 
    var stream; 
    var exifRotation; 
    return file.openAsync(accessMode).then(function (_stream) { 
     stream = _stream; 
     return Imaging.BitmapDecoder.createAsync(stream); 
    }).then(function (decoder) { 
     // irrelevant stuff to this question 
    }).then(function() { 
     if (stream) { 
      stream.close(); 
     } 
     return exifRotation; 
    }); 
} 
+0

看来,如果在第一个或第二个'then>的任何地方抛出错误,它将使流关闭代码不执行。最后'then'应该有关闭流的错误处理程序。 – 2015-07-07 17:25:09