Search code examples
c#bitmapmemorystream

Saving Bitmap to MemoryStream


I am trying to save a bitmap to a MemoryStream and then convert it to string. But the problem is, I am having an error that says the line img.Save(m, img.RawFormat); cannot be null. The error is this

The bitmap is from a fingerprint scan, that I converted to image. Now I want to convert its data to a string, by using MemoryStream. This is for the fingerprint data to be saved in the database. I don't know where I went wrong. You can find my code below:

        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();
        }

I hope for an accurate answer that can pin point the major error and what parts of the code should I change. Though any help would be much appreciated.


Solution

  • Interesting; what happens here is:

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

    with the inner Save doing this check:

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

    so; we can assume that format.FindEncoder(); is returning null here. As it happens, this is indeed the default if there is no matching codec:

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

    So basically, it isn't clear, but the problem is: there is no encoder found for the image format that you're using. Try saving as a well-known format, not necessarily the one that it loaded from. Maybe use ImageFormat.Png and save it as a png?

    img.Save(m, ImageFormat.Png);
    

    and as already mentioned in the comments, to get base-64 of that, you'll need:

    ping = Convert.ToBase64String(m.GetBuffer(), 0, (int)m.Length);