public void Serialize(ref byte[] buffer, ref int offset, Bitmap img) { // Let the image serialize itself to the memory stream // Its unfortunate that there's only a stream-based api... // The alternative would be manually locking the bits. // That would be easy, but we'd potentially lose some information (animation frames etc?) // Prepare buffer stream if (_sharedMemoryStream == null) { _sharedMemoryStream = new MemoryStream(200 * 1024); } var stream = _sharedMemoryStream; // Encode image into stream stream.Position = 0; var format = BitmapModeToImgFormat(BitmapMode); img.Save(stream, format); long sizeLong = stream.Length; if (sizeLong > int.MaxValue) { throw new InvalidOperationException("image too large"); } int size = (int)sizeLong; stream.Position = 0; var streamBuffer = stream.GetBuffer(); // Write Size SerializerBinary.WriteUInt32Fixed(ref buffer, ref offset, (uint)size); // Write stream data to serialization buffer if (size > 0) { SerializerBinary.EnsureCapacity(ref buffer, offset, size); SerializerBinary.FastCopy(streamBuffer, 0, buffer, (uint)offset, (uint)size); } offset += size; }
public void Serialize(ref byte[] buffer, ref int offset, Bitmap img) { // Let the image serialize itself to the memory stream // Its unfortunate that there's only a stream-based api... // The alternative would be manually locking the bits. // That would be easy, but we'd potentially lose some information (animation frames etc?) var mode = BitmapMode; var format = BitmapModeToImgFormat(mode); if (_sharedMemoryStream == null) { _sharedMemoryStream = new MemoryStream((int)(4 * (img.Width * img.Height) * 1.35)); } var ms = _sharedMemoryStream; ms.Position = 0; img.Save(ms, format); long sizeLong = ms.Position; if (sizeLong > int.MaxValue) { throw new InvalidOperationException("image too large"); } int size = (int)sizeLong; ms.Position = 0; var memoryStreamBuffer = ms.GetBuffer(); // Write Size SerializerBinary.WriteUInt32Fixed(ref buffer, ref offset, (uint)size); // Write data into serialization buffer if (size > 0) { SerializerBinary.EnsureCapacity(ref buffer, offset, size); SerializerBinary.FastCopy(memoryStreamBuffer, 0, buffer, offset, size); } offset += size; }