How can I save an image with PIL? How can I save an image with PIL? python python

How can I save an image with PIL?


The error regarding the file extension has been handled, you either use BMP (without the dot) or pass the output name with the extension already. Now to handle the error you need to properly modify your data in the frequency domain to be saved as an integer image, PIL is telling you that it doesn't accept float data to save as BMP.

Here is a suggestion (with other minor modifications, like using fftshift and numpy.array instead of numpy.asarray) for doing the conversion for proper visualization:

import sysimport numpyfrom PIL import Imageimg = Image.open(sys.argv[1]).convert('L')im = numpy.array(img)fft_mag = numpy.abs(numpy.fft.fftshift(numpy.fft.fft2(im)))visual = numpy.log(fft_mag)visual = (visual - visual.min()) / (visual.max() - visual.min())result = Image.fromarray((visual * 255).astype(numpy.uint8))result.save('out.bmp')


You should be able to simply let PIL get the filetype from extension, i.e. use:

j.save("C:/Users/User/Desktop/mesh_trans.bmp")


Try removing the . before the .bmp (it isn't matching BMP as expected). As you can see from the error, the save_handler is upper-casing the format you provided and then looking for a match in SAVE. However the corresponding key in that object is BMP (instead of .BMP).

I don't know a great deal about PIL, but from some quick searching around it seems that it is a problem with the mode of the image. Changing the definition of j to:

j = Image.fromarray(b, mode='RGB')

Seemed to work for me (however note that I have very little knowledge of PIL, so I would suggest using @mmgp's solution as s/he clearly knows what they are doing :) ). For the types of mode, I used this page - hopefully one of the choices there will work for you.