trouble whit save() in barcode generation in windows - python

hi i'm working in an app which generate barcodes into a pdf file. I tried it in linux and worked perfectly, but when try it in Windows, i receive some errors.
My code is the next:
def crear_barcode(numero):
filename = 'generated/temp/'+numero
writer = barcode.writer.ImageWriter()
code = barcode.Code39(numero,writer,add_checksum = False)
archivo = code.save(filename)
return archivo
and the errors I receiving are that:
Traceback (most recent call last):
File "C:\Documents and Settings\usuario\Escritorio\NIF-master\nif.py", line 23, in generarButton_clicked
generar_codigos(provincia,ciudad,numeroInicial,cantidad)
File "C:\Documents and Settings\usuario\Escritorio\NIF-master\controller\controller.py", line 64, in generar_codigos
archivo.image(crear_barcode(numero),eje_x * 50, linea * 25 , TAMANIO_CODIGO)
File "C:\Documents and Settings\usuario\Escritorio\NIF-master\controller\controller.py", line 43, in crear_barcode
archivo = code.save(filename)
File "C:\Python27\lib\site-packages\pybarcode-0.7-py2.7.egg\barcode\base.py", line 69, in save
_filename = self.writer.save(filename, output)
File "C:\Python27\lib\site-packages\pybarcode-0.7-py2.7.egg\barcode\writer.py", line 291, in save
output.save(filename, self.format.upper())
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1681, in save
save_handler = SAVE[format.upper()]
KeyError: u'PNG'
when I change the save() line and give it an extension ie:
code.save(filename,'png')
I receive that
Traceback (most recent call last):
File "C:\Documents and Settings\usuario\Escritorio\NIF-master\nif.py", line 23, in generarButton_clicked
generar_codigos(provincia,ciudad,numeroInicial,cantidad)
File "C:\Documents and Settings\usuario\Escritorio\NIF-master\controller\controller.py", line 64, in generar_codigos
archivo.image(crear_barcode(numero),eje_x * 50, linea * 25 , TAMANIO_CODIGO)
File "C:\Documents and Settings\usuario\Escritorio\NIF-master\controller\controller.py", line 43, in crear_barcode
archivo = code.save(filename,'png')
File "C:\Python27\lib\site-packages\pybarcode-0.7-py2.7.egg\barcode\base.py", line 68, in save
output = self.render(options)
File "C:\Python27\lib\site-packages\pybarcode-0.7-py2.7.egg\barcode\codex.py", line 105, in render
options.update(writer_options or {})
ValueError: dictionary update sequence element #0 has length 1; 2 is required
I don't understand why occur in windows and not in linux.
I have installed all the dependencies, PIL, pyBarcode, pyFpdf.

I faced a similar issue earlier, and this is what I did to solved it :
1) Open this file - C:\Python27\lib\site-packages\pybarcode-0.7-py2.7.egg\barcode\writer.py
2) You will see the following code -
try:
import Image, ImageDraw, ImageFont ### The Statement to be edited ####
except ImportError:
try:
from PIL import Image, ImageDraw, ImageFont # lint:ok
except ImportError:
import sys
sys.stderr.write('PIL not found. Image output disabled.\n\n')
Image = ImageDraw = ImageFont = None # lint:ok
3) You need to edit the first import statement to make the code look like the following -
try:
from PIL import Image, ImageDraw, ImageFont ### Edited.
except ImportError:
try:
from PIL import Image, ImageDraw, ImageFont # lint:ok
except ImportError:
import sys
sys.stderr.write('PIL not found. Image output disabled.\n\n')
Image = ImageDraw = ImageFont = None # lint:ok
4) Save the file.
5) Try running your app.
I hope this helps.

Without having the full code to test, it looks like this is due to OS specific file separators. Linux uses forward slashes vs. Windows uses backslashes. Try using platform independent filenames:
filename = os.path.join('generated','temp', str(numero))

Related

imread() unable to identify existing image on Spyder

The file evidently exists, but imread() is unable to identify the image. Is there something I am missing? I'm still new to python and its respective libraries.
Code (Python 3.7.9)
import os
import time
import numpy as np
import matplotlib.pyplot as plt
from randomlyShiftChannels import *
from alignChannels import *
from utils import *
#Path to your data directory
data_dir = os.path.join('..', 'data', 'demosaic')
#List of images
image_names = ['balloon.jpeg','cat.jpg', 'ip.jpg',
'puppy.jpg', 'squirrel.jpg', 'pencils.jpg',
'house.png', 'light.png', 'sails.png', 'tree.jpeg'];
print('Evaluating alignment...')
for imgname in image_names:
# Read image
imgpath = os.path.join(data_dir, imgname)
print("File exists:", os.path.exists(imgpath))
img = imread(imgpath)
Output
File exists: True
Traceback (most recent call last):
File "D:\Spring2021\CS370\week 6\p2-release\code\evalAlignment.py", line 48, in <module>
img = imread(imgpath)
File "D:\Spring2021\CS370\week 6\p2-release\code\utils.py", line 14, in imread
img = plt.imread(path).astype(float)
File "C:\Users\dminn\AppData\Local\Programs\Spyder\pkgs\matplotlib\pyplot.py", line 2246, in imread
return matplotlib.image.imread(fname, format)
File "C:\Users\dminn\AppData\Local\Programs\Spyder\pkgs\matplotlib\image.py", line 1496, in imread
with img_open(fname) as image:
File "C:\Users\dminn\AppData\Local\Programs\Spyder\pkgs\PIL\Image.py", line 2944, in open
"cannot identify image file %r" % (filename if filename else fp)
UnidentifiedImageError: cannot identify image file '..\\data\\demosaic\\balloon.jpeg'
I faced the identical issue using Spyder (Spyder 5.0.0 and 5.0.1).
No errors appeared when running the script from the command line.
Found workaround for Spyder: use pil_to_array() instead of imread()
from PIL import Image
img = pil_to_array(Image.open(imgpath))
Try converting your path to an absolute path, there are reasons we call it good practice
Sample code:
import os
os.path.abspath("mydir/myfile.txt") #'C:/example/cwd/mydir/myfile.txt'

Exporting a PNG of a zenmap topology from a Nmap XML file

I need help exporting the zenmap network topology graph to a PNG file automatically without having to open the zenmap and doing it manually.
I found a script on github but it's showing me an error:
#!/usr/bin/env python
import sys
if len(sys.argv) != 4:
print """{0} - Output a PNG from Nmap XML
Usage: {0} <scan.xml> <out.png> <width_in_pixels>""".format(sys.argv[0])
sys.exit(1)
try:
from zenmapGUI.TopologyPage import *
except ImportError:
import sys
sys.path.insert(0,"/usr/bin/zenmap")
from zenmapGUI.TopologyPage import *
t = TopologyPage(NetworkInventory(sys.argv[1]))
pix = int(sys.argv[3])
t.radialnet.set_allocation((0,0,pix,pix))
t.update_radialnet()
t.radialnet.save_drawing_to_file(sys.argv[2])
pradeep#ubuntu:~/Desktop$ python nmaptopng.py /home/pradeep/Desktop/topology.xml /home/pradeep/Desktop/xxx.png 500
Traceback (most recent call last):
File "nmaptopng.py", line 17, in <module>
t = TopologyPage(NetworkInventory(sys.argv[1]))
File "/usr/lib/python2.7/dist-packages/zenmapCore/NetworkInventory.py", line 145, in __init__
self.open_from_file(filename)
File "/usr/lib/python2.7/dist-packages/zenmapCore/NetworkInventory.py", line 315, in open_from_file
parsed = NmapParser(path)
TypeError: nmap_parser_sax() takes no arguments (1 given)
I tried looking for the NetworkInventory.py file in zenmap but failed to understand the problem! Can anyone help me with this?

IOError: cannot identify image file in Python

I am trying to run this start up code where I am trying to get python to read photos as I am trying to get it to copy all the photos in 1200 folders and paste them to a single photo for my deep learning project. But I keep getting this error or problem.
from PIL import Image
im = Image.open("1.jpg")
im.show()
This is what I get when I try to run the code.
anthony#anthony-G53JW:~/design4$ python copy2.py
Traceback (most recent call last):
File "copy2.py", line 2, in <module>
im = Image.open("1.jpg")
File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 2289, in open
preinit()
File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 365, in preinit
from PIL import JpegImagePlugin
File "/usr/local/lib/python2.7/dist-packages/PIL/JpegImagePlugin.py", line 40, in <module>
from PIL import Image, ImageFile, TiffImagePlugin, _binary
File "/usr/local/lib/python2.7/dist-packages/PIL/TiffImagePlugin.py", line 50, in <module>
from fractions import Fraction
File "/usr/lib/python2.7/fractions.py", line 7, in <module>
from decimal import Decimal
File "/usr/lib/python2.7/decimal.py", line 139, in <module>
import copy as _copy
File "/home/anthony/design4/copy.py", line 25, in <module>
dataset = Image.open("1.jpg")
File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 2317, in open
% (filename if filename else fp))
IOError: cannot identify image file '1.jpg'

pytesser doesn't work in python

I am using only PIL then it's work properly when I use pytesser then it doesn't work properly .What can i do for it?
from PIL import Image
from pytesser import *
image_file = Image.open("vote.jpg")
im = Image.open(image_file)
text = image_to_string(im)
print text
Traceback (most recent call last):
File "C:/Users/Tanvir/Desktop/py thon hand/hala.py", line 4, in <module>
image_file = Image.open("vote.jpg")
File "C:\Pythons27\lib\site-packages\PIL\Image.py", line 2286, in open
% (filename if filename else fp))
IOError: cannot identify image file 'vote.jpg'
I am find this solution .It was problem with PIL so at first I have to uninstall this PIL module then again install it and job done Every thing is okay.

Python Image Library - IndexError: string index out of range | Same code one works the other not

My task gets some files with header + image content. After the header extraction and create the image.png which is recognized and properly opened. This program works on windows with python 2.7.9 and the latest version at the time of PIL
Afterwords the image is converted from png to jpeg.
The code snippet:
im = Image.open("c:\\1\\rawfile.png")
im.save('c:\\1\\rawfile.jpeg',"JPEG")
Here appears the error (on the im.save() line), it only after the loading, if i do img.crop(x), img.rotate(x) the same error appears.
Traceback (most recent call last):
File "getMail.py", line 225, in <module>
start_deamon()
File "getMail.py", line 217, in start_deamon
deamon.process_email()
File "getMail.py", line 114, in process_email
self.img_conv.convert_file('c:\\1\\rawfile\\rawfile.png', 'c:\\1\\rawfile\\rawfile.jpg' )
File "getMail.py", line 162, in convert_file
im.save('c:\\1\\rawfile.jpeg',"JPEG")
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1406, in save
self.load()
File "C:\Python27\lib\site-packages\PIL\ImageFile.py", line 198, in load
s = read(self.decodermaxblock)
File "C:\Python27\lib\site-packages\PIL\PngImagePlugin.py", line 391, in load_read
cid, pos, len = self.png.read()
File "C:\Python27\lib\site-packages\PIL\PngImagePlugin.py", line 96, in read
len = i32(s)
File "C:\Python27\lib\site-packages\PIL\PngImagePlugin.py", line 44, in i32
return ord(c[3]) + (ord(c[2])<<8) + (ord(c[1])<<16) + (ord(c[0])<<24)
IndexError: string index out of range
I've tried the LOAD_TRUNCATED_IMAGES set to YES and it didn't work. I've also tried absolute paths with no luck.
On a debug stand alone program using the same hardcoded paths on the same files it works! (files are created, converted and properly read by file editors)
try:
with open( 'c:\\1\\rawFile', 'rb') as fin:
data = fin.read()
fin.close()
except:
print 'error1'
#do my stuff here
try:
with open( 'c:\\1\\rawfile.png', 'wb') as fout:
fout.write(data[index:])
fout.close()
except:
print 'error2'
try:
Image.open('c:\\1\\rawfile.png').save('c:\\1\\rawfile.jpg')
except:
print 'error 3'
If I hardcode the file paths on the main project it will fail and give the IndexError.
The original PIL was being used. Instead I've upgraded to Pillow (a PIL fork) which with the following code solved the problem. (as already described)
from PIL import ImageFile
#To ensure that *.png file are read
ImageFile.LOAD_TRUNCATED_IMAGES = True

Categories