c# - 如何像字节数组一样处理使用 protobuf 存储的 System.Drawing.Image?

标签 c# .net-6.0 protobuf-net

我使用 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/

相关文章:

c# - 如何在 WinForm 中打开默认 Windows 浏览器并将 HTTP Post 数据发送到浏览器中打开的 Url?

c# - 根据枚举值从 IoC 容器解析

c# - 如何使用 Protobuf.net C# 序列化自定义对象的基本属性

c# - 如何在 Delphi 中检测通用 Windows 平台 (UWP)

C# Entity Framework 查询存储过程错误 "Culture is not supported"

C# Lambda 到 txt 文件

c# - .NET Core 控制台应用程序的 WebApplicationFactory 是否有等效项?

azure - 获取 Azure 错误 : IDW10203: The 'scope' or 'scp' claim does not contain scopes 'access_as_machine' or was not found

c# - 如何获取DatabaseFacade的Log属性?

c# - 如果类在 Protobuf-net 中没有属性,是否有办法仅序列化公共(public)字段?