pillow can not draw text with fill - python

i draw a text to a image and i set the fill and i get an error , but i do not for the fill it get nothing for my image
from PIL import Image, ImageDraw
img = Image.open('test.png')
d = ImageDraw.Draw(img)
d.text((100, 100), "HELLO", fill="red")
img.save('testssss.png')
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImagePalette.py", line 99, in getcolor
return self.colors[color]
KeyError: (255, 0, 0)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 20, in <module>
d.text((100, 100), "HELLO", fill="red")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImageDraw.py", line 455, in text
ink = getink(fill)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImageDraw.py", line 403, in getink
ink, fill = self._getink(fill)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImageDraw.py", line 111, in _getink
ink = self.palette.getcolor(ink)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImagePalette.py", line 109, in getcolor
self.palette[index + 256] = color[1]
IndexError: bytearray index out of range
The image:
my system : replit(linux)

Try, (255,0,0) instead of red.
from PIL import Image, ImageDraw
img = Image.open('test.png')
d = ImageDraw.Draw(img)
d.text((100, 100), "HELLO", fill=(255,0,0))
img.save('testssss.png')
You should also look at the size of your image, it might be too small for the text you are using. You can try reducing from (100,100) to maybe (10,10) first and see if it works.
It could also be a case where you don’t have enough bits for the colour because your image is less than 256 bits per colour palette. You can also try converting your image to an rgb image using the following command before you add the text. Do
img = img.convert("RGB")

Related

can't save JPG image with alpha

width, height = resized_image.size
dummyImg = np.zeros([height, width, 4], dtype=np.uint8)
for x in range(width):
for y in range(height):
color = seg_map[y,x]
(r,g,b) = resized_image.getpixel((x,y))
if color == 0:
dummyImg[y,x] = [255,255,255,255]
else:
dummyImg[y,x] = [r,g,b,255]
img = Image.fromarray(dummyImg)
outputFilePath = '15d09a689ca0d4 Mod.jpg'
img.save(outputFilePath)
Hello, I am getting this error while trying to save image as "JPG", I included alpha channels in dummyimg.
Traceback (most recent call last):
File "/home/timmy/.local/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 620, in _save
rawmode = RAWMODE[im.mode]
KeyError: 'RGBA'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/timmy/Desktop/image-background-removal-master/impr.py", line 79, in <module>
img.save(outputFilePath)
File "/home/timmy/.local/lib/python3.6/site-packages/PIL/Image.py", line 2007, in save
save_handler(self, fp, filename)
File "/home/timmy/.local/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 622, in _save
raise IOError("cannot write mode %s as JPEG" % im.mode)
OSError: cannot write mode RGBA as JPEG
I checked GitHub issue cannot write mode RGBA as JPEG (4.2.0) , they said it is solved and is now doable
JPEG file format cannot handle transparency. To save an image with color and transparency you need to use another format (e.g. PNG).
You can save to JPEG only if you drop the alpha channel and make all pixels opaque.

Pillow: How can i paste a Image on another Image?

I'm writing a script that automatically create Quote Image for Instagram. So i want to put an log (logo.png) on the background.
If i run my code i get this error:
$ python main.py
Traceback (most recent call last):
File "main.py", line 17, in <module>
imgbg = bg.paste(logo, (0,0,0,0))
File "C:\Users\bukto\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\Image.py", line 1459, in paste
self.im.paste(im, box)
ValueError: images do not match
Thats my code:
#imports
from PIL import Image
import random
###Generate a Color###
#a list of rgb color codes
colors = [(26, 188, 156),(46, 204, 113),(39, 174, 96),(22, 160, 133),(52, 152, 219),(41, 128, 185),(155, 89, 182),(142, 68, 173),(52, 73, 94),(44, 62, 80),(230, 126, 34),(211, 84, 0),(231, 76, 60),(192, 57, 43)]
bg = Image.new('RGB', (800, 800), random.choice(colors)) #choose a random number out of the list
#add Logo
logo = Image.open("logo.png")
imgbg = bg.paste(logo, (0,0,0,0))
imgbg.save("./img/test.png")
I expect that the logo is in the left top.
If you want to test it yourself here is an git branch:
https://github.com/koehlertimo/QuoteMaker/tree/stackoverflow
Thanks for your support,
Timo Köhler
Your logo.png seems to load as a greyscale with alpha for some reason, so I split it into its constituent parts with:
logo = Image.open("logo.png")
Grey, Alpha = logo.split()
You then paste and save like this:
bg.paste(logo, (0,0), Alpha)
bg.save('result.png')

PIL Internal Exception: {TypeError}getsize() takes exactly 1 argument (3 given)

I get the exception referenced in the title using this code:
from PIL import Image, ImageDraw, ImageFont
img = Image.open('test_fixtures/image00161.jpg')
draw = ImageDraw.Draw(img)
font = ImageFont.load_default().font
draw.multiline_text((20,20), 'some text', 'white', font)
Here is the full stack trace:
Error
Traceback (most recent call last):
File "/home/davidparks21/opt/anaconda3/envs/xevo/lib/python2.7/unittest/case.py", line 329, in run
testMethod()
File "/home/davidparks21/ws/git/src/common/ml/scripts/FitnetsFAN/xf_plot_landmarks_test.py", line 18, in test_plt_landmarks_on_image
self.ground_truth_landmarks, self.ground_truth_landmarks + 7)
File "/home/davidparks21/ws/git/src/common/ml/scripts/FitnetsFAN/xf_plot_landmarks.py", line 63, in plt_landmarks_on_image
draw.multiline_text((20,20), legends, 'white', font)
File "/home/davidparks21/opt/anaconda3/envs/xevo/lib/python2.7/site-packages/PIL/ImageDraw.py", line 234, in multiline_text
line_spacing = self.textsize('A', font=font)[1] + spacing
File "/home/davidparks21/opt/anaconda3/envs/xevo/lib/python2.7/site-packages/PIL/ImageDraw.py", line 263, in textsize
return font.getsize(text, direction, features)
TypeError: getsize() takes exactly 1 argument (3 given)
When I look at line 263 of ImageDraw.py the code is:
return font.getsize(text, direction, features)
This leads me to one of three possible conclusions:
There's a version mismatch somewhere, but I can't see how
There's a bug in PIL
I'm using font wrong
Anyone want to venture a guess as to which it is? Or propose a new possibility?
FYI:
PIL.VERSION
'1.1.7'
PIL.PILLOW_VERSION
'5.0.0'
Change below
font = ImageFont.load_default().font
to
font = ImageFont.load_default()
And it should work

Why is Image.composite returning a "bad mask" error when I used one of the 2 images as a mask?

I followed this tutorial and the guy used the one of the 2 images as the mask. But for me it's not working. Why is this?
from PIL import Image
img1 = Image.open("beach.jpg")
img2 = Image.open("joker.jpg")
maxsize = min(img1.size,img2.size)
newratio = min(maxsize[0]/img2.size[0],maxsize[1]/img1.size[1])
newimg1width = int(img1.size[0]*newratio)
newimg1height = int(img1.size[1]*newratio)
newimgtuple = (newimg1width,newimg1height)
newimg = img1.resize(newimgtuple)
compimg = Image.composite(newimg, img2, newimg)
compimg.save("compimg.jpg")
The error:
Traceback (most recent call last):
File "C:\Users\dude\Desktop\Desktop\Projects\Youtube\Wordtoon\test.py", line 44, in <module>
compimg = Image.composite(newimg, img2, newimg)
File "C:\Users\dude\AppData\Local\Programs\Python\Python35-32\lib\site-packages\PIL\Image.py", line 2376, in composite
image.paste(image1, None, mask)
File "C:\Users\dude\AppData\Local\Programs\Python\Python35-32\lib\site-packages\PIL\Image.py", line 1344, in paste
self.im.paste(im, box, mask.im)
ValueError: bad transparency mask

PIL crop and paste problem: Cropping doesn't create a cropped image

I'm trying to crop an image and then paste the cropped image into the centre of another image. Ideally I'd like the cropped image to be smaller than the image its being pasted on so that there is a border around the pasted image but I don't know if that's possible.
Here's what I've tried (along with the resulting error message):
>>> import Image
>>> grey = Image.new('RGB', (200, 200), "grey")
>>> House = Image.open("House01.jpg")
>>> print grey.size, grey.mode, grey.format
>>>(200, 200) RGB None
>>> print House.size, House.mode, House.format
>>>(300, 300) RGB JPEG
>>> box = (25, 25, 25, 25)
>>> House.crop(box)
>>>Image._ImageCrop image mode=RGB size=0x0 at 0x11AD210>
>>> region = House.crop(box)
>>> region.show()
>>>Traceback (most recent call last):
>>> File "<pyshell#28>", line 1, in <module>
region.show()
>>> File "C:\Python26\lib\site-packages\PIL\Image.py", line 1483, in show
_show(self, title=title, command=command)
>>> File "C:\Python26\lib\site-packages\PIL\Image.py", line 2123, in _show
apply(_showxv, (image,), options)
>>> File "C:\Python26\lib\site-packages\PIL\Image.py", line 2127, in _showxv
apply(ImageShow.show, (image, title), options)
>>> File "C:\Python26\lib\site-packages\PIL\ImageShow.py", line 41, in show
if viewer.show(image, title=title, **options):
>>> File "C:\Python26\lib\site-packages\PIL\ImageShow.py", line 66, in show
self.show_image(image, **options)
>>> File "C:\Python26\lib\site-packages\PIL\ImageShow.py", line 85, in show_image
return self.show_file(self.save_image(image), **options)
>>> File "C:\Python26\lib\site-packages\PIL\ImageShow.py", line 81, in save_image
return image._dump(format=self.get_format(image))
>>> File "C:\Python26\lib\site-packages\PIL\Image.py", line 493, in _dump
self.save(file, format)
>>> File "C:\Python26\lib\site-packages\PIL\Image.py", line 1439, in save
save_handler(self, fp, filename)
>>> File "C:\Python26\lib\site-packages\PIL\BmpImagePlugin.py", line 242, in _save
ImageFile._save(im, fp, [("raw", (0,0)+im.size, 0, (rawmode, stride, -1))])
>>> File "C:\Python26\lib\site-packages\PIL\ImageFile.py", line 498, in _save
e.setimage(im.im, b)
>>>SystemError: tile cannot extend outside image
I can see that the 'region' size has been made (0,0) but I can't understand why.
Any help on this would be great thanks
The PIL documentation for the crop method states:
Returns a rectangular region from the
current image. The box is a 4-tuple
defining the left, upper, right, and
lower pixel coordinate.
This is a lazy operation. Changes to
the source image may or may not be
reflected in the cropped image. To get
a separate copy, call the load method
on the cropped copy.
So, you should try region = House.crop(box).load() to make sure you get an actual cropped copy.
UPDATE:
Actually, it seems the above only works if you're using PIL 1.1.6 and later. In versions before that, I guess load() doesn't return anything so you can't chain the operations. In that case, use:
region = House.crop(box)
region.load()
I had a similar error that I could not seem to solve, but I then realized as you did that it had to do with the arguments passed in to Image.crop(). You can see the size of your image is (0,0) so there is nothing to show. You are setting bounds from point (25,25) to (25,25).
If you need a 25x25 cropped image(starting from the top left):
```
>
>> import Image
>>> grey = Image.new('RGB', (200, 200), "grey")
>>> House = Image.open("House01.jpg")
>>> print grey.size, grey.mode, grey.format
>>>(200, 200) RGB None
>>> print House.size, House.mode, House.format
>>>(300, 300) RGB JPEG
>>> box = (0, 0, 25, 25)
>>> House.crop(box)
>>>Image._ImageCrop image mode=RGB size=0x0 at 0x11AD210>
>>> region = House.crop(box)
>>> region.show()
```
If you want to start from the center or another point I would use this link as a reference:

Categories

Resources