So, you either need a new file decoder or a patched BmpImagePlugin.py
. How to do the former is described in PIL's manual. For the later you will obviously need to send a patch and hope to get it into the next PIL version. My focus is on creating a new decoder:
from PIL import ImageFile, BmpImagePlugin _i16, _i32 = BmpImagePlugin.i16, BmpImagePlugin.i32 class BmpAlphaImageFile(ImageFile.ImageFile): format = "BMP+Alpha" format_description = "BMP with full alpha channel" def _open(self): s = self.fp.read(14) if s[: 2] != 'BM': raise SyntaxError("Not a BMP file") offset = _i32(s[10: ]) self._read_bitmap(offset) def _read_bitmap(self, offset): s = self.fp.read(4) s += ImageFile._safe_read(self.fp, _i32(s) - 4) if len(s) not in (40, 108, 124): # Only accept BMP v3, v4, and v5. raise IOError("Unsupported BMP header type (%d)" % len(s)) bpp = _i16(s[14: ]) if bpp != 32: # Only accept BMP with alpha. raise IOError("Unsupported BMP pixel depth (%d)" % bpp) compression = _i32(s[16: ]) if compression == 3: # BI_BITFIELDS compression mask = (_i32(self.fp.read(4)), _i32(self.fp.read(4)), _i32(self.fp.read(4)), _i32(self.fp.read(4))) # XXX Handle mask. elif compression != 0: # Only accept uncompressed BMP. raise IOError("Unsupported BMP compression (%d)" % compression) self.mode, rawmode = 'RGBA', 'BGRA' self.size = (_i32(s[4: ]), _i32(s[8: ])) direction = -1 if s[11] == '\xff': # upside - down storage self.size = self.size[0], 2 ** 32 - self.size[1] direction = 0 self.info["compression"] = compression # data descriptor self.tile = [("raw", (0, 0) + self.size, offset, (rawmode, 0, direction))]
To properly use this, the canonical way is supposedly to perform:
from PIL
import Image
Image.register_open(BmpAlphaImageFile.format, BmpAlphaImageFile)
# XXX register_save
Image.register_extension(BmpAlphaImageFile.format, ".bmp")
The problem is that there is already a plugin for handling ".bmp", and I didn't bother to find out how I could prepend this new extension so it is used before BmpImagePlugin is used (I also don't know if it is possible to do such thing in PIL). Said that, I actually used the code directly, as in:
from BmpAlphaImagePlugin
import BmpAlphaImageFile
x = BmpAlphaImageFile('gearscolor.bmp')
print x.mode
x.save('abc1.png')
The code by @mmgp is great for loading BMP files with Alpha, but on Python 3 requires two small changes:
if s[: 2] != 'BM':
becomes:
if s[: 2] != b 'BM':
and self.size needs to change where used, so the end of the code becomes:
self._size = (_i32(s[4: ]), _i32(s[8: ])) direction = -1 if s[11] == '\xff': # upside - down storage self._size = self._size[0], 2 ** 32 - self._size[1] direction = 0 self.info["compression"] = compression # data descriptor self.tile = [("raw", (0, 0) + self._size, offset, (rawmode, 0, direction))]
Or use a try/catch block as a fall-back:
try:
img = BmpAlphaImageFile(filename)
except IOError:
img = Image.open(filename)
Where gearscolor.bmp is a sample bitmap with full alpha channel as described earlier. The resulting png is saved with alpha data. If you check BmpImagePlugin.py's code, you will notice I reused most of its code.,So, you either need a new file decoder or a patched BmpImagePlugin.py. How to do the former is described in PIL's manual. For the later you will obviously need to send a patch and hope to get it into the next PIL version. My focus is on creating a new decoder:,The problem is that there is already a plugin for handling ".bmp", and I didn't bother to find out how I could prepend this new extension so it is used before BmpImagePlugin is used (I also don't know if it is possible to do such thing in PIL). Said that, I actually used the code directly, as in:,Ok, here is something to get started. Since I don't know specifically which format is your BMP file, I only handled a specific case of BMP with full alpha channel that I happen to have. The kind of BMPs I'm handling here can be obtained by converting, for example, PNG with alpha to BMP using ImageMagick. This will create what is called "BITMAPV5". Given your description, you don't have a BitmapV5 (because PIL would fail to even open it), so we will need an iteration with discussions to solve your specific case.
So, you either need a new file decoder or a patched BmpImagePlugin.py
. How to do the former is described in PIL's manual. For the later you will obviously need to send a patch and hope to get it into the next PIL version. My focus is on creating a new decoder:
from PIL import ImageFile, BmpImagePlugin _i16, _i32 = BmpImagePlugin.i16, BmpImagePlugin.i32 class BmpAlphaImageFile(ImageFile.ImageFile): format = "BMP+Alpha" format_description = "BMP with full alpha channel" def _open(self): s = self.fp.read(14) if s[: 2] != 'BM': raise SyntaxError("Not a BMP file") offset = _i32(s[10: ]) self._read_bitmap(offset) def _read_bitmap(self, offset): s = self.fp.read(4) s += ImageFile._safe_read(self.fp, _i32(s) - 4) if len(s) not in (40, 108, 124): # Only accept BMP v3, v4, and v5. raise IOError("Unsupported BMP header type (%d)" % len(s)) bpp = _i16(s[14: ]) if bpp != 32: # Only accept BMP with alpha. raise IOError("Unsupported BMP pixel depth (%d)" % bpp) compression = _i32(s[16: ]) if compression == 3: # BI_BITFIELDS compression mask = (_i32(self.fp.read(4)), _i32(self.fp.read(4)), _i32(self.fp.read(4)), _i32(self.fp.read(4))) # XXX Handle mask. elif compression != 0: # Only accept uncompressed BMP. raise IOError("Unsupported BMP compression (%d)" % compression) self.mode, rawmode = 'RGBA', 'BGRA' self.size = (_i32(s[4: ]), _i32(s[8: ])) direction = -1 if s[11] == '\xff': # upside - down storage self.size = self.size[0], 2 ** 32 - self.size[1] direction = 0 self.info["compression"] = compression # data descriptor self.tile = [("raw", (0, 0) + self.size, offset, (rawmode, 0, direction))]
To properly use this, the canonical way is supposedly to perform:
from PIL
import Image
Image.register_open(BmpAlphaImageFile.format, BmpAlphaImageFile)
# XXX register_save
Image.register_extension(BmpAlphaImageFile.format, ".bmp")
The problem is that there is already a plugin for handling ".bmp", and I didn't bother to find out how I could prepend this new extension so it is used before BmpImagePlugin is used (I also don't know if it is possible to do such thing in PIL). Said that, I actually used the code directly, as in:
from BmpAlphaImagePlugin
import BmpAlphaImageFile
x = BmpAlphaImageFile('gearscolor.bmp')
print x.mode
x.save('abc1.png')
The results you get with this method will be visually identical to converting the image to L or LA modes.,Digital Image Color Modes,Digital Image Color Modes ,Convert the image to one of the color modes that are convenient for your task. Image modes can be as following for monochrome (B&W and grayscale): L, LA, 1
from PIL
import Image, ImageEnhance
file = "C://Users/ABC/20.jpg"
img = Image.open(file)
img.show()
from PIL
import Image
file = "C://Users/ABC/20.jpg"
img = Image.open(file)
img.convert("1")
img.show()
from PIL
import Image
file = "C://Users/ABC/20.jpg"
img = Image.open(file)
img = img.convert("L")
img.show()
from PIL
import Image
file = "C://Users/ABC/20jpg"
img = Image.open(file)
filter = ImageEnhance.Color(img)
filter.enhance(0)
img.show()
from PIL import Image, ImageEnhance img = Image.open("Desktop/11.jpg") img_data = img.getdata() lst = [] for i in img_data: # lst.append(i[0] * 0.299 + i[1] * 0.587 + i[2] * 0.114) # # # Rec.609 - 7 weights lst.append(i[0] * 0.2125 + i[1] * 0.7174 + i[2] * 0.0721) # # # Rec.709 - 6 weights new_img = Image.new("L", img.size) new_img.putdata(lst) new_img.show()
Last Updated On: December 02, 2020
You can install Pillow with pip
as shown:
python3 - m pip install--upgrade pip
python3 - m pip install--upgrade Pillow
To load an image from a file, we use the open()
function in the Image
module, passing it the path to the image.
from PIL
import Image
image = Image.open('demo_image.jpg')
After obtaining an Image
object, you can now use the methods and attributes defined by the class to process and manipulate it. Let's start by displaying the image. You can do this by calling the show()
method on it. This displays the image on an external viewer (usually Preview on macOS, xv on Unix, and the Paint program on Windows).
image.show()
When you are done processing an image, you can save it to a file with the save()
method, passing in the name that will be used to label the image file. When saving an image, you can specify a different extension from its original, and the saved image will be converted to the specified format.
image = Image.open('demo_image.jpg')
image.save('new_image.png')
To resize an image, you call the resize()
method on it, passing in a two-integer tuple argument representing the width and height of the resized image. The function doesn't modify the used image; it instead returns another Image with the new dimensions.
image = Image.open('demo_image.jpg') new_image = image.resize((400, 400)) new_image.save('image_400.jpg') print(image.size) # Output: (1920, 1280) print(new_image.size) # Output: (400, 400)
Last Updated : 17 Dec, 2020,Technical Scripter 2020
Syntax:
imread(path, flag)
Thanks nezachem! Looks like my .png image file only has RGB and not RGBA. You could use this modified code:, My goal is to take that newly saved image file (.png) and to convert it to a bitmap (.bmp) file within the same folder.,I figured out what I'm doing wrong and this is actually similar to an error I had before. PIL will not let me convert to bitmap unless the image is black and white first. I'm going to try to convert it to black and white by associating the image with "1"., So I'm trying to convert the image to bitmap. I've looked at WxImage and Python Imaging Library (PIL) and I have no clue what I'm doing wrong.
It's as simple as this:
# convert a.png image file to a.bmp image file using PIL from PIL import Image file_in = "test1.png" img = Image.open(file_in) file_out = "test1.bmp" img.save(file_out)
PIL does not support alpha in BMP files. You need to strip it yourself. Something like (warning: untested):
img = Image.open("file.png")
r, g, b, a = img.split()
img = Image.merge("RGB", (r, g, b))
img.save("file.bmp")
It's as simple as this:
# convert a.png image file to a.bmp image file using PIL from PIL import Image file_in = "test1.png" img = Image.open(file_in) file_out = "test1.bmp" img.save(file_out)
I also get this error message.
Traceback (most recent call last):
File "C:\Python26\January\wxpython.py", line 9, in <module>
img.save(file_out)
File "C:\Python26\lib\site-packages\PIL\Image.py", line 1405, in save
save_handler(self, fp, filename)
File "C:\Python26\lib\site-packages\PIL\BmpImagePlugin.py", line 197, in _save
raise IOError("cannot write mode %s as BMP" % im.mode)
IOError: cannot write mode RGBA as BMP
PIL does not support alpha in BMP files. You need to strip it yourself. Something like (warning: untested):
img = Image.open("file.png")
r, g, b, a = img.split()
img = Image.merge("RGB", (r, g, b))
img.save("file.bmp")
Thanks nezachem!
Looks like my .png image file only has RGB and not RGBA. You could use this modified code:
# convert a.png image file to a.bmp image file using PIL from PIL import Image file_in = "test.png" img = Image.open(file_in) file_out = "test2.bmp" print len(img.split()) # test if len(img.split()) == 4: # prevent IOError: cannot write mode RGBA as BMP r, g, b, a = img.split() img = Image.merge("RGB", (r, g, b)) img.save(file_out) else: img.save(file_out)