New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-2: ordinal not in range(256) while trying to write Japanese in a new image #6225
Comments
You are using the default font, which supports only Latin-1 characters. You have to use a different font, for example: from PIL import ImageFont
font = ImageFont.truetype("NotoSansJP-Regular.ttf", size=20)
# ...
draw.text((203, 123), '道の駅', fill='#355C31', font=font) Edit: replaced Arial (I don't think it has Japanese support) with NotoSansJP (supports Japanese) |
Yes, @nulano, with indicating the font, the codes won't raise an error while the output is messy, only three rectangles are displayed as the attached image. |
Two things to check: Does the font you used support Japanese (e.g. in an office text editor)? What font did you try? I'm not sure if it is needed for Japanese, but do you have Raqm enabled? |
The previous result was generated with "Arial.ttf". Now I changed to "MSMINCHO.TTF" and now it works! Appreciate your patience and knowledge @nulano. The first time heard abt Raqm, will go to check it out. Btw, do u happen to know if it's possible to make the display of text a ratio of the image size? |
You can change the size of the font by changing the text = "Hello world"
target_width = 200
size = 20 # initial guess
font = ImageFont.truetype("font.ttf", size=size)
for i in range(3): # tweak number of loops until you get satisfactory speed/quality ratio (even 1 might be enough)
text_length = font.getlength(text)
size = int(size * (target_width / text_length)) # update guess
font = ImageFont.truetype("font.ttf", size=size) # recreate font using new guess
draw.text((x, y), text, font=font, ...) |
Since you are on MacOS, the discussion in #6175 might be relevant for installing Raqm. |
@caozhen-zen is there anything further that we can help you with, or can this issue be closed? |
Hi @radarhere , Many thx for your help. I am cool now. I think we can close this issue. |
What did you do?
What did you expect to happen?
I expect the codes to return a new image with '道の駅' written.
What actually happened?
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-2: ordinal not in range(256)
What are your OS, Python and Pillow versions?
Btw, the
sys.stdout.encoding
isUTF-8
.Thank you for your response!
@nulano @radarhere
The text was updated successfully, but these errors were encountered: