[PYTHON] Convert PIL format images read from form with Django to base64 format

Introduction

It's just a memo, so I'll omit the detailed settings of Django. The project is image_pred and the app name is myapp. The settings are only basic, as in the first part of the official page.

program

From index.html, send the image using the form.

index.html


{% load static %}
<!doctype html>
<html lang="ja">
<head>
 <meta charset="utf-8">
 <title>title</title>
</head>
<body>
   <div id = "input_form">
      <form action="{% url 'index' %}" method="POST" enctype="multipart/form-data">
         {% csrf_token %}
         {{ form }}
         <input type="submit" value="Send" />
      </form>
   </div>
   <!--<div id = "prevent"><img src="{{question_id}}"></div>-->
   <div id = "predict">{{urls}}</div>
</body>
</html>

forms.py


from django import forms

class PhotoForm(forms.Form):
    image = forms.ImageField(label='Please select an image')

views.py


from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views.generic import TemplateView
from .forms import PhotoForm

class MyappView(TemplateView):
    def __init__(self):
        self.params={'form': PhotoForm()}
        
    def get(self, req):
        return render(req, 'index.html', self.params)

    def post(self, req):
        form = PhotoForm(req.POST, req.FILES)
        if not form.is_valid():
            raise ValueError('invalid form')

        image = form.cleaned_data['image']
        self.url_get(req, image)
        return render(req, 'index.html', self.params)

    def url_get(self, req, url):
        from PIL import Image
        import base64
        import io
        from io import BytesIO

        img = Image.open(url)
        with io.BytesIO() as output:
            img.save(output,format="JPEG")
            contents = output.getvalue()
            data = base64.b64encode(contents)
            #print('data:image/jpeg;base64,' + str(data)[2:-1])
            self.params['urls'] = 'data:image/jpeg;base64,' + str(data)[2:-1]

result

This is the first image. Select the file and click Recognize. キャプチャ.PNG

I think you will see a result like this, so you can display the image based on this. キャプチャ3.PNG

References

Since the creation of the project etc. is based on this material, there are many parts of the program that are the same. https://trafalbad.hatenadiary.jp/entry/2018/09/11/105500

Recommended Posts

Convert PIL format images read from form with Django to base64 format
Convert images from FlyCapture SDK to a form that can be used with openCV
Convert color space from RGB to CIELAB with PIL (Pillow)
Convert images to sepia toning with PIL (Python Imaging Library)
How to easily convert format from Markdown
Convert from PDF to CSV with pdfplumber
How to convert DateTimeField format in Django
Cannot upload multiple images from form with FastAPI
Convert strings to character-by-character list format with python
Instantly convert Model to Dictionary with Django and initialize Form at explosive speed
Images created with matplotlib shift from dvi to pdf
Convert 202003 to 2020-03 with pandas
Convert Select query obtained from Postgre with Go to JSON
Linux script to convert Markdown files from JupyterLab format to Qiita format
Convert garbled scanned images to PDF with Pillow and PyPDF
[Caffe] Convert mean file from binary proto format to npy format
[Django] Redirect to previous page after submitting with POST form
Combine two images with Django
I read "Reinforcement Learning with Python: From Introduction to Practice" Chapter 1
I read "Reinforcement Learning with Python: From Introduction to Practice" Chapter 2
[Python] Try to recognize characters from images with OpenCV and pyocr
Convert .ipynb to .html (with BatchFile)
[Django] How to test Form [TDD]
Create folders from '01' to '12' with python
Common html to rent with Django
Convert list to DataFrame with python
Convert sentences to vectors with gensim
How to get started with Django
Post images from Python to Tumblr
Get the value from the [Django] Form
How to convert from .mgz to .nii.gz
Convert PDF to image with ImageMagick
Read fbx from python with cinema4d
How to authenticate with Django Part 2
How to authenticate with Django Part 3
I tried to send a registration completion email from Gmail with django.
Read CSV file with Python and convert it to DataFrame as it is
Preprocessing with Python. Convert Nico Nico Douga tag search results to CSV format