如何直接把檔案的 Binary data 給 HTMLImageElement
前言
最近需要把Texture的資料存成JSON,JSON裡存的是檔案的 Binary data (經過 Base64 編碼),但WebGL並不能直接透過檔案的 Binary data 來初始化,WebGL提供從 HTMLImageElement 來初始化 Texture ,所以需要用檔案的 Binary data 初始化 HTMLImageElement ,在此把學習的過程做個紀錄。內容
在之前的 將canvas的結果輸出到image 裡有使用"HTMLCanvasElement.toDataURL()"來初始化 HTMLImageElement ,如果打資料列印出來的話會得到以下data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAGTklEQVR4Xu3UAQ0AQAgDMfAvmk/exhUH68j2Zm4cAQJJgTUAyd6FJvAFDIBHIBAWMADh8kUnYAD8AIGwgAEIly86AQPgBwiEBQxAuHzRCRgAP0AgLGAAwuWLTsAA+AECYQEDEC5fdAIGwA8QCAsYgHD5ohMwAH6AQFjAAITLF52AAfADBMICBiBcvugEDIAfIBAWMADh8kUnYAD8AIGwgAEIly86AQPgBwiEBQxAuHzRCRgAP0AgLGAAwuWLTsAA+AECYQEDEC5fdAIGwA8QCAsYgHD5ohMwAH6AQFjAAITLF52AAfADBMICBiBcvugEDIAfIBAWMADh8kUnYAD8AIGwgAEIly86AQPgBwiEBQxAuHzRCRgAP0AgLGAAwuWLTsAA+AECYQEDEC5fdAIGwA8QCAsYgHD5ohMwAH6AQFjAAITLF52AAfADBMICBiBcvugEDIAfIBAWMADh8kUnYAD8AIGwgAEIly86AQPgBwiEBQxAuHzRCRgAP0AgLGAAwuWLTsAA+AECYQEDEC5fdAIGwA8QCAsYgHD5ohMwAH6AQFjAAITLF52AAfADBMICBiBcvugEDIAfIBAWMADh8kUnYAD8AIGwgAEIly86AQPgBwiEBQxAuHzRCRgAP0AgLGAAwuWLTsAA+AECYQEDEC5fdAIGwA8QCAsYgHD5ohMwAH6AQFjAAITLF52AAfADBMICBiBcvugEDIAfIBAWMADh8kUnYAD8AIGwgAEIly86AQPgBwiEBQxAuHzRCRgAP0A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ohMwAH6AQFjAAITLF52AAfADBMICBiBcvugEDIAfIBAWMADh8kUnYAD8AIGwgAEIly86AQPgBwiEBQxAuHzRCRgAP0AgLGAAwuWLTsAA+AECYQEDEC5fdAIGwA8QCAsYgHD5ohMwAH6AQFjAAITLF52AAfADBMICBiBcvugEDIAfIBAWMADh8kUnYAD8AIGwgAEIly86AQPgBwiEBQxAuHzRCRgAP0AgLGAAwuWLTsAA+AECYQEDEC5fdAIGwA8QCAsYgHD5ohMwAH6AQFjAAITLF53AA7XX/xBqKzAnAAAAAElFTkSuQmCC
這其實是一種資料格式稱為 MIME 類型,格式的類型如下
data:(MIME type);base64,(Base64 data)
會有變動只有 MIME type 與 Base64 data 這兩個地方, MIME type 表明的是資料格式,如PNG與BMP...等,詳細支援的格式可以參考 [MDN]MIME 类型 。Base64 data 就是被 Base64 編碼過的 Binary data ,為什麼 Binary data 要經過 Base64 編碼?因為單靠 String 沒辦法表達 Binary data , String 會有結束字元的問題,經過 Base64 編碼可以迴避結束字元的問題。
接下來就可以 MIME 類型的字串直接給 "HTMLImageElement.src",就像 將canvas的結果輸出到image 的範例一樣,這樣就完成 HTMLImageElement 的初始化,整體的流程如下圖
直接把檔案的 Binary data 給HTMLImageElement的流程 |
參考資料
[Wiki]網際網路媒體型式[MDN]MIME 类型
[Wiki]Base64
沒有留言:
張貼留言