GAE --With Python, rotate the image based on the rotation information of EXIF and upload it to Cloud Storage.

Introduction

Previously I tried to rotate the image on the server side using PIL and it failed. The cause is the following error

".../PIL-1.1.7/PIL/ImageFile.py", line 476, in _save
    fh = fp.fileno()
UnsupportedOperation: fileno

There seems to be something wrong with fileno (). If you search the net, you can see other people who are struggling with this error. I'm not sure about this error.

So this time, as a plan to overcome this, I will try to rotate it on the server side using GAE's ** Images Python API **.

** What is the Images Python API ** A function to operate image data provided by App Engine. You can resize, rotate, flip, and crop the image. The API can also extract information about the image, such as format, width, height, and histogram of color values. You can either receive data from the app or use Google Cloud Storage values. In addition to the Images API, you can also use the transformations provided by the Python 2.7 ** Python Imaging Library (PIL) **. (For more information, click here](https://cloud.google.com/appengine/docs/standard/python/images/))

Get EXIF

API import

from google.appengine.api import images

Open base64 with Image API

binary = base64.b64decode(base64_string)
gae_img = images.Image(binary)

Get information

I will get EXIF information from here, but when I get it using the Image Python API, I get an error if I do not follow the steps below.

# 1.Some processing on the image(conversion)
gae_img.rotate(0)
# 2.Perform conversion to image
gae_img.execute_transforms(parse_source_metadata=True)
# 3.Get EXIF information
exif = gae_img.get_original_metadata()

To explain step by step, I want to get EXIF information suddenly with gae_img.get_original_metadata (), but to do this, I want to do this with gae_img.execute_transforms (parse_source_metadata = True) in the source image metadata (EXIF). Need to be analyzed. As mentioned above, this gae_img.execute_transforms () is a method that "performs a transformation on the image", so before doing this, "assuming that the image has been transformed" is there. So, before this, I purposely wrote a seemingly meaningless process called gae_img.rotate (0). This gae_img.rotate () will be explained later.

So far, print exif

{u'MimeType': 0, u'ColorProfile': False, u'Orientation': 6, u'ColorSpace': 1, u'ImageWidth': 3264, u'ImageLength': 2448}

You can see that it is a dictionary type. The orientation of the image can be determined by the item ʻOrientation`.

print exif['Orientation']
# "1"From"8"Any of the numbers up to is output.

Now you can get the EXIF information.

Rotate the image based on EXIF information

I will summarize what I have done so far.

from google.appengine.api import images

binary = base64.b64decode(base64_string)
gae_img = images.Image(binary)

gae_img.rotate(0)
gae_img.execute_transforms(parse_source_metadata=True)
exif = gae_img.get_original_metadata()

From here, rotate the image based on ʻOrientation in ʻexif.

if exif['Orientation'] == 3:
    gae_img.rotate(180)
elif exif['Orientation'] == 6:
    gae_img.rotate(90)
elif exif['Orientation'] == 8:
    gae_img.rotate(270)
else : 
    gae_img.rotate(0)

converted_img = gae_img.execute_transforms(parse_source_metadata=True)

You can rotate the image by 90 degrees with gae_img.rotate (). As mentioned above, due to the nature of gae_img.execute_transforms (), an error will occur if the image is not converted once, so ʻelse` is used to perform the conversion once.

This time, I don't think that the images that are flipped upside down or flipped horizontally are not sent, so the processing for 2,4,5,7 is not written. Then, after rotating, execute gae_img.execute_transforms (parse_source_metadata = True) to execute the changes made to the image.

Upload to Cloud Storage

From here, upload to Cloud Storage. As a procedure

  1. Determine environment variables
  2. Open the file in a location suitable for your environment
  3. Write to the opened destination (upload) It looks like this. Let's take a look at the code.
import cloudstorage as gcs

def upload_gcs(self, name, type, binary):
    #Extract environment variables
    env = os.getenv('SERVER_SOFTWARE')
    #Upload to Google Cloud Storage in any environment
    if (env and (env.startswith('Google App Engine/') or env.startswith('Development/'))):
        # FileLogic.GCS_The ID contains a url that indicates the location to save.
        file_url = FileLogic.GCS_ID + name
        #Open file with Google Cloud Storage API
        with gcs.open(file_url, 'w', content_type=type, options={'x-goog-acl': 'public-read'}) as gcs_file:
            #Writing (uploading) images
            gcs_file.write(binary)
            # FileLogic.GCS_HOST_The host name is pre-filled in NAME
            file_url = FileLogic.GCS_HOST_NAME + file_url
    else:
        #Write locally if not in any environment
        file_url = 'local_file/' + name
        with open(file_url, 'w') as file:
            file.write(binary)
    return file_url

Open with the Google Cloud Storage API to open an existing object in your Cloud Storage bucket. At this time, you can open the file in write mode by passing 'w'. After opening any location in write mode, upload the image with write.

Recommended Posts

GAE --With Python, rotate the image based on the rotation information of EXIF and upload it to Cloud Storage.
Convert the spreadsheet to CSV and upload it to Cloud Storage with Cloud Functions
Return the image data with Flask of Python and draw it to the canvas element of HTML
Process the gzip file UNLOADed with Redshift with Python of Lambda, gzip it again and upload it to S3
Upload data to s3 of aws with a command and update it, and delete the used data (on the way)
[Python] Change the Cache-Control of the object uploaded to Cloud Storage
How to upload files to Cloud Storage with Firebase's python SDK
POST the image selected on the website with multipart / form-data and save it to Amazon S3! !!
How to install OpenCV on Cloud9 and run it in Python
Image upload & download to Azure Storage. With Python + requests + REST API
Convert the result of python optparse to dict and utilize it
How to update the python version of Cloud Shell on GCP
Upload file to GCP's Cloud Storage (GCS) ~ Load with local Python
PhytoMine-I tried to get the genetic information of plants with Python
Find the white Christmas rate by prefecture with Python and map it to a map of Japan
Put Cabocha 0.68 on Windows and try to analyze the dependency with Python
How to crop the lower right part of the image with Python OpenCV
Try to image the elevation data of the Geographical Survey Institute with Python
Work memo to migrate and update Python 2 series scripts on the cloud to 3 series
I ran GhostScript with python, split the PDF into pages, and converted it to a JPEG image.
I tried to get the movie information of TMDb API with Python
The story of making a tool to load an image with Python ⇒ save it as another name
[python] Send the image captured from the webcam to the server and save it
Read the data of the NFC reader connected to Raspberry Pi 3 with Python and send it to openFrameworks with OSC
How to save the feature point information of an image in a file and use it for matching
Try to measure the position of the object on the desk (real coordinate system) from the camera image with Python + OpenCV
Use Pillow to make the image transparent and overlay only part of it
A record of the time it took to deploy mysql on Cloud9 + Rails
Introduction to Python with Atom (on the way)
[Python3] Take a screenshot of a web page on the server and crop it further
Get information equivalent to the Network tab of Chrome developer tools with Python + Selenium
I want to plot the location information of GTFS Realtime on Jupyter! (With balloon)
Extract images and tables from pdf with python to reduce the burden of reporting
I tried to automate the article update of Livedoor blog with Python and selenium.
An easy way to pad the number with zeros depending on the number of digits [Python]
Make it easy to install the ROS2 development environment with pip install on Python venv
[Note] How to write QR code and description in the same image with python
Try to Normalize Cut the image with scikit-image (although it gets angry on the way)
Image processing with Python (I tried binarizing it into a mosaic art of 0 and 1)
Starting with Python 3.10, the form returned by inspect.signature () seems to be based on typing.get_type_hints ().
Read the csv file with jupyter notebook and write the graph on top of it
I tried to compare the processing speed with dplyr of R and pandas of Python
It is easy to execute SQL with Python and output the result in Excel
Extract the table of image files with OneDrive & Python
Add information to the bottom of the figure with Matplotlib
Install selenium on Mac and try it with python
Visualize the range of interpolation and extrapolation with python
Convert the image in .zip to PDF with Python
Information for controlling the motor with Python on RaspberryPi
Rotate and scale the image before cropping [python] [OpenCV]
Use of Google Cloud Storage (GCS) with "GAE / Py"
Extract the band information of raster data with python
[Python environment maintenance] De-NeoBundle. Prepare the environment of the super convenient complementary plug-in jedi-vim with dein and set it to be comfortable
How to output the number of VIEWs, likes, and stocks of articles posted on Qiita to CSV (created with "Python + Qiita API v2")
[Python] Save the result of web scraping the Mercari product page on Google Colab to Google Sheets and display the product image as well.
I want to cut out only the face from a person image with Python and save it ~ Face detection and trimming with face_recognition ~
Use Python to monitor Windows and Mac and collect information on the apps you are working on
Get the matched string with a regular expression and reuse it when replacing on Python3
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
Recursively get the Excel list in a specific folder with python and write it to Excel.
How to know the number of GPUs from python ~ Notes on using multiprocessing with pytorch ~