How can I convert a .ps file into a .png file? - python

I need to convert .ps files to .png files as part of an image recognition program I am making. I know I can use Ghostscript or other programs, but could someone give a specific example of how to write something like this:
def ps_to_png(ps_file):
file = ghostscript.read(ps_file)
png_file = ghostscript.save(file, "png")
return png_file
(This code is pseudo code- I want to know how to write something that actually does what this code looks like it will do.)
Thanks in advance! Stack is a great community and I appreciate it.
EDIT (Attempted solutions): When running this line:
os.system("ghostscript file.ps file.png")
I get the following Error:
'ghostscript' is not recognized as an internal or external command, operable program or batch file.
When attempting to use Pillow:
from PIL import Image
def convert_to_png(ps_file):
img = Image.open(ps_file)
img.save("img.png")
I get the following error:
OSError: Unable to locate Ghostscript on paths

You can use Pillow.
from PIL import Image
psimage=Image.open('myImage.ps')
psimage.save('myImage.png')
If you want to wrap it to a function:
from PIL import Image
def convert_to_png(path):
img = Image.open(path)
img.save("img.png")
path='/path_to_your_file'
convert_to_png(path)

Related

Is there a way of attaching an image on a python code in such a way that it becomes part of the soure code?

I'm a beginner in python and I'm trying to send someone my small python program together with a picture that'll display when the code is run.
I tried to first convert the image to a binary file thinking that I'd be able to paste it in the source code but I'm not sure if that's even possible as I failed to successfully do it.
You can base64-encode your JPEG/PNG image which will make it into a regular (non-binary string) like this:
base64 -w0 IMAGE.JPG
Then you want to get the result into a Python variable, so repeat the command but copy the output to your clipboard:
base64 -w0 IMAGE.JPG | xclip -selection clipboard # Linux
base64 -w0 IMAGE.JPG | pbcopy # macOS
Now start Python and make a variable called img and paste the clipboard into it:
img = 'PASTE'
It will look like this:
img = '/9j/4AAQSk...' # if your image was JPEG
img = 'iVBORw0KGg...' # if your image was PNG
Now do some imports:
from PIL import Image
import base64
import io
# Make PIL Image from base64 string
pilImage = Image.open(io.BytesIO(base64.b64decode(img)))
Now you can do what you like with your image:
# Print its description and size
print(pilImage)
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=200x100>
# Save it to local disk
pilImage.save('result.jpg')
You can save a picture in byte format inside a variable in your program. You can then convert the bytes back into a file-like object using the BytesIO function of the io module and plot that object using the Image module from the Pillow library.
import io
import PIL.Image
with open("filename.png", "rb") as file:
img_binary = file.read()
img = PIL.Image.open(io.BytesIO(img_binary))
img.show()
To save the binary data inside your program without having to read from the source file you need to encode it with something like base64, use print() and then simply copy the output into a new variable and remove the file reading operation from your code.
That would look like this:
img_encoded = base64.encodebytes(img_binary)
print(img_binary)
img_encoded = " " # paste the output from the console into the variable
the output will be very long, especially if you are using a big image. I only used a very small png for testing.
This is how the program should look like at the end:
import io
import base64
import PIL.Image
# with open("filename.png", "rb") as file:
# img_binary = file.read()
# img_encoded = base64.encodebytes(img_binary)
img_encoded = b'iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABX[...]'
img = PIL.Image.open(io.BytesIO(base64.decodebytes(img_encoded)))
img.show()
You could perhaps have your Python program download the image from a site where you upload files such as Google Drive, Mega, or Imgur. That way, you can always access and view the image easily without the need of running the program or for example converting the binary back into the image in the method you mentioned.
Otherwise, you could always store the image as bytes in a variable and have your program read this variable. I'm assuming that you really wish to do it this way as it would be easier to distribute as there is only one file that needs to be downloaded and run.
Or you could take a look at pyinstaller which is made for python programs to be easily distributed across machines without the need to install Python by packaging it as an executable (.exe) file! That way you can include the image file together by embedding it into the program. There are plenty of tutorials for pyinstaller you could google up. Note: Include the '--onefile' in your parameters when running pyinstaller as this will package the executable into a single file that the person you're sending it to can easily open whoever it may be-- granted the executable file can run on the user's operating system. :)

Python Pillow Image.show() Path Issue?

Honest warning—I'm a total beginner.
I'm using Python 3.8.2 in IDLE and sometimes in Spyder.
My goal: to open an image (located in a folder) in Preview using Pillow
My code:
from PIL import Image
my_image = Image.open("flower.jpg")
my_image.show(r"/Users/User/Desktop/flower.jpg")
I run this, and it works! But it only works if the jpg is on the Desktop. I want to put the image in a folder. So I changed my last line of code to something like this:
my_image.show(r"/Users/User/Desktop/folder/flower.jpg")
I put the image in the folder, run the program, and get this error:
**FileNotFoundError: [Errno 2] No such file or directory: 'flower.jpg'**
Oddly, if I put the jpg back onto the Desktop and still use the path with "folder" in it, the program runs successfully and shows me the image.
Is this a problem with the path? How can I use Image.show() to open an image that is located somewhere other than the Desktop?
Thank you!
If you want to open and view an image using an absolute path, you'll have to change this line:
my_image = Image.open(path_to_image_dir)
You've incorrectly passed a string to PIL.Image.show. This doesn't throw an error, since PIL.Image.show happens to take an optional string parameter title, which it will use as a title in the image window. Don't pass any parameters to show, and change "flower.jpg" in the line above to the actual path.

Python qrcode module not being saved

If I run this:
import qrcode
img = qrcode.make('Some data here')
I don't know where it saves the actual image. I've tried CD'ing to a path and run the Python code, I have had the script in a directory. But when running the code above it doesn't create a QR image file in the directory. Where is it saved?!
I've tried running qr "Some data here" > test.png from the command-line which works perfectly. But not the module itself for some reason.
The make function doesn't output an image. For that you have to do something like this after running that function:
img = qr.make_image(fill_color="black", back_color="white")
Read the docs.

Issue with removing files in python

I'm currently having some issues removing a file in python. I am creating a temporary file for pdf to image conversion. It is housed in a folder that holds a .ppm file and converts it to a .jpg file. It then deletes the temporary .ppm file. Here is the code:
import pdf2image
from PIL import Image
import os
images = pdf2image.convert_from_path('Path to pdf.pdf', output_folder='./folder name')
file = ''
for files in os.listdir('./folder name'):
if files.endswith(".ppm"):
file = files
path = os.path.join('folder name',file)
im = Image.open(path)
im.save("Path to image.jpg")
im.close()
os.remove(path)
The issue is at the end in the os.remove(path). I get the following error:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'path to ppm file'
I would appreciate any help and thanks in advance.
Not really the answer to your question, but you can just output in the correct format at the start, and avoid the issue in the first place:
pdf2image.convert_from_path('Path to pdf.pdf', output_folder='./folder name', fmt='jpg')
To actually answer your question, I'm not sure why you're having the issue, because really the close() should prevent this problem. Perhaps check out this answer and try using a with statement? Or maybe the permissions release is just delayed, I'm curious what throwing that remove in a loop for as long as it throws an exception would do.
Edit: To set the name, you'll want to do something like:
images = pdf2image.convert_from_path('Path to pdf.pdf', output_folder='./folder name', fmt='jpg')
for image in images:
# Save the image
The pdf2image documentation looks like it recommends using a temporary folder, like in this example, and then you can just .save(...) the PIL image:
import tempfile
with tempfile.TemporaryDirectory() as path:
images_from_path = convert_from_path('/home/kankroc/example.pdf', output_folder=path)
# Do something here
Edit: I realized that the reason it was in use is probably because you need to close() all the images in images. You should read up on the pdf2image documentation and about the PIL images that it spits out for more details.

Using MemoryFS file-like object with PIL Image

I'm trying to open Image file from PyFileSystem MemoryFS using PIL, I tried to do that like this example and i got the error below:
from PIL import Image
from fs.memoryfs import MemoryFS
fs=MemoryFS()
fs.makedir("test")
out=fs.open("test/file.jpg",'wb')
out.write(someimagefile.read())
out.close()
in=fs.open("test/file.jpg",'rb')
im=Image.open(in) #error: cannot identify image file <IO wrapper for <MemoryFile in <MemoryFS> test/file.jpg>>
however if I don't use a directory (ex. out=fs.open("file.jpg",'wb')) It does work as expected.
What am I doing wrong?
Thanks for your help.
I already get an error using the following line:
from fs.memoryfs import MemoryFS
Probably I don't have that library installed. Do you need this library? You can just open the image without opening it with MemoryFS:
im = Image.open("test/file.jpg")
Side note: I wouldn't use in as variable name, since it is also a Python keyword.

Categories