将位图保存到MemoryStream

时间:2019-01-30 17:13:36

标签: c# bitmap memorystream

我想一个位图保存到MemoryStream,然后将其转换为字符串。但问题是,我有这行的错误img.Save(m, img.RawFormat);不能nullThe error is this

位图来自指纹扫描,我将其转换为图像。现在,我想它的数据转换为字符串,使用的MemoryStream。这是用于将指纹数据保存在数据库中。我不知道哪里出了问题。您可以在下面找到我的代码:

        Bitmap bitmap;
        bitmap = ConvertSampleToBitmap(Sample);
        Bitmap img = new Bitmap(bitmap, fingerprint.Size);
        this.Invoke(new Function(delegate () {
            fingerprint.Image = img;   // fit the image into the picture box
        }));
        string ping;
        using (MemoryStream m = new MemoryStream())
        {
            img.Save(m, img.RawFormat);
            ping = m.ToString();
        }

我希望一个准确的答案,可以针点的重大错误,哪些部分的代码我应该改变。 虽然任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

有趣;这里发生的是:

public void Save(Stream stream, ImageFormat format)
{
    if (format == null)
    {
        throw new ArgumentNullException("format");
    }
    ImageCodecInfo encoder = format.FindEncoder();
    this.Save(stream, encoder, null);
}

使用内部Save进行此检查:

public void Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
{
    if (stream == null)
    {
        throw new ArgumentNullException("stream");
    }
    if (encoder == null)
    {
        throw new ArgumentNullException("encoder");
    }

所以;我们可以假设format.FindEncoder();在这里返回null。碰巧的是,如果没有匹配的编解码器,这确实是默认设置:

internal ImageCodecInfo FindEncoder()
{
    foreach (ImageCodecInfo info in ImageCodecInfo.GetImageEncoders())
    {
        if (info.FormatID.Equals(this.guid))
        {
            return info;
        }
    }
    return null;
}

因此,基本上还不清楚,但问题是:找不到用于您使用的图像格式的编码器。尝试保存为一种众所周知的格式,不一定是从其加载的格式。也许使用ImageFormat.Png并将其另存为png?

img.Save(m, ImageFormat.Png);

并且正如评论中已经提到的那样,要获得64的基数,您需要:

ping = Convert.ToBase64String(m.GetBuffer(), 0, (int)m.Length);
相关问题