Saving a matplotlib figure in BMP format

I am using these libraries:

import matplotlib.pyplot as plt
from PIL import Image as im

My code is as follows:

fig = plt.figure(dpi=250) # 
ax1 = fig.add_subplot(2, 1, 1)
pos1 =ax1.imshow(amplitud_DCO08,cmap='gray')
ax1.title.set_text('Amplitud del DCO')
fig.savefig('AmplitudDCO_escalado08',dpi=250, format='bmp')

I am trying to save the image using the following line of code:

fig.savefig('AmplitudDCO_escalado08',dpi=250, format='bmp')

However this shows me the error:

Format 'bmp' is not supported(supported formats: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff).

I need an image in .bmp format, because I need it quantized at 8 bits. How can I solve this problem? Or there is another way to save an imagen in .bmp format?

Upvotes: 0

Views: 4484

Answers (3)

Mike B
Mike B

Reputation: 1

The private method _print_pil in the matplotlib agg backend can save as a bmp via PIL.

fig.canvas._print_pil('AmplitudDCO_escalado08.bmp', fmt="BMP", pil_kwargs={})

pil_kwargs is required, so provide an empty dictionary. See PIL image format arguments.

Upvotes: 0

Zichzheng
Zichzheng

Reputation: 1290

If bmp is not supported as a save format. Then I guess there is no other way that let you save it as bmp with plt directly. If so, what we can do is to save it as .PNG first and then convert it to bmp. We can use PIL to do this. And you have PIL in your code so.

fig = plt.figure(dpi=250) # 
ax1 = fig.add_subplot(2, 1, 1)
pos1 =ax1.imshow(amplitud_DCO08,cmap='gray')
ax1.title.set_text('Amplitud del DCO')
fig.savefig('AmplitudDCO_escalado08.PNG',dpi=250))
im.open("AmplitudDCO_escalado08.PNG").save("AmplitudDCO_escalado08.bmp")

Upvotes: 1

Marco Bonelli
Marco Bonelli

Reputation: 69346

Seems like Matplotlib does not support saving in BMP format. You'll have to convert the figure into a Pillow image first, and then save that. To do this, you can use PIL.Image.frombytes() as suggested in this other answer.

import matplotlib.pyplot as plt
from PIL import Image as im

fig = plt.figure(dpi=250) # 
ax1 = fig.add_subplot(2, 1, 1)
pos1 =ax1.imshow(amplitud_DCO08,cmap='gray')
ax1.title.set_text('Amplitud del DCO')

image = im.frombytes('RGB', fig.canvas.get_width_height(), fig.canvas.tostring_rgb())
image.save('AmplitudDCO_escalado08.bmp')

Upvotes: 2

Related Questions