Home > OS >  How do I insert results of a function into a locally stored database?
How do I insert results of a function into a locally stored database?

Time:10-23

I've written a function that returns the Width, Height, and Dominant Color of an image, and I don't know how to store the results into a database. Here's the code I have so far:

import os
from colorthief import ColorThief
from PIL import Image

os.chdir("x")


def get_details():

    for f in os.listdir("x"):
        if f.endswith(".jpg"):
            i = Image.open(f)
            fn, fext = os.path.splitext(f)
            print(f"The file name is: {fn}{fext}")
            width = i.width
            print(f"The image width is: {width}px")
            height = i.height
            print(f"The Image height is: {height}px")
            ct = ColorThief(f)
            dominant_color = ct.get_color(quality=1)
            domcol = dominant_color

            def rgb_to_hex(domcol):
                return str("#xxx" % domcol).upper()

        print(f"The Dominant Color is: {rgb_to_hex(domcol)}")


get_details()

CodePudding user response:

There are 3 general options to make a local "database":

  1. Use a SQL database such as sqlite3. This solution needs some configurations it is a relatively simple solution.

  2. Use a NoSQL type database such as MongoDB but it is more complicated to setup.

  3. Final option (and least suggested but the simplest) is to store the values as a file using pickle library.

CodePudding user response:

Ultimately, it depends on what 'database' you want to use to store the data.

A relational database like mySQL or SQL Server or Oracle will have a connection string.

A simple text file won't have a connection string like a database, but will have a file path.

There are other storage options, too.

Regardless of what and where you decide your database will be, you need a way to access it from your code. For many, many storage options, you should be able to find some exiting Python libraries to use to access them.

Again, without specifics as to what and where you want to store this data, we can only generalize, but the basic idea will be you'll need to 'open' or access your database or file, you'll need to insert a record or row, and then you'll need to save your changes. Once you decide on your platform, you can find your access library, and that library documentation should detail how to use it to save your data.

  • Related