I am trying to write a method that takes image data in base64 string and saves it into a binary file while preserving transparency (for example in case of PNGs).
My other requirement is that this needs to be done in C# in PCL (Portable Class Library).
I know that you can use Image or WriteableBitmap to solve this issue but such classes are not available in PCL.
I have the following method that does the job of taking the base64 data and saving it to a file:
public static async Task Base64ToBinaryImageFile(IFile file, string base64Content)
{
var bytes = Convert.FromBase64String(base64Content);
using (var stream = await file.OpenAsync(FileAccess.ReadAndWrite))
{
stream.Seek(0, SeekOrigin.Begin);
using (var writer = new BinaryWriter(stream))
{
writer.Write(content);
writer.Flush();
}
}
}
It works fine except that:
I lose the transparency data (so transparent pixels show up as black).
The file that is created using this method has a larger size (in bytes) than the original file.
Any idea on what's the cause and how to fix these issues?
Update: Here is the JavaScript code that sends the base64 data to C#:
function onPaste(event) {
var $event = event.data.$;
var clipboardData = $event.clipboardData;
var found = false;
var imageType = /^image/;
if (!clipboardData) {
return false;
}
return Array.prototype.forEach.call(clipboardData.types, function (type, i) {
if (found) {
return false;
}
if (type.match(imageType) || clipboardData.items[i].type.match(imageType)) {
readImageAsBase64(clipboardData.items[i]);
return found = true;
}
return false;
});
}
function readImageAsBase64(item) {
if (!item || typeof item.getAsFile !== "function") {
return;
}
var file = item.getAsFile();
var reader = new FileReader();
reader.onload = function (evt) {
window.external.notify("pasteImageBase64/" + evt.target.result);
};
reader.readAsDataURL(file);
}