How to generate barcode in python as response of image object - python

Views.py:
def Bar(request):
payload = json.loads(request.body.decode('utf-8'))
a=payload["donor_n_key"]
ean = barcode.get('code128', a, writer=ImageWriter())
filename = ean.save('ean13')
image = ean.render()
return HttpResponse(image,content_type="image/png")
Here i have downloaded the barcode image but I am unable to open that image.I am getting the error is windows photo viewer can't open this picture because either photo viewer does not support this file format.
I am new to this django restframework.Please help me Anyone.

In Your View.py
Import This
import barcode
from barcode.writer import ImageWriter
def Bar(request):
lineCode = '1234567891234'
barCodeImage = barcode.get('ean13', lineCode, writer=ImageWriter())
filename = barCodeImage.save(item_name.png)
return HttpResponse(image,content_type="image/png")
It Will Generates Image and save it your project root folder
More help visit this link PyBarcode

Related

Unable to save webp file to model field

I'm not sure if this is entirely django related, but if someone could help me, that would be so much appreciated! I'm having trouble generating a webp file from the following code
from io import BytesIO
from PIL import Image
import requests
I've got the following model
class UserImage(models.Model):
user_provided_image = VersatileImageField(upload_to=folder10, null=True, blank=True)
nextgen_image = models.FileField(upload_to=folder10,null=True, blank=True) #for WebP images
I'm creating a webp file. This code works, but it saved it to the file to the root directory of my project and I'm not sure how to save it to the FileField (i.e. nextgen_image ) on my model
def create_webp_image(sender, instance, *args, **kwargs):
image_url = instance.image.thumbnail['1920x1080'].url
try:
response = requests.get(image_url, stream=True)
path = image_url
except: #local env
path = "http://localhost:8000" + image_url
response = requests.get(path, stream=True)
img = Image.open(BytesIO(response.content))
#build file path
position = path.rfind("/") + 1
newpath = path[0:position]
#build file name
image_name = path[position:]
name_of_file = image_name.split('.')[0] + ".webp"
#this creates the webp file
img.save(name_of_file,"webp")
#save image to model
#instance.nextgen_image = ?
post_save.connect(create_webp_image, sender=UserImage)
Thanks!
You can use something like that:
from django.core.files.base import ContentFile
...
img_content = ContentFile(BytesIO(response.content))
instance.nextgen_image.save(name_of_file, img_content, save=True)
...
If you want to use packages to get the job done then use this package django-resized.
Based on the code provided above this should do the trick. Hoping that this will solve your issue. Cheers
nextgen_image = ResizedImageField(force_format="WEBP",
upload_to=folder10,null=True, blank=True)

Getting a thumbnail image from google books api into a python variable

I can do this OK both in js and php but not in python. I'm trying to pull a thumbnail image from google books api into a python variable.
The text objects are fine eg
newTitle = (parsed_json['items'][0]['volumeInfo']['title'])
isbn10 = (parsed_json['items'][0]['volumeInfo']['industryIdentifiers'][1]['identifier'])
isbn13 = (parsed_json['items'][0]['volumeInfo']['industryIdentifiers'][0]['identifier'])
The image is supplied in the api as follows. (if you put the http// url into a browser you see the image):
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=XUnNDwAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=XUnNDwAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
I have tried the simple:
myImage = (parsed_json['items'][0]['volumeInfo']['imageLinks'][thumbnail])
which doesn't work.
I have installed pillow to provide image management:
from PIL import Image
img = Image.open("parsed_json['items'][0]['volumeInfo']['imageLinks'][thumbnail]") or
img = Image.open(parsed_json['items'][0]['volumeInfo']['imageLinks'][thumbnail])
which doesn't work. I have tried more complex arrangements:
from PIL import Image
import requests
from io import BytesIO
response = requests.get(parsed_json['items'][0]['volumeInfo']['imageLinks'][thumbnail])
img = Image.open(BytesIO(response.content))
but nothing seems to work. I have tried many other variations on these attempts. I have also, unsuccessfully tried to load the text that points to the thumbnail to try another route. I am confident that the "['items'][0]['volumeInfo']['imageLinks'][thumbnail]" is correct though my only way of testing whether the variable is properly loaded is to save it or if the line of code isn't working.
I didn't have problems downloading and opening the image.
I have use the following code
import requests
from PIL import Image
image_url = "https://books.google.com/books/content?id=XUnNDwAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api"
r = requests.get(image_url)
with open("demo_image",'wb') as f:
f.write(r.content)
img = Image.open("demo_image")

How to display image in python docx template (docxtpl)? Django Python

I am using python-docx-template (docxtpl) to generate a .docx file.
With this data:
docente= {
"id":145,
"lugar_de_nacimiento":"Loja",
"fecha_de_nacimiento":"1973-04-14",
"ciudad":"Loja",
"foto_web_low":"https://sica.utpl.edu.ec/media/uploads/docentes/fotos/web/low/1102904313_low.jpg"
}
I have a function where I pass the image docente['foto_web_low'] to the context and the path of the template:
from docxtpl import DocxTemplate, InlineImage
from docx.shared import Mm
def generaraDocumento(request):
response = HttpResponse(content_type='application/msword')
response['Content-Disposition'] = 'attachment; filename="cv.docx"'
doc = DocxTemplate(str(settings.BASE_DIR) + '/cv_api/templates/docx_filename.docx')
imagen = docente['foto_web_low']
context = {'imagen': imagen}
doc.render(context)
doc.save(response)
return response
The template where I have the image that I want to show docx_filename.docx has this:
The template where I have the data that I want to show docx_filename.docx has this:
Image: {{ imagen }}
When the document is generated, I only get the URL address and not the image, in my template it returns this:
Image: https://sica.utpl.edu.ec/media/uploads/docentes/fotos/web/low/1102904313_low.jpg
How can I make the image appear in the document .docx (docxtpl). Thanks in advance.
The image has to be an instance of docxtpl.InlineImage (see docs).
Another important thing is that the image must be present on the disk. docxtpl doesn't support reading images from a url.
Example:
from docxtpl import InlineImage
from docx.shared import Mm
doc = DocxTemplate(str(settings.BASE_DIR) + '/cv_api/templates/docx_filename.docx')
# The image must be already saved on the disk
# reading images from url is not supported
imagen = InlineImage(doc, '/path/to/image/file.jpg', width=Mm(20)) # width is in millimetres
context = {'imagen': imagen}
# ... the rest of the code remains the same ...
Resize the image first, before add it
make it fit to your space
from PIL import Image
img = Image.open("image-path")
newimg = img.resize((250, 250))
newimg.save("tmplogo.png")
then use the new sized image which name tmplogo.png
doc = DocxTemplate("Base.docx")
dic = {"logo": InlineImage(doc, "tmplogo.png")}
doc.render(dic)
doc.save("test.docx")
You're currently linking the variable foto_web_low to the url and not to an actual image. You will need to download the image first, and then attach it. The code below is not tested, but should be in the right direction:
First, dowload the image:
response = requests.get("https://The_URL_of_the_picture.jpg")
file = open("the_image.png", "wb")
file.write(response.content)
file.close()
And then simply add the image to your variable in the context:
docente= {
"id":145,
...
"foto_web_low":"the_image.png",
...
}

Django save base64 string to filesystem using models.ImageField

I am trying to upload image to file system using python django. I dont have any idea on how to proceed further.
in my model.py:
Class Test(object):
mission = models.TextField(blank=True)
image = models.ImageField(upload_to='documents/images/',blank=True)
account = models.OneToOneField(Account, related_name='account')
in my view.py
def add_image(request, account):
req = get_request_json(request)
data = Test.objects.add_image(account, req)
in my manager.py
Class TestManager(models.Manager):
def add_image(self, account, input):
acc = self.get(account=account)
acc.save()
return acc;
But I am not sure how to proceed from here.
I would like to know how to save the base64 image string to the specified location and store the path/file name in database?
I have worked with python where I write the files to a directory and get the path and store in db. Here I want to use the django options.
I have to repeat the same process with other file formats too.
If you have an image in base64 string format and you want to save it to a models ImageField, this is what I would do
import base64
from django.core.files.base import ContentFile
image_b64 = request.POST.get('image') # This is your base64 string image
format, imgstr = image_b64.split(';base64,')
ext = format.split('/')[-1]
data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext)
Now, you can simply do
Test.objects.create(image=data)

How to add watermark to pdf file?

How to add watermark to pdf file generated from this code?
import xhtml2pdf
from xhtml2pdf import pisa
def delivery_cancel(request, did):
d_instance = get_object_or_404(Delivery, pk=did, user=request.user)
users = request.user.get_profile()
user = request.user
contents = render_to_string('delivery_cancel.html', {'delivery':d_instance,'users':users,'user':user})
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'inline; filename=mypdf.pdf'
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(contents.encode('utf-8')), result, show_error_as_pdf=True, encoding='UTF-8')
response.write(result.getvalue())
result.close()
return response
I tried to use reportlab but I failed so I'm asking for another solution.
The input to xhtml2pdf is XHTML, so you probably want to specify your watermark there. The documentation says to use a background-image on #page.
Alternatively, you can create a single-page PDF that just contains the watermark and apply it to your generated file after the fact using something like pdftk's background option.
My approach is a longer one but it should solve most of the problems faced.
With this script you will be able to add the list of watermark email address from a xlsx sheet and add the same email address as watermark to all the pages of a pdf which you input
# Importing all required packages
import xlrd
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch, cm
from PyPDF2 import PdfFileWriter, PdfFileReader
from reportlab.lib.colors import HexColor
# create watermarked booklet
def final_booklets(file_name,booklet):
watermark_obj = PdfFileReader(file_name)
watermark_page = watermark_obj.getPage(0)
pdf_reader = PdfFileReader(booklet)
pdf_writer = PdfFileWriter()
# Watermark all the pages
for page in range(pdf_reader.getNumPages()):
page = pdf_reader.getPage(page)
page.mergePage(watermark_page)
pdf_writer.addPage(page)
output = file_name+"_booklet.pdf"
with open(output, 'wb') as out:
pdf_writer.write(out)
# Create watermark pdf again each email address
def watermark_pdf(target,booklet):
file_name = (target + ".pdf")
c = canvas.Canvas(file_name)
c.saveState()
c.setFillColor(HexColor('#dee0ea'))
c.setFont("Helvetica", 40)
c.translate(15*cm, 20*cm )
c.rotate(45)
c.drawRightString(0,0,target)
c.restoreState()
c.showPage()
c.save()
final_booklets(file_name,booklet)
# Read the sheet to get everyones email address
def read_xlsx(fn):
book = xlrd.open_workbook(fn)
sheet = book.sheet_by_index(0)
booklet = "book.pdf"
for cell in range(1,sheet.nrows):
target = sheet.cell(cell,1).value
watermark_pdf(target,booklet)
# main controller
if __name__ == "__main__":
fn = "Test.xlsx"
read_xlsx(fn)
Original Github link: https://github.com/manojitballav/python_watermark/blob/master/master.py

Categories

Resources