C# - save base64 string to image file without losing transparency
<p>I am trying to write a method that takes image data in base64 string and saves it into a binary file <strong>while preserving transparency (for example in case of PNGs)</strong>.</p>

<p>My other requirement is that this needs to be done in C# in PCL (Portable Class Library).</p>

<p>I know that you can use Image or WriteableBitmap to solve this issue but such classes are not available in PCL.</p>

<p>I have the following method that does the job of taking the base64 data and saving it to a file:</p>

<pre><code>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();
        }
    }
}
</code></pre>

<p>It works fine except that:</p>

<ol>
<li><p>I lose the transparency data (so transparent pixels show up as black).</p></li>
<li><p>The file that is created using this method has a larger size (in bytes) than the original file.</p></li>
</ol>

<p>Any idea on what's the cause and how to fix these issues?</p>

<hr>

<p>Update: Here is the JavaScript code that sends the base64 data to C#:</p>

<pre><code>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);
}
</code></pre>