我使用 protobuf-net v2.4.0 来存储 System.Drawing.Image 以及以下代理:
internal class SystemDrawingImageSurrogate
{
public SystemDrawingImageSurrogate(byte[] data)
{
Data = data;
}
public byte[] Data;
public static implicit operator System.Drawing.Image(SystemDrawingImageSurrogate surrogate)
{
if (surrogate == null || surrogate.Data == null)
return null;
MemoryStream stream = new MemoryStream(surrogate.Data);
var bitmap = new System.Drawing.Bitmap(stream);
return bitmap;
}
public static implicit operator SystemDrawingImageSurrogate(System.Drawing.Image source)
{
if (source == null)
return null;
byte[] byteImage = (byte[])new ImageConverter().ConvertTo(source, typeof(byte[]));
return new SystemDrawingImageSurrogate(byteImage);
}
}
我用它来存储如下所示的类:
public class PersonWithPhotoSurrogate : PersonSurrogate
{
public PersonWithPhotoSurrogate(PersonWithPhoto pwp) : base(pwp)
{
}
public int PictureWidth;
public int PictureHeight;
public System.Drawing.Image Photo;
}
public class FileBodySurrogate
{
public FileBodySurrogate(FileBody fileBody) { }
public List<Person> People;
}
现在我需要从 net-framework 迁移到 net6,因此我需要将 PersonWithPhotoSurrogate.Photo 字段声明为 byte[] 而不是 Image如下图:
public class PersonWithPhotoSurrogate : PersonSurrogate
{
public PersonWithPhotoSurrogate(PersonWithPhoto pwp) : base(pwp)
{
}
public int PictureWidth;
public int PictureHeight;
public /*System.Drawing.Image*/ byte[] Photo;
}
在读取存储的旧文件时,如何处理此问题以保持向后兼容性?
最佳答案
您的 SystemDrawingImageSurrogate
在模型中添加了一个额外的层,因此,如果您从 Image
切换到简单的 byte[]
,您'仍然需要表示该层;也许(未经测试):
public class PersonWithPhotoSurrogate : PersonSurrogate
{
public PersonWithPhotoSurrogate(PersonWithPhoto pwp) : base(pwp)
{
}
public int PictureWidth;
public int PictureHeight;
public ImageWrapper Photo;
}
public class ImageWrapper
{
public byte[] Data;
}
显然具有与原始模型相同的标签编号。您不应该需要替代件 - 您只需要模型看起来与替代件的相同。
关于c# - 如何像字节数组一样处理使用 protobuf 存储的 System.Drawing.Image?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74598036/