23.01.2018 Views

MICROSOFT_PRESS_EBOOK_PROGRAMMING_WINDOWS_8_APPS_WITH_HTML_CSS_AND_JAVASCRIPT_PDF

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

function saveGrayscale() {<br />

var picker = new Windows.Storage.Pickers.FileSavePicker();<br />

picker.suggestedStartLocation =<br />

Windows.Storage.Pickers.PickerLocationId.picturesLibrary;<br />

picker.suggestedFileName = imageFile.name + " - grayscale";<br />

picker.fileTypeChoices.insert("PNG file", [".png"]);<br />

var imgData, fileStream = null;<br />

picker.pickSaveFileAsync().then(function (file) {<br />

if (file) {<br />

return file.openAsync(Windows.Storage.FileAccessMode.readWrite);<br />

} else {<br />

return WinJS.Promise.wrapError("No file selected");<br />

}<br />

}).then(function (stream) {<br />

fileStream = stream;<br />

var canvas = document.getElementById("canvas1");<br />

var ctx = canvas.getContext("2d");<br />

imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);<br />

return Imaging.BitmapEncoder.createAsync(<br />

Imaging.BitmapEncoder.pngEncoderId, stream);<br />

}).then(function (encoder) {<br />

//Set the pixel data--assume "encoding" object has options from elsewhere.<br />

//Conversion from canvas data to Uint8Array is necessary because the array type<br />

//from the canvas doesn't match what WinRT needs here.<br />

encoder.setPixelData(encoding.pixelFormat, encoding.alphaMode,<br />

encoding.width, encoding.height, encoding.dpiX, encoding.dpiY,<br />

new Uint8Array(imgData.data));<br />

}<br />

//Go do the encoding<br />

return encoder.flushAsync();<br />

}).done(function () {<br />

fileStream.close();<br />

}, function () {<br />

//Empty error handler (do nothing if the user canceled the picker)<br />

});<br />

Note how the BitmapEncoder takes a codec identifier in its first parameter. We’re using pngEncoderId,<br />

which is, as you can see, defined as a static property of the Windows.Graphics.Imaging.BitmapEncoder<br />

class; other values are bmpEncoderId, gifEncoderId, jpegEncoderId, jpegXREncoderId, and<br />

tiffEncoderId. These are the formats supported by the API. You can set additional properties of the<br />

BitmapEncoder before setting pixel data, such as its BitmapTransform, which will then be applied during<br />

encoding.<br />

One gotcha to be aware of here is that the pixel array obtained from a canvas element (a DOM<br />

CanvasPixelArray) is not directly compatible with the WinRT byte array required by the encoder. This<br />

is the reason for the new Uint8Array call down there in the last parameter.<br />

446

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!