2013-09-29 182 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