2013-09-29 140 views
1

我将画布转换为图像,现在我想将图像保存到磁盘。 我的问题是: 我可以保存或下载图像到用户磁盘? 我使用WinJS - JavaScript用WinJS将图像保存到磁盘

+0

可以,但需要用户交互来选择文件位置:http://msdn.microsoft.com/en-us/library/windows/apps /jj150595.aspx – David

回答

3

绝对如此。由于发表了的Kraig几乎同样的问题在social.msdn.com: Saving a Canvas as an image in Windows 8


var Imaging = Windows.Graphics.Imaging; 
var picker = new Windows.Storage.Pickers.FileSavePicker(); 
picker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary; 
picker.fileTypeChoices.insert("PNG file", [".png"]); 
var imgData, fileStream = null; 
picker.pickSaveFileAsync().then(function (file) {    
    if (file) { 
     return file.openAsync(Windows.Storage.FileAccessMode.readWrite);     
    } else { 
     return WinJS.Promise.wrapError("No file selected"); 
    } 
}).then(function (stream) { 
    fileStream = stream; 
    var canvas = document.getElementById("canvas1");    
    var ctx = canvas.getContext("2d"); 
    imgData = ctx.getImageData(0, 0, canvas.width, canvas.height); 

    return Imaging.BitmapEncoder.createAsync(Imaging.BitmapEncoder.pngEncoderId, stream); 
}).then(function (encoder) { 
    //Set the pixel data--assume "encoding" object has options from elsewhere 
    encoder.setPixelData(encoding.pixelFormat, encoding.alphaMode, 
     encoding.width, encoding.height, encoding.dpiX, encoding.dpiY, 
     new Uint8Array(imgData.data)); 
    //Go do the encoding 
    return encoder.flushAsync(); 
}).done(function() { 
    //Make sure to do this at the end 
    fileStream.close(); 
}, function() { 
    //Empty error handler (do nothing if the user canceled the picker 
}); 
+0

Wichi像素格式应该在“encoder.setPixelData”函数中使用吗? – Piotrek