javascript - UWP - 将 png 保存为 jpg,我希望透明度变为白色
问题描述
我在这里问了一个关于将画布保存为 png 的问题。当我保存到 png 时效果很好,除了问题:背景是透明的,我希望它是白色的。
我的第一个想法是尝试使用 JPG 编码,它会自动添加背景——我是对的!但它在其中添加了黑色背景。
现在不幸的是,我似乎无法控制画布的制作,所以我不能只为其添加白色背景。我在画布上查找了文档,显然不能在它的背景中添加白色 - 如果我可以在画布上添加白色背景,请告诉我,因为这将解决我的问题。
因此,唯一的其他解决方案是以某种方式从下面的代码中获取我的 PNG 编码流,并用白色替换透明度。如果可以在 png 而不是 jpg 中完成,我很好。如果只能在 jpg 上完成,我也可以。在此图像上获得白色背景的任何解决方案。
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
});
}
解决方案
推荐阅读
- if-statement - IF 结果不同于 IFS 结果在 Google 表格中
- hibernate-search - 休眠搜索:持久化新实体后索引损坏
- python - 如何将多个 tar.gz 文件提取到一个目录中?
- php - 如何获取多个键的值?
- sql - 如何使用sql从同一级别的所有xml元素中选择一个属性
- python - OpenCV 或 PyTesseract 可以识别字体吗
- mysql - 如何使用项目 ID 修复 ORDER BY?
- sql - 为什么 Google Analytics 和 BigQuery 之间的独特事件差异如此之大?
- c# - 将盒装类型评估为 C# 中的类型
- html - 角度插值可以在 HTML src 标签内工作吗?