Getting this issue while saving and writing text over image using python image library. I am trying to write a text over a png image using Pillow imaging library, however after trying previous answers in stack overflow, still face this issue.
from pickle import FALSE
import sys #keep sys import and insert as first 2 lines
import os
from sys import exit
import numpy as np
from PIL import ImageFont, ImageDraw, Image
fontuse = "D:/Ubuntusharefolder/CustomFonts/EnglishFonts/NotoSans-Medium.ttf"
font_color_bgra = (0,255,0,0)
font = ImageFont.truetype(fontuse, 32 * int(2), layout_engine=ImageFont.LAYOUT_RAQM)
filename = 'order_image_1.png'
input_subfolder_path= 'D:/testinput'
output_folder_final_path = 'D:/testinput/updtxtimg'
src_img_base = np.full((1920, 1080, 3),255, dtype = np.uint8) #(1920, 1080, 3)
print('src_base imguse gen size: ',src_img_base.shape)
print ('input img file path:',input_subfolder_path + '/' + filename)
src_img_use = np.array(Image.open( input_subfolder_path + '/' + filename ) ) #(511, 898, 4)
print('src_imguse gen size: ', src_img_use.shape)
textpos = (520, 210)
textwrite = 'Testname'
img_pil_4dtxt = ImageDraw.Draw(Image.fromarray(src_img_base))
#img_pil_4dtxt = ImageDraw.Draw(Image.fromarray(src_img_use))
img_pil_4dtxt.text(textpos, textwrite, font = font, fill = font_color_bgra)
print('saved img in path:',output_folder_final_path + '/' + 'upd' + '_' + filename)
Image.fromarray(img_pil_4dtxt).save(output_folder_final_path + '/' + 'upd' + '_' + filename)
print('saved_img done')
command line and error obtained:
> & C:/ProgramData/Anaconda3/python.exe ./code/txtoverimgv1.py
src_base imguse gen size: (1920, 1080, 3)
input img file path: D:/testinput/order_image_1.png
src_imguse gen size: (1080, 1920, 4)
saved img in path: D:/testinput/updtxtimg/upd_order_image_1.png
Traceback (most recent call last):
File "./code/txtoverimgv1.py", line 29, in <module>
Image.fromarray(img_pil_4dtxt).save(output_folder_final_path + '/' + 'upd' + '_' + filename)
File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\Image.py", line 2762, in fromarray
arr = obj.__array_interface__
AttributeError: 'ImageDraw' object has no attribute '__array_interface__'
This happens because ImageDraw.Draw()
does not return a NumPy array, but an ImageDraw object. You cannot directly call Image.fromarray()
on it;
pil_img = Image.fromarray(src_img_base) # or src_img_use if needed
img_pil_4dtxt = ImageDraw.Draw(pil_img)
img_pil_4dtxt.text(textpos, textwrite, font=font, fill=font_color_bgra)
output_path = os.path.join(output_folder_final_path, 'upd_' + filename)
pil_img.save(output_path)