1

我正在尝试在我的应用程序中实现从剪贴板功能上传图像,代码如下:

var clipboard = Windows.ApplicationModel.DataTransfer.Clipboard.getContent();

            if (clipboard.contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.bitmap)) {
                clipboard.getBitmapAsync().done(function (stream) {
                    stream.openReadAsync().then(function (bitmapStream) {
                       //TODO
                    });

                });

                return;
            }

作品,我可以上传它,但只能作为位图。我想要实现的是将图像上传为 jpeg。我知道我可以使用画布元素将位图转换为 jpeg,但是还有其他方法吗?也许来自http://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging的东西?

4

1 回答 1

1

经过几次试验,我找到了解决方案,代码如下。不漂亮但有效,将位图从剪贴板转换为 png/jpeg,并将文件上传到服务器(这里几乎没有 ajax 请求)。希望它会帮助有类似问题的人。

if (clipboard.contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.bitmap)) {
    clipboard.getBitmapAsync().done(function(bitmap) {
        bitmap.openReadAsync().then(function(bitmapStream) {
            Windows.Graphics.Imaging.BitmapDecoder.createAsync(bitmapStream).then(function(decoder) {
                decoder.getPixelDataAsync().then(function(pixelDataProvider) {
                    var pixels = pixelDataProvider.detachPixelData();
                    var memoryStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();

                    Windows.Graphics.Imaging.BitmapEncoder.createAsync(Windows.Graphics.Imaging.BitmapEncoder.pngEncoderId, memoryStream).then(function(encoder) {
                        encoder.setPixelData(decoder.bitmapPixelFormat, Windows.Graphics.Imaging.BitmapAlphaMode.ignore,
                                            decoder.orientedPixelWidth, decoder.orientedPixelHeight, decoder.dpiX, decoder.dpiY, pixels);

                        encoder.flushAsync().then(function() {
                            var fileName = 'screenshot_' + moment().format('MMDDYYYY_HHmm') + '.png';
                            var imageblob = MSApp.createBlobFromRandomAccessStream('image/png', memoryStream);

                            var formData = new FormData();
                            formData.append('upload', imageblob, imageName);
                        });
                   });
                });
           });
         });
  });
}
于 2013-07-10T08:02:15.620 回答