Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

javascript - How to save html5 canvas as an image file in window 8 metro app?

var myImage = canvas.toDataURL("image/png");

I think myImage has the image bytes encoded in png format now how to save myImage as a file (in images folder)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of using .toDataUrl, you need to use .msToBlob:

var blob = canvas.msToBlob();

Then, you'll need to write this out to disk:

var output;
var input;
var outputStream;

Windows.Storage.ApplicationData.current.localFolder.createFileAsync("yourFile", 
          Windows.Storage.CreationCollisionOption.replaceExisting).
    then(function(file) {
        return file.openAsync(Windows.Storage.FileAccessMode.readWrite);
    }).then(function(stream) {
        outputStream = stream;
        output = stream.getOutputStreamAt(0);
        input = blob.msDetachStream();
        return Windows.Storage.Streams.RandomAccessStream.copyAsync(input, output);
    }).then(function() {
        return output.flushAsync();
    }).done(function() {
        input.close();
        output.close();
        outputStream.close();
    });

In your applications app data folder, you will now have the image written to disk.

If you wish to place it somewhere else -- e.g. my pictures etc -- then you'll just need to use one of the other storage folders. See the sample here. Note that to access the pictures library you need to add that capability to your manifest (just a checkbox in the package.appxmanifest editor in VS)

There are many other imaging options too for more complex manipulation of the output file. See the imaging sample for code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...