在 UWP 中将画布另存为图像 [英] Saving a Canvas as an image in UWP

查看:27
本文介绍了在 UWP 中将画布另存为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 本文档 用于将画布导出和保存为 png.它给出了以下代码:

I found this documentation for exporting and saving a Canvas as a png. It gives the following code:

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
});

在encoder.setPixelData"区域中,他们使用一个名为encoding"的对象来设置所有值,但没有说明在前面的任何步骤中如何创建该对象.

In the 'encoder.setPixelData' area, they use an object called 'encoding' to set all the values, but have no explanation of how this object is created in any of the prior steps.

如何创建这个编码"对象来完成示例?

How can I create this 'encoding' object to complete the example?

推荐答案

我找到了另一种保存画布的方法,仍然没有解决我最初的问题

I found a different way to save the canvas, still didn't solve my initial problem

我可以将画布转换为 blob 流并将其保存为 png 文件

I can turn the canvas into a blob stream and save that to a png file

function saveCanvasAsImage(canvasElement) {
    var picker = new Windows.Storage.Pickers.FileSavePicker();
    picker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
    picker.fileTypeChoices.insert("PNG file", [".png"]);

    var input, output = null;
    var blob = canvasElement.msToBlob();

    return picker.pickSaveFileAsync()
        .then(function (file) {
            if (file) {
                return file.openAsync(Windows.Storage.FileAccessMode.readWrite);
            } else {
                return WinJS.Promise.wrapError("No file selected");
            }
        })
        .then(function (op) {
            output = op;
            input = blob.msDetachStream();

            return Windows.Storage.Streams.RandomAccessStream.copyAsync(input, output);
        })
        .then(function() {
            return output.flushAsync();
        })
        .done(function() {
            input.close();
            output.close();
        }, function(e) {
            // handle error here
        });
}

不幸的是,它使用透明背景保存,但也许有一种方法可以让我的画布具有白色背景.

Unfortunately it's saving with a transparent background, but maybe there's a way I can make my canvas have a white background.

----

所以我找到了一种更直接地回答我原来问题的方法:

So I found a way to answer my original question more directly:

function saveCanvasAsImage(canvasElement) {
    var Imaging = Windows.Graphics.Imaging;
    var picker = new Windows.Storage.Pickers.FileSavePicker();
    picker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
    // picker.fileTypeChoices.insert("JPEG file", [".jpg"]);
    picker.fileTypeChoices.insert("PNG file", [".png"]);
    var fileStream, decoder, encoding, pixels = null;


    var encoderIds = {
        '.png': Imaging.BitmapEncoder.pngEncoderId,
        '.jpg': Imaging.BitmapEncoder.jpegEncoderId
    }

    var encoderId = encoderIds['.jpg'];

    var blob = canvasElement.msToBlob();

    return Imaging.BitmapDecoder.createAsync(Imaging.BitmapDecoder.pngDecoderId,
            blob.msDetachStream())
        .then(function (dc) {
            decoder = dc;

            return picker.pickSaveFileAsync();
        }).then(function (file) {
            if (file) {
                encoderId = encoderIds[file.fileType];
                return file.openAsync(Windows.Storage.FileAccessMode.readWrite);
            } else {
                return WinJS.Promise.wrapError("No file selected");
            }
        }).then(function(stream) {
            fileStream = stream;

            var transform = new Windows.Graphics.Imaging.BitmapTransform();

            return decoder.getPixelDataAsync(
                decoder.bitmapPixelFormat,
                decoder.bitmapAlphaMode,
                transform,
                Windows.Graphics.Imaging.ExifOrientationMode.respectExifOrientation,
                Windows.Graphics.Imaging.ColorManagementMode.colorManageToSRgb
            );

        }).then(function (pixelProvider) {

            pixels = pixelProvider.detachPixelData();

            return Imaging.BitmapEncoder.createAsync(encoderId, fileStream);
        }).then(function (encoder) {
            encoding = decoder;
            //Set the pixel data--assume "encoding" object has options from elsewhere
            encoder.setPixelData(encoding.bitmapPixelFormat, encoding.bitmapAlphaMode,
                encoding.pixelWidth, encoding.pixelHeight, encoding.dpiX, encoding.dpiY,
                pixels);
            //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
        });
}

我已经注释掉了另存为 JPG 的功能,因为这是一个新问题,但这适用于 png

I've commented out the ability to save as JPG because that's a new problem, but this works for pngs

这篇关于在 UWP 中将画布另存为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆