ホームページ バックエンド開発 Python チュートリアル Python を使用した簡単な画像暗号化ツールの構築

Python を使用した簡単な画像暗号化ツールの構築

Oct 09, 2024 pm 10:18 PM

今日は、画像処理と基本的な暗号化技術を組み合わせたエキサイティングなプロジェクトに取り組んでいきます。シンプルかつ効果的な方法を使用して画像を暗号化および復号化できる Python プログラムを検討します。段階的に見ていきましょう!

前提条件

この手順を進めるには、次のものが必要です:

  1. Python プログラミングの基礎知識
  2. Python がコンピューターにインストールされています。
  3. 画像処理に使用される Python イメージング ライブラリである Pillow ライブラリ。インストールするには pip install ピローを使用します。

  4. Tkinter は、グラフィカル ユーザー インターフェイス (GUI) の構築に使用される Python ライブラリです。インストールするには pip install tk を使用します。

このプログラムは何をするのですか?

このプログラムは、ユーザーが次のことをできるようにするグラフィカル ユーザー インターフェイス (GUI) を作成します。

  • 画像ファイルを選択
  • 出力場所を選択してください
  • シードキーを入力してください
  • 画像を暗号化または復号化します

暗号化プロセスでは、シード キーに基づいて画像のピクセルがシャッフルされ、画像が認識できなくなります。復号化プロセスではこれを逆に行い、元のイメージを復元します。

コードの説明

必要なライブラリのインポート

import os
from tkinter import Tk, Button, Label, Entry, filedialog, messagebox
from PIL import Image
import random
ログイン後にコピー
  • os は、オペレーティング システムと対話する機能を提供します。
  • tkinter は、ボタン、ラベル、入力フィールドなどの GUI 要素を提供します。
  • PIL (Pillow) を使用すると、画像を開いたり、操作したり、保存したりできます。
  • ランダムは、シードを使用して、決定論的な方法でピクセルをシャッフルするのに役立ちます。

シードランダムジェネレータ関数

def get_seeded_random(seed):
    """Returns a seeded random generator."""
    return random.Random(seed)
ログイン後にコピー

get_seeded_random 関数は、同じシード値が与えられた場合に毎回同じ方法で項目をシャッフルできるランダム オブジェクトを返します。

これは、画像の暗号化と復号化を一貫して行うための鍵となります。

画像の暗号化

def encrypt_image(input_image_path, output_image_path, seed):
    """Encrypts the image by manipulating pixel values."""
    image = Image.open(input_image_path)
    width, height = image.size
    # Get pixel data as a list
    pixels = list(image.getdata())
    random_gen = get_seeded_random(seed)

    # Create a list of pixel indices
    indices = list(range(len(pixels)))
    # Shuffle the indices using the seeded random generator
    random_gen.shuffle(indices)

    # Reorder pixels based on shuffled indices
    encrypted_pixels = [pixels[i] for i in indices]

    # Create new image
    encrypted_image = Image.new(image.mode, (width, height))
    # Apply encrypted pixels to the new image
    encrypted_image.putdata(encrypted_pixels)
    # Save the encrypted image
    encrypted_image.save(output_image_path)
    return True
ログイン後にコピー

この encrypt_image 関数内:

  • 画像をロードし、そのピクセル データを抽出します。
  • 復号化時に同じシャッフル順序が維持されるように、シードされたランダム ジェネレーターを使用してピクセル順序がシャッフルされます。
  • シャッフルされたピクセル値を使用して新しい画像を作成し、暗号化された画像として保存します。

画像の復号化

def decrypt_image(input_image_path, output_image_path, seed):
    """Decrypts the image by reversing the encryption process."""
    image = Image.open(input_image_path)
    width, height = image.size
    # Get encrypted pixel data as a list
    encrypted_pixels = list(image.getdata())
    random_gen = get_seeded_random(seed)

    # Create a new list to hold pixel indices in their original order
    indices = list(range(len(encrypted_pixels)))
    # Shuffle the indices again to get the original order
    random_gen.shuffle(indices)

    # Create a new image to hold the decrypted data
    decrypted_pixels = [None] * len(encrypted_pixels)

    # Restore original pixels using the shuffled indices
    for original_index, shuffled_index in enumerate(indices):
        decrypted_pixels[shuffled_index] = encrypted_pixels[original_index]

    # Save the decrypted image
    decrypted_image = Image.new(image.mode, (width, height))
    decrypted_image.putdata(decrypted_pixels)
    decrypted_image.save(output_image_path)
    return True
ログイン後にコピー

この decrypt_image 関数は、暗号化プロセスを逆に行うことで機能します。それ:

  • 暗号化されたイメージをロードします。
  • 同じランダム シードを使用して、ピクセルを元の順序に再シャッフルします。
  • 復号化されたピクセルを使用して新しい画像を作成し、保存します。

ファイル選択機能

def select_input_image():
    """Opens a file dialog to select an input image."""
    input_image_path = filedialog.askopenfilename(title="Select Image")
    input_image_label.config(text=input_image_path)

def select_output_image():
    """Opens a file dialog to select an output image path."""
    output_image_path = filedialog.asksaveasfilename(defaultextension=".png", filetypes=[("PNG files", "*.png"),("JPEG files", "*.jpg;*.jpeg"),("All files", "*.*")], title="Save Encrypted/Decrypted Image")

    output_image_label.config(text=output_image_path)
ログイン後にコピー

select_input_image 関数を使用すると、ユーザーはファイル ダイアログを使用して暗号化または復号化する画像を選択できます。

選択した画像パスが GUI に表示されます。

同様に、select_output_image 関数を使用すると、ユーザーは出力画像の保存場所を選択できます。

暗号化および復号化ボタンの機能

def encrypt():
    input_image_path = input_image_label.cget("text")
    output_image_path = output_image_label.cget("text")
    seed = seed_entry.get()

    if not input_image_path or not output_image_path:
        messagebox.showerror("Error", "Please select input and output images.")
        return

    if encrypt_image(input_image_path, output_image_path, seed):
        messagebox.showinfo("Success", "Image encrypted successfully!")

def decrypt():
    input_image_path = input_image_label.cget("text")
    output_image_path = output_image_label.cget("text")
    seed = seed_entry.get()

    if not input_image_path or not output_image_path:
        messagebox.showerror("Error", "Please select input and output images.")
        return

    if decrypt_image(input_image_path, output_image_path, seed):
        messagebox.showinfo("Success", "Image decrypted successfully!")
ログイン後にコピー

暗号化関数と復号化関数:

  • 選択されたファイル パスとユーザーが入力したシード値を取得します。
  • 続行する前に、ユーザーが入力イメージ パスと出力イメージ パスの両方を選択していることを確認します。
  • それぞれの encrypt_image() または decrypt_image() 関数を呼び出し、完了すると成功メッセージを表示します。

GUIの作成

root = Tk()
root.title("Image Encryption Tool")

# Create and place widgets
Label(root, text="Select Image to Encrypt/Decrypt:").pack(pady=5)
input_image_label = Label(root, text="No image selected")
input_image_label.pack(pady=5)

Button(root, text="Browse", command=select_input_image).pack(pady=5)

Label(root, text="Output Image Path:").pack(pady=5)
output_image_label = Label(root, text="No output path selected")
output_image_label.pack(pady=5)

Button(root, text="Save As", command=select_output_image).pack(pady=5)

Label(root, text="Enter Seed Key:").pack(pady=5)
seed_entry = Entry(root)
seed_entry.pack(pady=5)

Button(root, text="Encrypt Image", command=encrypt).pack(pady=5)
Button(root, text="Decrypt Image", command=decrypt).pack(pady=5)

root.mainloop()
ログイン後にコピー

ラベル、ボタン、テキスト入力フィールドは、pack() を使用して配置されます。

root.mainloop 関数はウィンドウを開いたままにし、ユーザー入力に応答します。

プログラムの実行中

Building a Simple Image Encryption Tool Using Python

結論

このプログラムは、ピクセル レベルでデジタル画像を操作する方法と、基本的な暗号化タスクに疑似乱数ジェネレーターを使用する方法を示します。

コーディングを楽しんで、安全を確保してください!

以上がPython を使用した簡単な画像暗号化ツールの構築の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Pythonを使用してテキストファイルのZIPF配布を見つける方法 Pythonを使用してテキストファイルのZIPF配布を見つける方法 Mar 05, 2025 am 09:58 AM

Pythonを使用してテキストファイルのZIPF配布を見つける方法

Pythonでファイルをダウンロードする方法 Pythonでファイルをダウンロードする方法 Mar 01, 2025 am 10:03 AM

Pythonでファイルをダウンロードする方法

Pythonでの画像フィルタリング Pythonでの画像フィルタリング Mar 03, 2025 am 09:44 AM

Pythonでの画像フィルタリング

HTMLを解析するために美しいスープを使用するにはどうすればよいですか? HTMLを解析するために美しいスープを使用するにはどうすればよいですか? Mar 10, 2025 pm 06:54 PM

HTMLを解析するために美しいスープを使用するにはどうすればよいですか?

Pythonを使用してPDFドキュメントの操作方法 Pythonを使用してPDFドキュメントの操作方法 Mar 02, 2025 am 09:54 AM

Pythonを使用してPDFドキュメントの操作方法

DjangoアプリケーションでRedisを使用してキャッシュする方法 DjangoアプリケーションでRedisを使用してキャッシュする方法 Mar 02, 2025 am 10:10 AM

DjangoアプリケーションでRedisを使用してキャッシュする方法

Natural Language Toolkit(NLTK)の紹介 Natural Language Toolkit(NLTK)の紹介 Mar 01, 2025 am 10:05 AM

Natural Language Toolkit(NLTK)の紹介

TensorflowまたはPytorchで深い学習を実行する方法は? TensorflowまたはPytorchで深い学習を実行する方法は? Mar 10, 2025 pm 06:52 PM

TensorflowまたはPytorchで深い学習を実行する方法は?

See all articles