2020年5月8日 星期五

把Base64 轉成 Byte Array 後儲存為圖檔

專案需要將撈出來的HTML頁面產生PDF...慢慢刻太花時間外加CSS很容易跑掉,乾脆轉圖檔儲存,但用html2canvas轉完後是base64,只好轉存成byte再save圖檔給PDF用...紀錄一下參考的base64 to byte文章
 
HTML Markup
The following HTML Markup consists of an ASP.Net FileUpload control to upload the Image File and a Button control to trigger the File upload process.
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
    onclick="btnUpload_Click" />
</form>
 
 
Convert Base64 string to Byte Array using C# and VB.Net
When the Upload button is clicked, the Image file is read into a Byte Array using the BinaryReader class object.
The Byte Array is then converted into Base64 encoded string using the Convert.ToBase64String method.
Now in order to save the Base64 encoded string as Image File, the Base64 encoded string is converted back to Byte Array using the Convert.FromBase64String function.
Finally the Byte Array is saved to Folder on Disk as File using WriteAllBytes method of the File class.
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
    //***Convert Image File to Base64 Encoded string***//
 
    //Read the uploaded file using BinaryReader and convert it to Byte Array.
    BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream);
    byte[] bytes = br.ReadBytes((int)FileUpload1.PostedFile.InputStream.Length);
 
    //Convert the Byte Array to Base64 Encoded string.
    string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
 
    //***Save Base64 Encoded string as Image File***//
 
    //Convert Base64 Encoded string to Byte Array.
    byte[] imageBytes = Convert.FromBase64String(base64String);
       
    //Save the Byte Array as Image File.
    string filePath = Server.MapPath("~/Files/" + Path.GetFileName(FileUpload1.PostedFile.FileName));
    File.WriteAllBytes(filePath, imageBytes);
}
 
VB.Net
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
    '***Convert Image File to Base64 Encoded string***
 
    'Read the uploaded file using BinaryReader and convert it to Byte Array.
    Dim br As New BinaryReader(FileUpload1.PostedFile.InputStream)
    Dim bytes As Byte() = br.ReadBytes(CInt(FileUpload1.PostedFile.InputStream.Length))
 
    'Convert the Byte Array to Base64 Encoded string.
    Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
 
    '***Save Base64 Encoded string as Image File***
 
    'Convert Base64 Encoded string to Byte Array.
    Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
 
    'Save the Byte Array as Image File.
    Dim filePath As String = Server.MapPath("~/Files/" + Path.GetFileName(FileUpload1.PostedFile.FileName))
    File.WriteAllBytes(filePath, imageBytes)
End Sub
 

1 則留言: