📅  最后修改于: 2023-12-03 15:23:19.791000             🧑  作者: Mango
在 SQLite 中,可以使用 BLOB 类型来存储二进制数据,例如图像。但是,如果您希望将图像文件存储在文件夹中并仅在数据库中保存图像路径,该怎么办?在这篇文章中,我们将探讨如何在 SQLite 数据库中的文件夹和图像路径中捕获图像并将它们存储在文件夹中。
首先,我们需要创建一个 SQLite 数据库以存储图像路径。您可以使用 SQLite 的命令行工具或任何 SQLite 客户端来创建一个数据库。下面是一个示例:
CREATE TABLE images (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
path TEXT NOT NULL
);
该表将用于存储图像的 ID、名称和路径。
使用任何编程语言(如 Python、Java 或 C#)连接到 SQLite 数据库,然后捕获要存储在文件夹中的图像。
import sqlite3
import os
conn = sqlite3.connect('images.db')
cursor = conn.cursor()
# Create a table for images
cursor.execute('''CREATE TABLE images (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
path TEXT NOT NULL
)''')
# Open a file and read the contents
with open("image.png", "rb") as image_file:
image_data = image_file.read()
# Generate a unique filename
filename = os.path.splitext(os.path.basename("image.png"))[0] + "_" + str(id) + ".png"
# Write the file to disk
with open(os.path.join("images", filename), "wb") as out_file:
out_file.write(image_data)
# Insert the image path into the database
cursor.execute("INSERT INTO images (name, path) VALUES (?, ?)", (filename, "images/" + filename))
conn.commit()
conn.close()
上面的代码做了以下事情:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
private Connection connect() {
String url = "jdbc:sqlite:images.db";
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
public void insertImage(String name, String path) {
String query = "INSERT INTO images(name,path) VALUES(?,?)";
int id = 0;
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, name);
pstmt.setString(2, path);
pstmt.executeUpdate();
// Get the ID of the newly inserted record
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
id = rs.getInt(1);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
try {
// Open the input and output files
FileInputStream input = new FileInputStream("image.png");
FileOutputStream output = new FileOutputStream(new File("images/" + name));
// Write the file to disk
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
input.close();
output.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
Main app = new Main();
app.insertImage("image.png", "images/image.png");
}
}
上面的 Java 代码做了以下事情:
using System;
using System.Data.SQLite;
using System.IO;
class Program {
static void Main(string[] args) {
SQLiteConnection cn = new SQLiteConnection("Data Source=images.db");
// Create a table for images
cn.Open();
SQLiteCommand cmd = new SQLiteCommand("CREATE TABLE images (id INTEGER PRIMARY KEY, name TEXT NOT NULL, path TEXT NOT NULL)", cn);
cmd.ExecuteNonQuery();
// Open the input file and read the contents
byte[] fileData = File.ReadAllBytes("image.png");
// Generate a unique filename
int id = 1; // This should be the ID of the new record
string filename = Path.GetFileNameWithoutExtension("image.png") + "_" + id + Path.GetExtension("image.png");
// Write the file to disk
File.WriteAllBytes("images/" + filename, fileData);
// Insert the image path into the database
cmd = new SQLiteCommand("INSERT INTO images (name, path) VALUES (@name, @path)", cn);
cmd.Parameters.AddWithValue("@name", filename);
cmd.Parameters.AddWithValue("@path", "images/" + filename);
cmd.ExecuteNonQuery();
cn.Close();
}
}
上面的 C# 代码做了以下事情:
捕获图像并将其存储在文件夹中后,我们可以从数据库中检索出图像路径并将其用于恢复图像。如果您希望在检索后从文件夹中删除图像,请确保进行备份。
import sqlite3
import os
conn = sqlite3.connect('images.db')
cursor = conn.cursor()
# Retrieve the image path from the database
cursor.execute("SELECT path FROM images WHERE name = 'image.png'")
path = cursor.fetchone()[0]
# Generate a filename from the path
filename = os.path.basename(path)
# Read the file contents and store in memory
with open(os.path.join("images", filename), "rb") as file:
image_data = file.read()
conn.close()
# Save the image to a file
with open("new_image.png", "wb") as file:
file.write(image_data)
# Delete the file from the folder
os.remove(os.path.join("images", filename))
上面的 Python 代码做了以下事情:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
private Connection connect() {
String url = "jdbc:sqlite:images.db";
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
public void retrieveImage(String name) {
String query = "SELECT path FROM images WHERE name=?";
String path = "";
byte[] data = null;
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, name);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
path = rs.getString("path");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
try {
// Read the file contents and store in memory
Path imagePath = Paths.get("images/" + path);
data = Files.readAllBytes(imagePath);
// Save the image to a file
FileOutputStream output = new FileOutputStream(new File("new_image.png"));
output.write(data);
// Delete the file from the folder
imagePath.toFile().delete();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
Main app = new Main();
app.retrieveImage("image.png");
}
}
上面的 Java 代码做了以下事情:
using System;
using System.Data.SQLite;
using System.IO;
class Program {
static void Main(string[] args) {
SQLiteConnection cn = new SQLiteConnection("Data Source=images.db");
// Retrieve the image path from the database
cn.Open();
SQLiteCommand cmd = new SQLiteCommand("SELECT path FROM images WHERE name='image.png'", cn);
string path = cmd.ExecuteScalar().ToString();
// Read the file contents and store in memory
byte[] fileData = File.ReadAllBytes("images/" + path);
// Save the image to a file
File.WriteAllBytes("new_image.png", fileData);
// Delete the file from the folder
File.Delete("images/" + path);
cn.Close();
}
}
上面的 C# 代码做了以下事情:
在 SQLite 数据库中存储文件夹和图像路径是一种很有用的技术,可以让您有效地组织和管理您的数据。在本文中,我们探讨了如何捕获图像并将其存储在文件夹中,以及如何从文件夹中恢复图像并从中删除。这将使您能够更好地管理和组织您的图像。