Windows 8 在WinJS Metro应用程序中使用BitmapEncoder后关闭流
在一个用JS编写的Windows8Metro应用程序中,我打开一个文件,获取流,使用“promise-.then”模式向其中写入一些图像数据。它工作正常-文件已成功保存到文件系统,除非在使用BitmapEncoder将流刷新到文件后,流仍处于打开状态。ie;在关闭应用程序之前,我无法访问该文件,但“stream”变量超出了我引用的范围,因此我无法关闭它。有什么东西可以与C#using语句相媲美吗Windows 8 在WinJS Metro应用程序中使用BitmapEncoder后关闭流,windows-8,microsoft-metro,winjs,Windows 8,Microsoft Metro,Winjs,在一个用JS编写的Windows8Metro应用程序中,我打开一个文件,获取流,使用“promise-.then”模式向其中写入一些图像数据。它工作正常-文件已成功保存到文件系统,除非在使用BitmapEncoder将流刷新到文件后,流仍处于打开状态。ie;在关闭应用程序之前,我无法访问该文件,但“stream”变量超出了我引用的范围,因此我无法关闭它。有什么东西可以与C#using语句相媲美吗 ...then(function (file) { return f
...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.
};
来自微软的这个可能会有所帮助。抄袭如下
看起来,在您的情况下,您需要在then
调用链之前声明流,确保您的名称与接受流的函数的参数不冲突(注意它们执行的部分\u 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;
});
}
似乎如果在第1个或第2个
中的任何地方抛出了错误,则会使流关闭代码无法执行。最后一个then
应该有错误处理程序,它也会关闭流。