C#将Color32[]转到byte[]及其反转
public static byte[] Color32ArrayToByteArray(Color32[] colors)
{
if (colors == null || colors.Length == 0)
return null;
int lengthOfColor32 = Marshal.SizeOf(typeof(Color32));
int length = lengthOfColor32 * colors.Length;
byte[] bytes = new byte[length];
GCHandle handle = default(GCHandle);
try
{
handle = GCHandle.Alloc(colors, GCHandleType.Pinned);
IntPtr ptr = handle.AddrOfPinnedObject();
Marshal.Copy(ptr, bytes, 0, length);
}
finally
{
if (handle != default(GCHandle))
handle.Free();
}
return bytes;
}
public static byte[] ConvertColor32ArrayToByteArray(Color32[] colors)
{
if (colors == null || colors.Length == 0)
return null;
int lengthOfColor32 = Marshal.SizeOf(typeof(Color32));
int length = lengthOfColor32 * colors.Length;
byte[] bytes = new byte[length];
GCHandle handle = default(GCHandle);
try
{
handle = GCHandle.Alloc(colors, GCHandleType.Pinned);
IntPtr ptr = handle.AddrOfPinnedObject();
Marshal.Copy(ptr, bytes, 0, length);
}
finally
{
if (handle != default(GCHandle))
handle.Free();
}
return bytes;
}
public static Color32[] ConvertByteArrayToColor32Array(byte[] bytes)
{
if (bytes == null || bytes.Length == 0)
return null;
int length = bytes.Length;
int lengthOfColor32 = Marshal.SizeOf(typeof(Color32));
Color32[] colors = new Color32[length / lengthOfColor32];
GCHandle handle = default(GCHandle);
try
{
handle = GCHandle.Alloc(colors, GCHandleType.Pinned);
IntPtr ptr = handle.AddrOfPinnedObject();
Marshal.Copy(bytes, 0, ptr, length);
}
finally
{
if (handle != default(GCHandle))
handle.Free();
}
return colors;
}
本文来自博客园,作者:艾孜尔江,转载请注明原文链接:https://www.cnblogs.com/ezhar/p/13651274.html