today I was making some code that will resize a few images that already been uploaded. It is actually a def function and called when the button is pressed on the Odoo web client.
Code:
#api.multi
def resize_image(self):
for record in self:
Image.open(self.foto1).resize((800, 600),Image.ANTIALIAS).save(self.foto1, quality=100)
Error:
File "/opt/odoo/addons/asset/asset.py", line 209, in resize_image
Image.open(self.foto1).resize((800, 600),Image.ANTIALIAS).save(self.foto1, quality=100)
IOError: [Errno 36] File name too long: '/9j/4AAQSkZJRgABAQEASABIAAD/7QFKUGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAREcAVoAAxslRxwCAAACAAIcAhkAJkFGLVMgR
I can't give all the error file name because it's probably the byte itself...
import cStringIO
#api.multi
def resize_image(self):
for record in self:
Image.open(cStringIO.StringIO(self.foto1.decode('base64'))).resize((800, 600),Image.ANTIALIAS).save(self.foto1, quality=100)
Related
I am trying to read a png file into a python-flask application running in docker and am getting an error that says
ValueError: Could not find a format to read the specified file in mode
'i'
i have uploaded a file using an HTML file and now i am trying to read it for further processing. i see that scipy.misc.imread is deprecated and i am trying to replace this with imageio.imread
if request.method=='POST':
file = request.files['image']
if not file:
return render_template('index.html', label="No file")
#img = misc.imread(file)
img = imageio.imread(file)
i get this error :
File "./appimclass.py", line 34, in make_prediction
img = imageio.imread(file)
File "/usr/local/lib/python3.6/site-packages/imageio/core/functions.py", line 221, in imread
reader = read(uri, format, "i", **kwargs)
File "/usr/local/lib/python3.6/site-packages/imageio/core/functions.py", line 139, in get_reader
"Could not find a format to read the specified file " "in mode %r" % mode
Different, but in case helpful. I had an identical error in a different library (skimage), and the solution was to add an extra 'plugin' parameter like so -
image = io.imread(filename,plugin='matplotlib')
Had the exact same problem recently, and the issue was a single corrupt file. Best is to use something like PIL to check for bad files.
import os
from os import listdir
from PIL import Image
dir_path = "/path/"
for filename in listdir(dir_path):
if filename.endswith('.jpg'):
try:
img = Image.open(dir_path+"\\"+filename) # open the image file
img.verify() # verify that it is, in fact an image
except (IOError, SyntaxError) as e:
print('Bad file:', filename)
#os.remove(dir_path+"\\"+filename) (Maybe)
I had this problem today, and found that if I closed the file before reading it into imageio the problem went away.
Error was:
File "/home/vinny/pvenvs/chess/lib/python3.6/site-packages/imageio/core/functions.py", line 139, in get_reader "Could not find a format to read the specified file " "in mode %r" % mode ValueError: Could not find a format to read the specified file in mode 'i'
Solution:
Put file.close() before images.append(imageio.imread(filename)), not after.
Add the option "pilmode":
imageio.imread(filename,pilmode="RGB")
It worked for me.
I encountered the same error, and at last, I found it was because the picture was damaged.
I had accidentally saved some images as PDF, so the error occurred. resolved after deleting those incompatible format images.
def open_file():
b_text.set("Loading")
files = askopenfile(initialdir = ".",parent=root ,title="choose a video",filetype=[("Video Files","*.mp4")])
if files:
print("File was loaded")
files.without_audio().preview()
This is the error i am facing
Traceback (most recent call last):
File "C:\Users\felix\anaconda3\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "c:/Users/felix/Desktop/video editor/new.py", line 27, in open_file
b=Button(root,textvariable=b_text,relief=GROOVE,bg="#232323",fg="white", command=open_file)
AttributeError: '_io.TextIOWrapper' object has no attribute 'without_audio'
You must execute VideoFileClip before previewing.
The method askopenfile selects a file.
Execute clip = VideoFileClip(file.name) for creating VideoFileClip object.
Then you can execute clip.without_audio().preview().
For more details see: MoviePy – Previewing a Video Clip.
When executing the code, I was getting an error message:
clip.preview requires Pygame installed
I has to install pygame.
Here is a code sample for selecting and previewing a video file:
from tkinter.filedialog import askopenfile
from moviepy.editor import *
file = askopenfile(initialdir = ".", title="choose a video", filetype=[("Video Files","*.mp4")])
if file:
print("File was loaded")
# https://www.geeksforgeeks.org/moviepy-previewing-a-video-clip/
# Loading video file
clip = VideoFileClip(file.name)
# previewing the clip at fps = 10
clip.without_audio().preview(fps=10)
Note:
Since the example is "stand alone" application, I had to remove the parent argument (but you should keep the parent=root argument).
I'm currently trying to write a simple Python (3.6.6) program that can grab a Youtube video, play it back, and graph the waveplot and spectogram of the file. But it only runs properly in Jupyter notebook. I'm using this site as a guide on the program. I want to make sure it can run in IDLE as well, but so far no luck. Here's the code section regarding the file retrieval / path set and trying to play it back:
# Downloading audio
audiostream = video.getbestaudio()
# audiostream.download()
from tkinter import filedialog as fd
# Asking where to save it
print("Select the directory...")
dir_name = fd.askdirectory()
print(dir_name)
path = dir_name + "/" + video.title + ".wav"
print(path)
audiofile = audiostream.download(filepath=path)
import IPython.display as ipd
# Playing back the audio
print("Playing back audio...")
ipd.Audio(filename=path)
And the error message:
Traceback (most recent call last):
File "C:\Users\(myPCname)\Desktop\YTpyDwnlder.py", line 45, in <module>
ipd.Audio(filename=path)
File "C:\Python36\lib\site-packages\IPython\lib\display.py", line 110, in __init__
super(Audio, self).__init__(data=data, url=url, filename=filename)
File "C:\Python36\lib\site-packages\IPython\core\display.py", line 627, in __init__
self.reload()
File "C:\Python36\lib\site-packages\IPython\lib\display.py", line 121, in reload
super(Audio, self).reload()
File "C:\Python36\lib\site-packages\IPython\core\display.py", line 652, in reload
with open(self.filename, self._read_flags) as f:
OSError: [Errno 22] Invalid argument: 'C:/Users/(myPCname)/Desktop/gui/Low Roar - "I\'ll Keep Coming".wav'
The path seems correct for the most part so I'm not sure why the program thinks it's wrong. I've tried to double and triple check through looking up other sites on Python string formatting for files and I can't find what's wrong. I've also tried inserting '\' to all potential single or double quotes within (provided they don't already have the '\' before them) the string but it still doesn't like it (I know this is a futile attempt and is redundant).
How can I fix this?
Also sorry if the tags are incorrect; this is my first time posting a question on here.
Nevermind. I found that the problem was due to invalid characters in the filename ('"' is changed to '#' in the filename).
I am using pickle to serialize a list of objects, encrypting the serialized string and then using pickle to dump it into a file so that I can be read out in reverse later. I understand this may be a round about way of doing things but in theory I cant seem to get my head around why when reloading the data it continues to fail. Let me first apologize for my horrendous naming conventions one day these will improve.
I have dumped the code below, the error only occurs at the very end when loading the data back into the list and fails with the following error:
Traceback (most recent call last):
File "servertest.py", line 453, in <module>
mylist = mary1.ReadFromFile()
File "servertest.py", line 142, in ReadFromFile
mrylist = pickle.loads(datastring)
File "C:\Python27\lib\pickle.py", line 1388, in loads
return Unpickler(file).load()
File "C:\Python27\lib\pickle.py", line 864, in load
dispatch[key](self)
KeyError: '\xa7'
I have printed the data out at each step when calling both the write and read functions and it appears to be fine:
This is rawdata
]q ((c__main__
User
q☺oq☻}q♥(U☻idq♦U♦daveq♣U♥pinq♠U☻22qub(h☺o}q (h♦U♦maryq
h♠U♥434q♂ube.
this is encrypt data
'▼ES╬NZ┴w▲sæô▄Hó^┴☻½K◄6►ëΘ░¡√╡▼/ⁿ♀*a]ì╡
5åα¬δ⌡D╓£o¶α{ô √■♣í♠.|H^E«√☼Hwñ/cúw╠Σ√↔↔╞╞┼3
this is enc data
'▼ES╬NZ┴w▲sæô▄Hó^┴☻½K◄6►ëΘ░¡√╡▼/ⁿ♀*a]ì╡
5åα¬δ⌡D╓£o¶α{ô √■♣í♠.|H^E«√☼Hwñ/cúw╠Σ√↔↔╞╞┼3
unencrypted data
]q ((c__main__
User
q☺oq☻}q♥(U☻idq♦U♦daveq♣U♥pinq♠U☻22qub(h☺o}q (h♦U♦maryq
h♠U♥434q♂ube.
The following shows the two functions I'm using:
def WriteToFile(self, mrlist):
self.mrlist = mrlist
rawdata = pickle.dumps(mrlist, 1)
#print 'rawdata1\n' + rawdata
#encrypt pickled list (call on my encryption functions)
encrydata = self.encryptmessage.EncrMsg(rawdata)
print('this is encrypt data \n ' + encrydata)
#Open and dump encrypted string to file
file=open(self.fn,"wb")
pickle.dump(encrydata, file, 1)
file.close()
#Function to call when reading the file
def ReadFromFile(self):
mrylist = []
#open file and load
file = open(self.fn, "rb")
encdata = pickle.load(file)
file.close
print('this is enc data*********\n ' + encdata)
#Decrypt the string
datastring = self.encrytmessage.DeCryptMsh(encdata)
print 'unencrypted data' + datastring
mrylist = pickle.loads(datastring)
return mrylist`
Edit:
The following shows the simple user class for those interested in seeing what the list contains:
class User:
def __init__(self, id, pin):
self.id = id
self.pin = pin
def getpair(self):
return ' %s " | " %s ' % (self.id, self.pin)
def edit_pin(self, pin1):
self.pin = pin1
Solution
I managed to get this sorted, my original way of doing this was working fine and it wasn't actually an issue with pickle at all. It appears that my initialisation vector when calling my decryption function differed from when it was originally encrypted.
This still produced an identical string when decryption took place but must have included some differences i was unable to see. I've rewritten the ReadWrite class to make use of Read and Write functions rather than using pickle to dump the serialised/encrypted list into the file. I have also started writing the IV to an external so that it can be read by the decrypt method the next time the program loads.
Thank you for any help and suggestions given.
i've created a file with the name enviroment.py which contain a Profile class however when i in another file try to import the file like import testProject.enviroment import Profile i get below error
yaml_helper.py", line 11, in read_yaml
with open(file_path, 'r') as f:
IOError: [Errno 2] No such file or directory:
however i'm not sure why it gives this error since the Profile hasnt even been initialized. all i've done is imported it?
enviroment.py
class Profile(object):
def __init__(self, profile):
self.profile = yaml_helper.read_yaml(project.default_profiles_dir, profile)
self.run_enviroment()
def get(self, key):
return self.profile.get(key)
def run_enviroment(self):
return common.validate(connectors.exasol_credentials, self.profile)
That's not an import error. That's an error when the program is trying to open a file. The problem is where you call yaml_helper.read_yaml.
Are you passing in the correct parameters? for example, in that call, you are passing in project.default_profies_dir What is project? I don't see it defined. That could be your problem.