I'm attempting to write a program that places text onto an image, I'm trying to get my head round PIL and have run into the error: OSError: cannot open resource. This is my first python program so apologies if the error is obvious.
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
im = Image.open("example.jpg")
font_type = ImageFont.truetype("Arial.ttf", 18)
draw = ImageDraw.Draw(im)
draw.text(xy=(50, 50), text= "Text One", fill =(255,69,0), font = font_type)
im.show()
I get the error:
Traceback (most recent call last):
File "C:\Users\laurence.maskell\Desktop\attempt.py", line 7, in <module>
font_type = ImageFont.truetype("Arial.ttf", 18)
File "C:\Python34\lib\site-packages\PIL\ImageFont.py", line 259, in truetype
return FreeTypeFont(font, size, index, encoding, layout_engine)
File "C:\Python34\lib\site-packages\PIL\ImageFont.py", line 143, in __init__
self.font = core.getfont(font, size, index, encoding,
layout_engine=layout_engine)
OSError: cannot open resource
I fixed the problem by using default font.
font = ImageFont.load_default()
If you just need to put some text (font style is not matter to you) then this might be a simple solution.
font = ImageFont.load_default()
draw = ImageDraw.Draw(pil_img)
draw.text(( 20, 32), "text_string", (255,0,0), font=font)
from PIL import Image, ImageDraw, ImageFont
im = Image.open("mak.png")
font_type = ImageFont.truetype("arial.ttf", 18)
draw = ImageDraw.Draw(im)
draw.text(xy=(120, 120), text= "download font you want to use", fill=(255,69,0), font=font_type)
im.show()
Its "arial.ttf" not "Arial.ttf"
Here is the link to download arial.ttf font.
I have also met this issue on Windows 10 Pro with PIL 5.3.0.
On my machine, the error is caused by non-ASCII font file names. If I change the the font name to only contain ASCII characters, I can open the font without any error.
Edit (2019-07-29): this is indeed a bug with ImageFont.truetype() method and it has been fixed in this pull request.
For Linux I used:
$ locate .ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-B.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-BI.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-L.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-LI.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-M.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-MI.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-R.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-RI.ttf
/usr/share/fonts/truetype/ubuntu-font-family/UbuntuMono-B.ttf
/usr/share/fonts/truetype/ubuntu-font-family/UbuntuMono-BI.ttf
/usr/share/fonts/truetype/ubuntu-font-family/UbuntuMono-R.ttf
/usr/share/fonts/truetype/ubuntu-font-family/UbuntuMono-RI.ttf
It actually returned A LOT MORE than that!
Then I took the python code posted here in Stack Overflow:
PIL: Generating Vertical Gradient Image
Plugged in the font name "Ubuntu-R.ttf" returned by locate:
color_palette = [BLUE, GREEN, RED]
image_w=200
image_h=200
region = Rect(0, 0, image_w, image_h)
imgx, imgy = region.max.x+1, region.max.y+1
image = Image.new("RGB", (imgx, imgy), WHITE)
draw = ImageDraw.Draw(image)
vert_gradient(draw, region, gradient_color, color_palette)
#image.text((40, 80),"No Artwork",(255,255,255))
#font = ImageFont.truetype(r'C:\Users\System-Pc\Desktop\arial.ttf', 40)
#font = ImageFont.load_default()
font = ImageFont.truetype("Ubuntu-R.ttf", int(float(image_w) / 6))
draw.text((int(image_w/12), int(image_h / 2.5)), "No Artwork", \
fill=(0,0,0), font=font)
image.show()
And voila! I now have an image to display when there is no image to display in a music file I'm playing:
I was also facing the same issue. but later found out it was an issue with the slash. So, if anybody else missed this small thing, it's for you.
I had the font inside the font folder. When I tried to import the font using font/<font_name>.ttf, the code couldn't locate it. Replaced / with \ and it could locate the font.
If you are on Windows, by the following method my problem was resolved:
go to the Font folder in C:\Windows\Fonts
Right-click on the font that you want to use and click on "Properties"
go to the Security tab and copy the address of "Object name:"
then place the above path (*****) in the following code:
ImageFont.truetype("*****", int(float(image_w) / 6))
PIL cannot find the specified font. Check that it exists, and that it is named with the exact same case.
You can also try to copy it directly in the project folder.
I think you should move the font to fonts or any folder. I had the same issue on heroku. After i moved the font to fonts directory it works
When I ran into this issue in Linux, I solved by:
Install the .ttf into Linux
Run the code with the actual .tff in ~. For some reason, even with the font installed and the .py running inn another dir, it needed to have the .tff in the home dir.
This issue also crops up in PIL for android. While it is quite possible to copy a font file into the project directory as others have noted, if more than a few android fonts are wanted it may be tidier to add the android font directory to the ImageFont.py search path instead. I altered it like this between lines 870-871:
870 elif sys.platform in ("linux", "linux2"):
if 'ANDROID_BOOTLOGO' in os.environ:
# kludge added for android
dirs += [
"/system/fonts"
]
else:
871 lindirs = os.environ.get("XDG_DATA_DIRS", "")
872 if not lindirs:
... # According to the freedesktop spec, XDG_DATA_DIRS should
# default to /usr/share
lindirs = "/usr/share"
dirs += [os.path.join(lindir, "fonts") for lindir in lindirs.split(":")]
As I have understood, a problem with location
of the file: "Arial.ttf"
As I have understood the Arial.ttf file is with the program, but start is made from other place.
In this case it is necessary to add the Arial.ttf file to a full path:
# __file__ contain full path to the py scrypt
# for python 3.9 and later
import os
path = os.path.dirname(__file__) + '/'
im = Image.open("example.jpg")
font_type = ImageFont.truetype(path + "Arial.ttf", 18)
For older py version see more at:
How do I get the full path of the current file's directory?
It's just that the name of the .ttf file does'nt match with the filename you pass to ImageFont.truetype().
Make sure that the case and spelling are correct. There is no other external factor that could affect merely loading a font from a ttf file.
I solved it simply by doing the following steps:
Created a hidden folder named fonts (.fonts) in the home directory.
Downloaded my desired font from the web. Note: You can download any
font you want by typing "font_name.tiff download" on Google.
Copy and paste the downloaded .ttf file into the .fonts folder.
Copy and paste the new path of your .ttf file in the code as shown below.
im_show = draw_ocr(image, boxes, txts, scores, font_path='/.fonts/simfang.ttf')
That's how it worked for me.
You can follow this link as a visual aid. https://www.youtube.com/watch?v=Q5GO_glHXyQ&t=35s
Related
I convert a PostScript file to PDF by Ghostscript. I have a problem embedding/installing Type 1 fonts.
For installing Type 1 Font, I can add the PFA file path to Ghostscript Fontmap, which should be in /usr/share/ghostscript/version/FONTMAP, but I have no such file in /usr/share/ghostscript/9.50` or similar folders on Ubuntu 20.04.
How can I include the font file directly within the script:
Instead of
/Times-Bold findfont 10 scalefont setfont
something like
(/home/font.pfa) 10 scalefont setfont
Does PostScript/Ghostscript use AFM file data or read the glyph widths or just from the glyph structure provided in PFA file?
The fonts and Fontmap file can be placed in several directories. Here is a typical search path:
/usr/share/ghostscript/9.52/Resource/Init/Fontmap
/usr/share/ghostscript/9.52/lib/Fontmap
/usr/share/ghostscript/9.52/Resource/Font/Fontmap
/usr/share/ghostscript/fonts/Fontmap
/usr/share/fonts/Type1/Fontmap
/usr/share/fonts/Fontmap
I sometimes use fonts that are not installed in the search path just in the current working directory. I use the gs -P and either of these work:
(font.pfa) 12 selectfont
/font.pfa 12 selectfont
The search path can also be modified by adding the directories to the GS_FONTPATH or GS_LIB environment variables.
The AFM file is not mandatory and the metrics can be obtained from the font alone. Some programs use the AFM file instead of the actual fonts and so they are needed for those programs.
You do, you just have the path/name slightly wrong:
/usr/share/ghostscript/9.50/Resource/Init/Fontmap.GS
You can also use your own custom fontmap using a command line parameter: "-sFONTMAP=/path/to/custom/fontmap" (best to copy the system one, and add your customisations to the copy)
You can't, not like that, anyway - that's not how Postscript works. Postscript always references fonts by name (not by file/path), so whilst there ways to read the font file(s), you still need to know the font name(s) in order to scale and set the font(s).
Ghostscript does not use AFM files, it gets the metrics from the fonts and glyph outlines.
Hope that helps some....
I am converting a .ttf/.otf font file reader in Lua 5.2 from Windows to MacOS and also want to add support for .suit font files which include ttf fonts.
Plain .ttf/.otf files now work fine, but already the reading of a .suit file doesn't work.
Any ideas on how to read the bytes of the .suit font on MacOS?
Does it have to do with a file name alias?
local input = assert(io.open("/Library/Fonts/Tahoma.ttf", "rb"))
local data=input:read("*all")
print(string.byte(data,1)) --prints the correct value 0
io.close(input)
local input = assert(io.open("/Library/Fonts/Maestro.suit", "rb"))
local data=input:read("*all")
print(string.byte(data,1)) --prints nothing
io.close(input)
The upper part (Tahoma) prints the correct first byte value 0, while the bottom part prints nothing, although I would have expected the value 0.
When I use string.len(data), it shows the correct value for Tahoma, but 0 for Maestro, although it should be something like 46k.
See https://apple.stackexchange.com/questions/8455 .suit is not a folder, but it can be addressed like a folder. To open the font part in the .suit file use:
local file=io.open("/Library/Fonts/Maestro.suit/..namedfork/rsrc","rb")
Does anyone know how to display a local image in markdown? I don't want to set up a webserver for that.
I try the following in markdown, but it doesn't work:
![image](files/Users/jzhang/Desktop/Isolated.png)
I suspect the path is not correct. As mentioned by user7412219 ubuntu and windows deal with path differently. Try to put the image in the same folder as your Notebook and use:
![alt text](Isolated.png "Title")
On windows the desktop should be at: C:\Users\jzhang\Desktop
The following works with a relative path to an image into a subfolder next to the document:
![image info](./pictures/image.png)
Solution for Unix-like operating system.
STEP BY STEP :
Create a directory named like Images and put all the images that will be rendered by the Markdown.
For example, put example.png into Images.
To load example.png that was located under the Images directory before.
![title](Images/example.png)
Note : Images directory must be located under the same directory of your markdown text file which has .md extension.
To add an image in markdown file the .md file and the image should be in the same directory. As in my case my .md file was in doc folder so i also moved the image into the same folder. After that write the following syntax in .md file
![alt text](filename)
like ![Car Image](car.png)
This has worked for me.
The best solution is to provide a path relative to the folder where the md document is located.
Probably a browser is in trouble when it tries to resolve the absolute path of a local file. That can be solved by accessing the file trough a webserver, but even in that situation, the image path has to be right.
Having a folder at the same level of the document, containing all the images, is the cleanest and safest solution.
It will load on GitHub, local, local webserver.
images_folder/img.jpg < works
/images_folder/img.jpg < this will work on webserver's only (please read the note!)
Using the absolute path, the image will be accessible only with a url like this: http://hostname.doesntmatter/image_folder/img.jpg
if image has bracket it won't display
![alt text](Isolated(1).png)
rename the image and remove brackets
![alt text](Isolated-1.png)
Update:
if you have spaces in the file path, you should consider renaming it too or if you use JavaScript you can encode it using
encodeURIComponent(imagePath)
Also, always try to save images and files alike with lowercase, please develop that habit, just my personal view though
Adding a local image worked for me by like so: ![alt text](file://IMG_20181123_115829.jpg)
Without the file:// prefix it did not work (Win10, Notepad++ with MarkdownViewer++ addon)
Edit: I found out it also works with html tags, and that is way better:
<img src="file://IMG_20181123_115829.jpg" alt="alt text" width="200"/>
Edit2: In Atom editor it only works without the file:// prefix. What a mess.
Depending on your tool - you can also inject HTML into markdown.
<img src="./img/Isolated.png">
This assumes your folder structure is:
├── img
└── Isolated.jpg
├── README.md
Edited:
Working for me ( for local image )
![system schema](doc/systemDiagram.jpg)
tree
├── doc
└── jobsSystemSchema.jpg
├── README.md
markdown file README.md is at the same level as doc directory.
In your case ,your markdown file should be at the same level as the directory files.
Working for me (absolute url with raw path)
![system schema](https://server/group/jobs/raw/master/doc/systemDiagram.jpg)
NOT working for me (url with blob path)
![system schema](https://server/group/jobs/blob/master/doc/systemDiagram.jpg)
Just add the relative image file route from the markdown file
![localImage](./client/src/assets/12.png)
This worked for me in ubuntu:
![Image](/home/gps/Pictures/test.png "a title")
Markdown file is in:
/home/gps/Documents/Markdown/
Image file is in:
/home/gps/Pictures/
To my knowledge, for VSCode on Linux, the local image can be normally displayed only when you put the image into the same folder as your .md post file.
i.e. only ![](image.jpg) or ![](./image.jpg) will work.
Even the absolute path like ![](/home/bala/image.jpg)also doesn't work.
In Jupyter Notebook Markdown, you can use
<img src="RelPathofFolder/File" style="width:800px;height:300px;">
Another possibility for not displayed local image is unintentional indent of the image reference - spaces before ![alt text](file).
This makes it 'code block' instead of 'image inclusion'. Just remove the leading spaces.
You may find following the syntax similar to reference links in markdown handy, especially when you have a text with many displays of the same image:
![optional text description of the image][number]
[number]: URL
For example:
![][1]
![This is an optional description][2]
[1]: /home/jerzy/ComputerScience/Parole/Screenshot_2020-10-13_11-53-29.png
[2]: /home/jerzy/ComputerScience/Parole/Screenshot_2020-10-13_11-53-30.png
I've had problems with inserting images in R Markdown. If I do the entire URL: C:/Users/Me/Desktop/Project/images/image.png it tends to work. Otherwise, I have to put the markdown in either the same directory as the image or in an ancestor directory to it. It appears that the declared knitting directory is ignored when referencing images.
Either put the image in the same folder as the markdown file or use a relative path to the image.
just copy the image and then paste it, you will get the output
![image.png](attachment:image.png)
The basic syntax is ![Image description](Any_Image_of_your_choice.png "title"). In my case, I used image name as Any\ Image\ of\ your\ choice.png in ![Image description](Any\ Image\ of\ your\ choice.png) instead of ![Image description](Any_Image_of_your_choice.png) and it was not working. So I would say make sure to check the image directory and also image name doesn't contain spaces if so use underscore(_) instead of space.
Faced issue while using markdown in Jupyter notebook in Ubuntu 18.04.
I got a solution:
a) Example Internet:
![image info e.g. Alt](URL Internet to Images.jpg "Image Description")
b) Example local Image:
![image Info](file:///<Path to your File><image>.jpg "Image Description")
![image Info](file:///C:/Users/<name>/Pictures/<image>.jpg "Image Description")
TurboByte
I am trying to add custom unicode font(http://www.freebanglafont.com/catetory.php?b=173) with Laravel TCPDF. But it throwing error like
"TCPDF ERROR: Could not include font definition file:"
My controller code:
$pdf->setFontSubsetting(true);
$fontname = TCPDF_FONTS::addTTFfont(public_path().'/fonts/SolaimanLipi.ttf', 'TrueTypeUnicode', '', 32);
$pdf->SetFont($fontname, '', 14, '', true);
$pdf->AddPage();
I have put my font in "public/fonts" and followed the documentation
http://www.tcpdf.org/fonts.php
Try placing your font in the tcpdf/fonts folder or setting the K_PATH_FONTS constant to the location of your font. Either way, it is unnecessary (and probably unwise) to keep your font folder in the public folder.
Check the TCPDF tools folder, there is a script for adding font. You will find the instruction and example in convert_fonts_examples.txt.
First, copy the .ttf font file in tcpdf\tools\
In a terminal go to tcpdf\tools folder run the following code
php tcpdf_addfont.php -b -t TrueTypeUnicode -i arial.ttf
Then, the script will notify you if the font was successfully added.
>>> Converting fonts for TCPDF:
*** Output dir set to ./TCPDF/fonts/
+++ OK : ./TCPDF/tools/arial.ttf added as arial
>>> Process successfully completed!
Then in you project try to use the added font.
Install / download / require the tcpdf library into your project.
Open the library folder (for example mine was: ./vendor/tecnickcom/tcpdf).
Notice and enter to the tools folder.
Copy the TTF file(s) into this tools folder.
Run this command from the terminal (still from the tools folder): $ PHP
tcpdf_addfont -i BOOKOS.TTF (Replace BOOKOS.TTF with your own fonts)
Repeat step (5) for each fonts desired.
Coding time..
To change between fonts from your php code, use the following scripts.
$pdf->SetFont($font_family = ‘bookos’, $variant = ‘’, $fontsize = 11);
How to (easily) get current file path in Sublime Text 3
I don't often use ST console (I used it only once to install package manager), but I suppose it could be good way to :
get current file path like some kind pwd command.
But it doesn't work.
Does anyone know an easy way to get current file path?
to clipboard : better not a strict objective in the answer
not necessary by ST command, maybe package?
Right click somewhere in the file (not on the title tab) --> Copy file path
If you don't want to use the mouse, you could set up a keyboard shortcut as explained here https://superuser.com/questions/636057/how-to-set-shortcut-for-copy-file-path-in-sublime-text-3
To easily copy the current file path, add the following to Key Bindings - User:
{ "keys": ["ctrl+alt+c"], "command": "copy_path" },
Source
Key Bindings - User can be opened via the command palette (command + p on OSX)
Easy to understand using image. On Right Click you will get this.
Transcribed code in image for convenience:
import sublime, sublime_plugin, os
class CopyFilenameCommand(sublime_plugin.TextCommand):
def run(self, edit):
if len(self.view.file_name()) > 0:
filename = os.path.split(self.view.file_name())[1]
sublime.set_clipboard(filename)
sublime.status_message("Copied file name: %s" % filename)
def is_enabled(self):
return self.view.file_name()... # can't see
Mac OS X - Sublime Text 3
Right click > Copy File Path
A lot of these answers involve touching the mouse. Here's how to do get the path without any mouse clicks using SideBarEnhancements
Install SideBarEnhancements using PackageControl.
Click super + shift + P to open the command palette
In the command palette begin typing path until you see File: Copy Path
Select File: Copy Path
Now the path to file you are working in is copied into your clipboard.
There is a Sublime Package which gives your current file location inside a status bar. I just cloned them directly to my /sublime-text-3/Packages folder.
git clone git#github.com:shagabutdinov/sublime-shell-status.git ShellStatus;
git clone git#github.com:shagabutdinov/sublime-status-message.git StatusMessage;
You have to check/read the description on GitHub. Even it is listed in package control it would not install properly for me. You can actually edit the shell output as you want. If you have the right skills with python/shell.
Looks like this (Material Theme)
If you're like me and always click on items in the sidebar just to realize that copying the path only works when clicking in the editor area, have a look at the SideBarEnhancements package. It has a huge bunch of options to copy file paths in a variety of different ways.
Installation is available via Package Control (despite the webpage only mentions installation via manual download).
Note: The package “sends basic, anonymous statistics”. The webpage explains how to opt out from that.
Go to this link. The code in the link is given by robertcollier4.
Create a file named CpoyFileName.py or whatever you like with .py extension.
Save the file in Sublime Text 3\Packages\User folder. Then paste the above given key bindings in your Preferences: Key Bindings file.
Now, you can use the specified key bindings to copy just filename or total (absolute) filepath.
Please note that the filename or filepath do contain file extension.
Fastest Solution ( No Packages Needed + Comprehensive ):
Folder Path:
Folder in "Sidebar"
Right Click
"Find In Folder"
"Where" field contains everything you need
File Path:
File in current "Tab"
Right Click
"Copy File Path"