Need help saving in PyMuPDF - python-3.x

This is a basic script that should insert a watermark image on the first page of a PDF and save it under a new name.
I could do the same with the same files in pdfrw, but I'm stuck with PyMuPDF (which I would prefer to use...).
The py file is in the same folder with the pdf and the png.
import fitz
input_file = "sample.pdf"
output_file = "sample_stamped.pdf"
stamp = "watermark.png"
doc = fitz.open(input_file)
rect = fitz.Rect(0, 0, 100, 100)
pix = fitz.Pixmap(stamp)
page = doc[0]
page.insertImage(rect, pixmap = pix, overlay = True)
doc.save(output_file)
I'm getting this error msg:
Traceback (most recent call last):
File "D:/Google Drive/Python/PDF/pdfstamp.py", line 14, in <module>
doc.save(output_file)
File "D:\Python\lib\site-packages\fitz\fitz.py", line 2411, in save
return _fitz.Document_save(self, filename, garbage, clean, deflate, incremental, ascii, expand, linear, pretty, decrypt)
RuntimeError: not a dict (array)
Thanks in advance for any help.

Related

How to fix AttributeError: 'Image' object has no attribute 'seek'. Did you mean: 'seed'?

I am trying to create a pptx or powerpoint file using python-pptx and reading the image using python wand library but getting error like AttributeError: 'Image' object has no attribute 'seek'. Did you mean: 'seed'?
Note: All the files are in same folder starts with 'watermarked_'
from io import FileIO
import os
from wand.image import Image
from pptx.util import Inches
from pptx import Presentation
def create_slide()->FileIO:
# Creating presentation object
root = Presentation()
for file in os.listdir():
if file.startswith('watermarked_'):
# Creating slide layout
first_slide_layout = root.slide_layouts[1]
slide = root.slides.add_slide(first_slide_layout)
shapes = slide.shapes
#Adding title or heading to the slide
title_shape = shapes.title
title_shape.text = f" Created By python-pptx for Watermarking "
#Adding sub-title with border to the slide
body_shape = shapes.placeholders[1]
tf = body_shape.text_frame
tf.text = f"This is a watermarked image of {file}"
with Image(filename = file) as watermarked_image:
#Maintianing the aspect ratio of the image
width, height = watermarked_image.size
ratio = height/width
new_width = width / 2
new_height = int(new_width * ratio)
watermarked_image.resize(int(new_width), new_height)
# Add the watermarked image to the slide
slide.shapes.add_picture(watermarked_image ,Inches(1), Inches(3))
root.save("Output.pptx")
create_slide()
Traceback (most recent call last):
File "/Users/quantum/Desktop/image/project.py", line 60, in <module>
quantum#MacBook-Air image % python -u "/Users/quantum/Desktop/image/project.py"
Traceback (most recent call last):
File "/Users/quantum/Desktop/image/project.py", line 60, in <module>
create_slide()
File "/Users/quantum/Desktop/image/project.py", line 57, in create_slide
slide.shapes.add_picture(watermarked_image ,Inches(1), Inches(3))
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pptx/shapes/shapetree.py", line 332, in add_picture
image_part, rId = self.part.get_or_add_image_part(image_file)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pptx/parts/slide.py", line 39, in get_or_add_image_part
image_part = self._package.get_or_add_image_part(image_file)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pptx/package.py", line 36, in get_or_add_image_part
return self._image_parts.get_or_add_image_part(image_file)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pptx/package.py", line 151, in get_or_add_image_part
image = Image.from_file(image_file)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pptx/parts/image.py", line 168, in from_file
if callable(getattr(image_file, "seek")):
AttributeError: 'Image' object has no attribute 'seek'. Did you mean: 'seed'?
Any frequent help will be much appreciated
A wand.image.Image object is not a valid argument for Shapes.add_picture(). The first argument to that call needs to be the str path to an image file or a file-like object containing an image.
I suppose that means you'll need to save the modified image as a JPG or PNG or whatever and then provide the filename. You could also save it to a BytesIO object and pass that to .add_picture() as that would count as a file-like object and not require using the filesystem.

PIL.UnidentifiedImageError: cannot identify image file

I'm working on GCP cloud functions and intend to write a functions which combines two images. But I', getting the following error when I invoke the function:
Traceback (most recent call last): File
"/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py",
line 346, in run_http_function result =
_function_handler.invoke_user_function(flask.request) File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py",
line 217, in invoke_user_function return
call_user_function(request_or_event) File
"/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py",
line 210, in call_user_function return
self._user_function(request_or_event) File "/user_code/main.py", line
74, in execute newIntro= generateIntroImage(nameMappings['stdName'],
nameMappings['stdPicture'], nameMappings['logo'],
nameMappings['stdYear'], nameMappings['font']) File
"/user_code/main.py", line 12, in generateIntroImage
images.append(Image.open(logo)) File
"/env/local/lib/python3.7/site-packages/PIL/Image.py", line 2862, in
open "cannot identify image file %r" % (filename if filename else fp)
PIL.UnidentifiedImageError: cannot identify image file '/tmp/logo.jpg'
I have ran this function on my local machine and it works as expected but when I deploy it on GCP, it gives this error and crashes. Here's my function:
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
def generateIntroImage(stdName, stdPicture, logo, year, typeFace):
images = [Image.open(x) for x in [stdPicture, logo]]
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
font= ImageFont.truetype(typeFace, 70)
draw= ImageDraw.Draw(new_im)
draw.text((0, 0), stdName+"'s " +year+" Year Book", (0,0,0),font= font)
fileName= "/tmp/test.jpg"
new_im.save(fileName)
return fileName
These images are .jpg and .png files. Any idea what could be wrong?
Happened to me on Google Colab as well, apparently updating PIL version fixed the problem for me.
PIL throws error because it cannot identify the image format. Most probably the reason is that the image is corrupted and hence cannot be read (or "identified") by pillow's Image.open(). For example if you try opening the image in an IPython prompt, it would fail as well.
In [2]: from PIL import Image
In [3]: Image.open("176678612.jpg")
---------------------------------------------------------------------------
UnidentifiedImageError Traceback (most recent call last)
<ipython-input-3-3f91b2f4e49a> in <module>
----> 1 Image.open("176678612.jpg")
/opt/conda/envs/swin/lib/python3.7/site-packages/PIL/Image.py in open(fp, mode, formats)
3022 warnings.warn(message)
3023 raise UnidentifiedImageError(
-> 3024 "cannot identify image file %r" % (filename if filename else fp)
3025 )
3026
UnidentifiedImageError: cannot identify image file '176678612.jpg'
And the relevant piece of code handling this check is from PIL.Image.open()
"""
exception PIL.UnidentifiedImageError: If the image cannot be opened and
identified.
"""
raise UnidentifiedImageError(
"cannot identify image file %r" % (filename if filename else fp)
So, the fix is to delete the image, or replace it with an uncorrupted version.
you need to provide a downloadable link to the image. What worked for me was click on the download image and the copy that URL.

Resize image in Tkinter

So, I need to resize an image in tkinter. Before you do anything - this is not a duplicate. I have gone through every other question on this site and none have helped me. The thing with me is - I don't wan't to save the image. I need to load the image, resize it, then display it with PhotoImage in a label. I tried to use ImageTk, but for some reason it won't work.
Here's my code with ImageTk:
from tkinter import *
import PIL
from PIL import Image, ImageTk
root = Tk()
left_nose_path_white = Image.open(r'C:\Users\User\Documents\Python stuff\Other apps\Veteris\Dog photos\Advanced\Sides\GIF\Nose\Nose (left) - White.gif')
def resize_image():
global left_nose_path_white
total_screen_width = root.winfo_screenwidth()
total_screen_height = root.winfo_screenheight()
frame_width, frame_height = left_nose_path_white.size
dog_new_width = int(frame_width / 3)
dog_new_height = int(frame_height / 3)
left_nose_path_white = left_nose_path_white.resize((dog_new_width, dog_new_height), Image.LANCZOS)
resize_image()
left_nose_img_white = ImageTk.PhotoImage(file = left_nose_path_white)
label = Label(image = left_nose_img_white)
label.pack()
root.mainloop()
This returns the error:
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 124, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
My code should find the width and height of the original image, divide it by 3, and then show it. The reason I don't want to have to save the image is because the user will open the application several times.
I'm new to using PILL/Pillow, so the answer may be obvious.
I have Pillow installed using pip.
I only have one version of Python on my computer (Python 3.7)
Full Error:
Traceback (most recent call last):
File "C:\Users\User\Documents\Python stuff\Other apps\Veteris\Scripts\Veteris_program.py", line 230, in <module>
left_nose_img_white = ImageTk.PhotoImage(file = left_nose_path_white)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 95, in __init__
image = _get_image_from_kw(kw)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 64, in _get_image_from_kw
return Image.open(source)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 2779, in open
prefix = fp.read(16)
AttributeError: 'Image' object has no attribute 'read'
Exception ignored in: <function PhotoImage.__del__ at 0x000002B0A8A49950>
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 124, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
Thanks for the help!

How to load Textures in Pyglet and Ratcave

I am making a simple OpenGL 3.3 OBJ viewer in Python using the modules Pyglet and Ratcave. I want to load a textured sphere I made in Blender. While my Pyglet/Ratcave OBJ viewer loads untextured OBJ files, when I add textures to my project, I get this error and the program fails to load:
ValueError: could not convert string to float: 'textures'
What does this mean?
I got a different error when I tried to import textures from my OneDrive folder and use them in my Blender project. When I put the textures in the same folder as the script and OBJ/MTL files, it got rid of that error, but now I can't load the textures because, for whatever reason, Ratcave needs to convert the textures to a float and it can't do that.
import pyglet
import ratcave as rc
import time
window = pyglet.window.Window()
def update(dt):
pass
pyglet.clock.schedule(update)
# Insert filename into WavefrontReader
obj_filename = 'Textured Sphere Eevee.obj'
obj_reader = rc.WavefrontReader(obj_filename)
# Check which meshes can be found inside the Wavefront file, and extract it into a Mesh object for rendering
print(obj_reader.bodies.keys())
Sphere = obj_reader.get_mesh("Cube")
Sphere.position.xyz = 0, 0, -10
scene= rc.Scene(meshes=[Sphere])
#window.event
def on_draw():
with rc.default_shader:
scene.draw()
#scene.clear()
#time.sleep(10)
pyglet.app.run()
Traceback (most recent call last):
File "C:\Users\Jeffery\Desktop\Art\Pyglet Game Engine\scripts\Ratcave_OBJ_Loader_Test 2.py", line 15, in <module>
obj_reader = rc.WavefrontReader(obj_filename)
File "C:\Users\Jeffery\AppData\Local\Programs\Python\Python37-32\lib\site-packages\ratcave\wavefront.py", line 28, in __init__
self.bodies = read_wavefront(file_name)
File "C:\Users\Jeffery\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wavefront_reader\reading.py", line 114, in read_wavefront
materials = read_mtlfile(path.join(path.dirname(fname_obj), fname_mtl))
File "C:\Users\Jeffery\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wavefront_reader\reading.py", line 88, in read_mtlfile
material[prefix] = tuple(float(d) for d in split_data)
File "C:\Users\Jeffery\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wavefront_reader\reading.py", line 88, in <genexpr>
material[prefix] = tuple(float(d) for d in split_data)
ValueError: could not convert string to float: 'textures'

Error when Unzipping with Pyside Qtgui

When I run my program, I get the following error and am not sure on how to correct it. Can someone help with explaining what this error is and how to correct it? Newb here so details are appreciated. Thanks for your time in advance!
Code:
#!/usr/bin/python
import zipfile
from PySide import QtGui
import re
#Select file to extract
app = QtGui.QApplication([])
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.AnyFile)
if (dialog.exec()):
fileName = dialog.selectedFiles()
#Select Directory to extract to
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.Directory)
dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
if (dialog.exec()):
dirName = dialog.selectedFiles()
print("Extracting.....")
zFile= zipfile.ZipFile(fileName)
zFile.extractall(dirName)
Error output:
Traceback (most recent call last):
File "C:\Users\Jennifer\Documents\BatchScripts\unzip.py", line 22, in <module>
zFile= zipfile.ZipFile(fileName)
File "C:\Python33\lib\zipfile.py", line 933, in __init__
self._RealGetContents()
File "C:\Python33\lib\zipfile.py", line 970, in _RealGetContents
endrec = _EndRecData(fp)
File "C:\Python33\lib\zipfile.py", line 237, in _EndRecData
fpin.seek(0, 2)
AttributeError: 'list' object has no attribute 'seek'
In your file and target directory code blocks, dialog.selectedFiles() returns a list. zipfile.ZipFile can only handle one file at a time, hence your error. To iterate over the list being provided by dialog.selectedFiles(), use the following:
for archive in fileName: # you should probably change it to fileNames to reflect its true nature
zfile = zipfile.ZipFile(archive)
print("Extracting " + str(zfile.filename) + "...")
zfile.extractall(dirName[0]) # also a list, extract to first item and ignore rest
and you should be all set.

Resources