Attempted to use a piece of code from other questions on Stack Overflow. Ran into this piece of code:
from PIL import ImageFont
from urllib.request import urlopen
truetype_url = 'https://github.com/googlefonts/roboto/blob/main/src/hinted/Roboto-Black.ttf'
font = ImageFont.truetype(urlopen(truetype_url), size=10)
I got this error:
OSError: unknown file format
I tried other suggestions such as reinstalling PIL, using requests.get and I receive the same error. I checked the link and it does take you to the item in question. Are there other suggestions I can try?
My Goal:
Be able to take a font from a link so I do not have to do this locally on my computer.
Thanks!
You can do it like this:
from PIL import Image, ImageFont, ImageDraw
import requests
import io
# Load font from URI
truetype_url = 'https://github.com/googlefonts/roboto/blob/main/src/hinted/Roboto-Black.ttf?raw=true'
r = requests.get(truetype_url, allow_redirects=True)
font = ImageFont.truetype(io.BytesIO(r.content), size=24)
# Create a black canvas and get drawing context
canvas = Image.new('RGB', (300,180))
draw = ImageDraw.Draw(canvas)
# Write in our font
draw.text((10, 10), "Got that crazy font", font=font, fill=(255,255,255))
canvas.save('result.png')
As Karl points out in the comments, you can do it with urllib as you were originally intending like this:
from urllib.request import urlopen
truetype_url = 'https://github.com/googlefonts/roboto/blob/main/src/hinted/Roboto-Black.ttf?raw=true'
font = ImageFont.truetype(urlopen(truetype_url), size=10)
Related
I am making a scraper for my personal use that takes screenshots and saves them to a pdf. I am using pyscreenshot to take the screenshot and this returns a PIL image (PIL.PngImagePlugin.PngImageFile to be precise). I am using FPDF to make the pdf and can use the image method to add an image to the pdf.
The trouble is, this takes in either a file path or a URL. It is my understanding that saving many things to the disk will cause wear, so ideally I would like to save the image to the pdf straight from the PIL object instead of saving the image first. I'll be taking around 1500 screenshots, is this an unnecessary worry?
I am using Ubuntu if that changes anything. Here are the docs for the image method: https://pyfpdf.readthedocs.io/en/latest/reference/image/index.html
Here are the relevant parts of my code.
import pyscreenshot as ImageGrab
from fpdf import FPDF
def get_page_image():
page_image = ImageGrab.grab(bbox = half_page_bbox)
page_image.save("Test image 1.png")
return image
half_page_bbox = (249, 1, 1672, 1028)
pdf = FPDF("P", "mm", "A4")
pdf.add_page()
page_image = get_page_image()
pdf.image("Test image 1.png", 10, 10, 100)
pdf.output("My pdf.pdf")
I have tried using io to save it in memory, but this isn't working. Here is my code followed by the error.
import io
tmpFile = io.BytesIO()
image.save(tmpFile, format='png')
tmpFile.seek(0)
pdf.image(tmpFile, 10, 10, 100)
in <module>
pdf.image(tmpFile, 10, 10, 100)
File "/home/henry/.local/lib/python3.8/site-packages/fpdf/fpdf.py", line 150, in wrapper
return fn(self, *args, **kwargs)
File "/home/henry/.local/lib/python3.8/site-packages/fpdf/fpdf.py", line 963, in image
pos=name.rfind('.')
AttributeError: '_io.BytesIO' object has no attribute 'rfind'
You can do the following, note that I'm using fpdf2 instead of fpdf
pip install fpdf2
import pyscreenshot as ImageGrab
from fpdf import FPDF
img = ImageGrab.grab()
pdf = FPDF("P", "mm", "A4")
pdf.add_page()
pdf.image(img, 10, 10, 100)
pdf.output('My pdf.pdf')
I'm trying to take a screen grab with PILLOW and reading text from it using pytesseract but I keep seeing a "AttributeError: read". I've tried to read the documentation and google but haven't found anything.
from PIL import ImageGrab
from PIL import Image
import PIL
snapShot = PIL.ImageGrab.grab(0, 0, 500, 500) #takes screenshot and stores it temporarily
pyt.pytesseract.tesseract_cmd = r'C:\Users\user\Desktop\project\venv\Scripts\pytesseract.exe' #locate pytesseract exe
im = Image.open(snapShot)
text = pyt.image_to_string(im)
print(text)
Error code:
File "C:\Users\user\Desktop\project\venv\lib\site-packages\PIL\Image.py", line 519, in __getattr__
raise AttributeError(name)
AttributeError: read
As a comment pointed out the use of 'Image.open()' on a Image object causes the error. Removing this gave another error however 'PermissionError: [WinError 5] Access is denied' which was resolved by installing the tesseract client on top of the pytesseract package and pointing to it.
from PIL import ImageGrab
import PIL
snapShot = PIL.ImageGrab.grab(0, 0, 500, 500) #takes screenshot and stores it temporarily
pyt.pytesseract.tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract\tesseract.exe' #default path to tesseract client executable
text = pyt.image_to_string(snapshot)
print(text)
from PIL import Image, ImageDraw, ImageFont
import glob
import os
images = glob.glob("directory_path/*.jpg")
for img in images:
images = Image.open(img)
draw = ImageDraw.Draw(images)
font = ImageFont.load_default() #Downloaded Font from Google font
text = "Text on all images from directory"
draw.text((0,150),text,(250,250,250),font=font)
images.save(img)
I have to put text on all images , I have tried above code but its not working
This code worked for me just fine, but the text was hard to read because it was small and white. I did change directory_path to images and put my images in there. The images looked like this, the text is small and on the left side:
Here is the solution
from PIL import Image,ImageDraw,ImageFont
import glob
import os
images=glob.glob("path/*.jpg")
for img in images:
images=Image.open(img)
draw=ImageDraw.Draw(images)
font=ImageFont.load_default()
text="Whatever text"
draw.text((0,240),text,(250,250,250),font=font)
images.save(img)
one possible problem with the code may be that you are using the images variable for saving the list of images and also to iterate through the images.
Try this code, this will work for sure.
from PIL import Image, ImageDraw, ImageFont
import glob
import os
images = glob.glob("new_dir/*.jpg")
print(images)
for img in images:
image = Image.open(img)
draw = ImageDraw.Draw(image)
font = ImageFont.load_default() #Downloaded Font from Google font
text = "Text on all images from directory"
draw.text((0,150),text,fill = 'red' ,font=font)
image.save(img)
I'm new to Jython (but not to Python) and I'm trying to get the dimensions of an image from a URL.
For example the input would be https://www.w3schools.com/w3images/fjords.jpg
and it would return (600, 400).
I know in Python it can be done with PIL:
from PIL import Image
from io import BytesIO
import requests
data = requests.get(url).content
im = Image.open(BytesIO(data))
print(im.size)
But how to do this in Jython since PIL is not supported by Jython?
You can use the ImageIO class.
from java.net import URL
from javax.imageio import ImageIO
img = ImageIO.read(URL("https://www.w3schools.com/w3images/fjords.jpg"))
print img.getWidth()
print img.getHeight()
I am writing python code to take an image from the web and calculate the standard deviation, ... and do other image processing with it. I have the following code:
from scipy import ndimage
from urllib2 import urlopen
from urllib import urlretrieve
import urllib2
import Image
import ImageFilter
def imagesd(imagelist):
for imageurl in imagelist:
opener1 = urllib2.build_opener()
page1 = opener1.open(imageurl)
im = page1.read()
#localfile = urlretrieve(
#img = Image.fromstring("RGBA", (1,1), page1.read())
#img = list(im.getdata())
# page1.read()
print img
#standard_deviation(p
Now I keep going back and forth because I am not sure how to take the image directly from the web, without saving it to disk, and passing it to the standard deviation function.
Any hints/help would be greatly appreciated.
Thanks.
PIL (Python Imaging Library) methods "fromstring" and "frombuffer" expect the image data in a raw, uncompacted, format.
When you do page1.read() you get the binary file data. In order to have PIL understanding it, you have to make this data mimick a file, and pass it to the "Image.open" method, which understands the file format as it is read from the web (i.e., the .jpg, gif, or .png data instead of raw pixel values)
Try something like this:
from cStringIO import StringIO
(...)
data = StringIO(page1.read())
img = Image.open(data)