Matplotlib savefig to BytesIO is slightly wrong?
Question: I'm trying to save [matplotlib](/questions/tagged/matplotlib "show questions
tagged 'matplotlib'") figures to a memory stream, exactly as in another
example on SO:

    
    
    import matplotlib.pyplot as plt
    import io
    
    
    plt.figure()
    plt.plot([1, 2])
    plt.title("test")
    buf = io.BytesIO()
    plt.savefig(buf, format = 'png')
    plt.savefig("real.png", format = 'png')
    buf.seek(0)
    data = buf.read()
    buf.close()
    f = open('copy.png', 'w')
    f.write(data)
    f.close()
    

I find that copy.png is slightly larger in size and applications refuse to
open it. Is this some sort of encoding issue?

**Background** :

I'm trying to use python.net to render graphs with matplotlib and pass them
out to C# for drawing. I want to avoid writing the images to disk. Ideally, I
want to write to some sort of byte array that I can work with in C#.


Answer: Try opening the file in binary mode.

`f = open('copy.png', 'wb')`

From the documentation:

> Python on Windows makes a distinction between text and binary files; the
> end-of-line characters in text files are automatically altered slightly when
> data is read or written. This behind-the-scenes modification to file data is
> fine for ASCII text files, but it’ll corrupt binary data like that in JPEG
> or EXE files. Be very careful to use binary mode when reading and writing
> such files.

