using System; using System.Collections.Generic; namespace Neatly.UI { public static class ImageHeader { delegate Size DelegateVector(byte[] bytes); public struct Size { public static readonly Size zero = new Size(0,0); public int width; public int height; public Size(int width, int height) { this.width = width; this.height = height; } } private struct ParseItem { private byte[] m_Head; private DelegateVector m_Action; public ParseItem(byte[] bytes, DelegateVector action) { this.m_Head = bytes; this.m_Action = action; } public bool IsRightTexture(byte[] sourceByte) { if (sourceByte.Length < m_Head.Length) { return false; } for (int i = 0; i < m_Head.Length; i++) { if (sourceByte[i] != m_Head[i]) { return false; } } return true; } public Size GetSize(byte[] sourceByte) { return m_Action(sourceByte); } } public static Size GetSize(byte[] sourceByte) { try { for (int i = 0; i < m_ParseList.Count; i++) { return m_ParseList[i].IsRightTexture(sourceByte) ? m_ParseList[i].GetSize(sourceByte) : Size.zero; } } catch (Exception e) { return Size.zero; } return Size.zero; } private static List m_ParseList = new List { new ParseItem(new byte[] {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}, GetPngSize), //Png }; //Png 尺寸解析 private static Size GetPngSize(byte[] bytes) { int sizeIndex = 16; int width = bytes[sizeIndex] << 24 | bytes[sizeIndex + 1] << 16 | bytes[sizeIndex + 2] << 8 | bytes[sizeIndex + 3]; int height = bytes[sizeIndex + 4] << 24 | bytes[sizeIndex + 5] << 16 | bytes[sizeIndex + 6] << 8 | bytes[sizeIndex + 7]; return new Size(width, height); } } }