2

在用 JS 编写的 Windows 8 Metro 应用程序中,我打开一个文件,获取流,使用“promise - .then”模式向其中写入一些图像数据。它工作正常 - 文件成功保存到文件系统,除了使用 BitmapEncoder 将流刷新到文件后,流仍然打开。IE; 在我终止应用程序之前,我无法访问该文件,但“流”变量超出了我可以参考的范围,因此我无法关闭()它。有没有可以与 C# using 语句相媲美的东西?

...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.
            };
4

1 回答 1

1

来自 Microsoft 的这个简单的图像样本可能会有所帮助。复制如下。

看起来,在你的情况下,你需要在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; 
    }); 
} 
于 2012-04-20T14:04:28.523 回答