When I try the following:
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas
import urllib
import StringIO
import PIL.Image
image_file = urllib.urlopen('https://www.google.com/images/srpr/logo11w.png')
image_string = StringIO.StringIO(image_file.read())
logo = PIL.Image.open(image_string)
canvas = Canvas('output.pdf', pagesize=letter)
canvas.drawImage(logo, 10, 10)
canvas.showPage()
canvas.save()
I get this error:
Traceback (most recent call last):
File "imagefromurl.py", line 12, in <module>
canvas.drawImage(logo, 10, 10)
File "/usr/lib/python2.7/dist-packages/reportlab/pdfgen/canvas.py", line 857, in drawImage
imgObj = pdfdoc.PDFImageXObject(name, image, mask=mask)
File "/usr/lib/python2.7/dist-packages/reportlab/pdfbase/pdfdoc.py", line 2090, in __init__
ext = string.lower(os.path.splitext(source)[1])
File "/usr/lib/python2.7/posixpath.py", line 96, in splitext
return genericpath._splitext(p, sep, altsep, extsep)
File "/usr/lib/python2.7/genericpath.py", line 91, in _splitext
sepIndex = p.rfind(sep)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 515, in __getattr__
raise AttributeError(name)
Reportlab is version 2.5.
I was doing it the hard way. This works (also added the necessary mask to avoid transparent becoming black):
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.utils import ImageReader
logo = ImageReader('https://www.google.com/images/srpr/logo11w.png')
canvas = Canvas('output.pdf', pagesize=letter)
canvas.drawImage(logo, 10, 10, mask='auto')
canvas.showPage()
canvas.save()
Though the hard way would have allowed me to detect a failure to fetch the image url and handle it (e.g. substituting a local image), and this doesn't.
Related
I'm trying to convert a .npy image to a nii.gz image, I'm having various problems even though I'm following instructions correctly.
This is the code I'm using:
import numpy as np
import nibabel as nib
file_dir = "D:/teste volumes slicer/"
fileNPY1 = "teste01.npy"
img_array1 = np.load(file_dir + fileNPY1)
print(img_array1.shape)
print(img_array1.dtype)
normal_array = "D:/teste volumes slicer/teste01.npy"
print ("done")
nifti_file = nib.Nifti1Image(normal_array, np.eye(4))
About the image: (332, 360, 360) float64 (this is what we got when we print the shape and dtype)
https://ibb.co/mRyTrw7 - image that shows the error and the image's information
The error message:
Traceback (most recent call last):
File "d:\teste volumes slicer\conversor.py", line 16, in <module>
nifti_file = nib.Nifti1Image(normal_array, np.eye(4))
File "C:\Python39\lib\site-packages\nibabel\nifti1.py", line 1756, in __init__
super(Nifti1Pair, self).__init__(dataobj,
File "C:\Python39\lib\site-packages\nibabel\analyze.py", line 918, in __init__
super(AnalyzeImage, self).__init__(
File "C:\Python39\lib\site-packages\nibabel\spatialimages.py", line 469, in __init__
self.update_header()
File "C:\Python39\lib\site-packages\nibabel\nifti1.py", line 2032, in update_header
super(Nifti1Image, self).update_header()
File "C:\Python39\lib\site-packages\nibabel\nifti1.py", line 1795, in update_header
super(Nifti1Pair, self).update_header()
File "C:\Python39\lib\site-packages\nibabel\spatialimages.py", line 491, in update_header
shape = self._dataobj.shape
AttributeError: 'str' object has no attribute 'shape'
The problem with your code is instead of passing your Numpy-array (your image), you are passing the path of the image to the Nifti1Image function.
This is the correct way to convert it:
import numpy as np
import nibabel as nib
file_dir = "D:/teste volumes slicer/"
fileNPY1 = "teste01.npy"
img_array1 = np.load(file_dir + fileNPY1)
nifti_file = nib.Nifti1Image(img_array1 , np.eye(4))
Report lab is not producing a pdf in a very simple example/try:
from arcpy import *
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from pyPdf import PdfFileWriter, PdfFileReader
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, cm
from reportlab.platypus import Paragraph
from reportlab.lib import colors
from reportlab.pdfgen import canvas
filename = "HelloWorld.pdf"
c = canvas.Canvas(filename)
c.drawString(100,750,"Welcome to Reportlab!")
c.save()
These two lines work fine:
c.drawString(100,750,"Welcome to Reportlab!")
c.save()
But is this one that throw the errors. I've tried to change the path, the filename, try the 'r' before the string of text for the path+filename, nothing works.
I've got this error trace:
Traceback (most recent call last):
File "C:\Users\Edmundo\GIS_SEG\EGtemp\PdfReports\PyScripts\TestRepLab.py", line 15, in <module>
c.save()
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfgen\canvas.py", line 1237, in save
self._doc.SaveToFile(self._filename, self)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 221, in SaveToFile
data = self.GetPDFData(canvas)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 246, in GetPDFData
return self.format()
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 423, in format
IOf = IO.format(self)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 871, in format
fcontent = format(self.content, document, toplevel=1) # yes this is at top level
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 80, in format
f = element.format(document)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 1561, in format
return PD.format(document)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 679, in format
L = [(format(PDFName(k),document)+b" "+format(dict[k],document)) for k in keys]
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 80, in format
f = element.format(document)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 610, in format
s.decode('pdfdoc')
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\rl_codecs.py", line 1047, in _rl_codecs
if name.startswith(e): return RL_Codecs.__rl_codecs(e)
AttributeError: 'NoneType' object has no attribute '_RL_Codecs__rl_codecs'
You need to call showPage():
from reportlab.pdfgen import canvas
filename = "HelloWorld.pdf"
c = canvas.Canvas(filename)
c.drawString(100,750,"Welcome to Reportlab!")
c.showPage()
c.save()
I am using python 2.7 and pyBarcode 0.7 in Windows and I am trying to generate barcode as png image by using following sample code (available in pyBarcode webpage)
>>> import barcode
>>> barcode.PROVIDED_BARCODES
[u'code39', u'ean', u'ean13', u'ean8', u'gs1', u'gtin', u'isbn', u'isbn10',
u'isbn13', u'issn', u'jan', u'pzn', u'upc', u'upca']
>>> EAN = barcode.get_barcode_class('ean13')
>>> EAN
<class 'barcode.ean.EuropeanArticleNumber13'>
>>> ean = EAN(u'5901234123457')
>>> ean
<barcode.ean.EuropeanArticleNumber13 object at 0x00BE98F0>
# Example with PNG
>>> from barcode.writer import ImageWriter
>>> ean = EAN(u'5901234123457', writer=ImageWriter())
>>> fullname = ean.save('ean13_barcode')
Last line generates following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\python27\lib\site-packages\barcode\base.py", line 68, in save
output = self.render(options)
File "c:\python27\lib\site-packages\barcode\ean.py", line 106, in render
return Barcode.render(self, options)
File "c:\python27\lib\site-packages\barcode\base.py", line 103, in render
raw = Barcode.raw = self.writer.render(code)
File "c:\python27\lib\site-packages\barcode\writer.py", line 188, in render
self._callbacks['paint_text'](xpos, ypos)
File "c:\python27\lib\site-packages\barcode\writer.py", line 280, in _paint_te
xt
font = ImageFont.truetype(FONT, self.font_size * 2)
File "c:\python27\lib\site-packages\PIL\ImageFont.py", line 218, in truetype
return FreeTypeFont(filename, size, index, encoding)
File "c:\python27\lib\site-packages\PIL\ImageFont.py", line 134, in __init__
self.font = core.getfont(file, size, index, encoding)
File "c:\python27\lib\site-packages\PIL\ImageFont.py", line 34, in __getattr__
raise ImportError("The _imagingft C module is not installed")
ImportError: The _imagingft C module is not installed
I retried by installing Pillow (but before that I removed PIL); I downloaded "Pillow-4.2.1-win32-py2_7.exe"
and I did also "pip install Pillow".
Now when I try to run
import barcode
I got:
File "barcode\codex.py", line 12, in <module>
from barcode.base import Barcode
File "barcode\base.py", line 9, in <module>
from barcode.writer import SVGWriter
File "barcode\writer.py", line 12, in <module>
import Image, ImageDraw, ImageFont
File "c:\python27\lib\site-packages\PIL\Image.py", line 27, in <module>
from . import VERSION, PILLOW_VERSION, _plugins
ValueError: Attempted relative import in non-package
What should I do ?
thanks
I am wondering why I can get this error:
pyglet.lib.gl.GLExeption: invalid value
at: self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture())
Imported libs:
import sys
import math
import random
import time
from collections import deque
from pyglet import image
from pyglet.gl import *
from pyglet.graphics import TextureGroup
from pyglet.window import key, mouse, Window
from PIL import Image
I'm using PIL for making the PNG:
print "Creating ", TEXTURE_PATH
images = map(Image.open, texture_path)
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]
new_im.convert('RGB')
new_im.save(TEXTURE_PATH, "PNG")
And the 'texture_path`(lowercase) is here:
texture_path = ['res/textures/grass_top.png'] * 99
The full error message is:
Traceback (most recent call last):
File "D:\pythoncode\pyglet\minecraft_remake.py", line 955, in <module>
main()
File "D:\pythoncode\pyglet\minecraft_remake.py", line 948, in main
window = Window(width = 640, height = 480, caption="Minecraft 3d!", resizable=True)
File "D:\pythoncode\pyglet\minecraft_remake.py", line 554, in __init__
self.model = Model()
File "D:\pythoncode\pyglet\minecraft_remake.py", line 198, in __init__
self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture())
File "C:\Python27\lib\site-packages\pyglet\image\__init__.py", line 818, in get_texture
force_rectangle)
File "C:\Python27\lib\site-packages\pyglet\image\__init__.py", line 803, in create_texture
rectangle, force_rectangle)
File "C:\Python27\lib\site-packages\pyglet\image\__init__.py", line 1514, in create
blank)
File "C:\Python27\lib\site-packages\pyglet\gl\lib.py", line 104, in errcheck
raise GLException(msg)
GLException: invalid value
I found the problem, but didn't know how to fix it, the problem are in the PNG making.
When I replace the textures.png with another picture, it's working
but when I make one with PIL, it doesn't work.
Solved: the problem is in my .PNG Editor, i just make the image manually and it works!
im using Graphics Gale Free edition to edit and it will work.
i think the problem is in the PIL itself. Or The pyglet doesnt load PIL config PNG
P.s it may be because color configuration
I'm using Python and I have the following snippet of code:
>>> from PIL import Image
>>> from PIL import ImageFont
>>> from PIL import ImageDraw
>>> img = Image.open("sample_in.jpg")
>>> draw = ImageDraw.Draw(img)
# font = ImageFont.truetype(<font-file>, <font-size>)
>>> font = ImageFont.truetype("sans-serif.ttf", 16)
# draw.text((x, y),"Sample Text",(r,g,b))
>>> draw.text((0, 0),"Sample Text",(255,255,255),font=font)
>>> img.save('sample_in.jpg')
source: Add Text on Image using PIL
The problem I am having is I can't rename the file the same as the original is there a way to accomplish this?
Traceback:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1433, in save
fp = __builtin__.open(fp, "wb")
IOError: [Errno 13] Permission denied: 'sample_in.jpg'