資源簡介
網上有很多BMP轉Texture2d的代碼,但是大多都不能用?。。∵@個腳本是通過讀取BMP文件的字節流解析協議直接將BMP從Byte[]解析出來的算法,是解析BMP的算法,根據這個算法可以在所有平臺上解析.BMP格式的圖片。
代碼片段和文件信息
using?System.Collections;
using?System.Collections.Generic;
using?System.Drawing;
using?System.IO;
using?UnityEngine;
using?UnityEngine.UI;
public?class?Test?:?MonoBehaviour
{
????public?RawImage?outputImg;
????byte[]?file?=?null;
????private?void?Start()
????{
????????Texture2D?t?=?ReadBmp();
????????outputImg.rectTransform.sizeDelta?=?new?Vector2(t.width?t.height);
????????outputImg.texture?=?t;
????}
????public?Texture2D?ReadBmp()
????{
????????
????????file?=?File.ReadAllBytes(“請將該路徑修改為自己BMP圖片的絕對路徑“);
????????tagBITMAPFILEHEADER?file_header?=?new?tagBITMAPFILEHEADER();
????????file_header.bfType?=?System.Text.Encoding.Default.GetString(file?0?2);
????????file_header.bfSize?=?_4ByteToInt(0x0002);
????????file_header.bfReserved1?=?_2ByteToInt(0x0006);
????????file_header.bfReserved2?=?_2ByteToInt(0x0008);
????????file_header.bfOffBits?=?_4ByteToInt(0x000A);
????????tagBMP_INFOHEADER?info_header?=?new?tagBMP_INFOHEADER();
????????info_header.biSize?=?_4ByteToInt(0x000E);
????????info_header.biWidth?=?_4ByteToInt(0x0012);
????????info_header.biHeight?=?_4ByteToInt(0x0016);
????????info_header.biPlanes?=?_2ByteToInt(0x001A);
????????info_header.biBitCount?=?_2ByteToInt(0x001C);
????????info_header.biCompression?=?_4ByteToInt(0x001E);
????????info_header.biSizeImage?=?_4ByteToInt(0x0022);
????????info_header.biXPelsPerMeter?=?_4ByteToInt(0x0026);
????????info_header.biYPelsPerMeter?=?_4ByteToInt(0x002A);
????????info_header.biClrUsed?=?_4ByteToInt(0x002E);
????????info_header.biClrImportant?=?_4ByteToInt(0x0032);
????????if?(info_header.biBitCount?!=?24)
????????{
????????????Debug.LogError(“本範例只能讀取?24?bit?寬度的圖像。:“?+?info_header.biBitCount);
????????????return?null;
????????}
????????Texture2D?t?=?new?Texture2D(info_header.biWidth?info_header.biHeight);
????????//?skip?:?微軟規定圖片寬度?/?4?必須?等於?0
????????//?如果寬度無法整除?4?,那麼必須要補?0
????????int?skip?=?0;
????????if?(t.width?*?3?%?4?!=?0)
????????{
????????????skip?=?4?-?(t.width?*?3?%?4);
????????}
????????int?i?=?0;
????????for?(int?y?=?0;?y?????????{
????????????for?(int?x?=?0;?x?????????
評論
共有 條評論