今日は、画像処理と基本的な暗号化技術を組み合わせたエキサイティングなプロジェクトに取り組んでいきます。シンプルかつ効果的な方法を使用して画像を暗号化および復号化できる Python プログラムを検討します。段階的に見ていきましょう!
前提条件
この手順を進めるには、次のものが必要です:
- Python プログラミングの基礎知識
- Python がコンピューターにインストールされています。
画像処理に使用される Python イメージング ライブラリである Pillow ライブラリ。インストールするには pip install ピローを使用します。
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 関数はウィンドウを開いたままにし、ユーザー入力に応答します。
プログラムの実行中
結論
このプログラムは、ピクセル レベルでデジタル画像を操作する方法と、基本的な暗号化タスクに疑似乱数ジェネレーターを使用する方法を示します。
コーディングを楽しんで、安全を確保してください!
以上がPython を使用した簡単な画像暗号化ツールの構築の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

Pythonは、Web開発、データサイエンス、機械学習、自動化、スクリプトの分野で広く使用されています。 1)Web開発では、DjangoおよびFlask Frameworksが開発プロセスを簡素化します。 2)データサイエンスと機械学習の分野では、Numpy、Pandas、Scikit-Learn、Tensorflowライブラリが強力なサポートを提供します。 3)自動化とスクリプトの観点から、Pythonは自動テストやシステム管理などのタスクに適しています。

2時間以内にPythonの基本を学ぶことができます。 1。変数とデータ型を学習します。2。ステートメントやループの場合などのマスター制御構造、3。関数の定義と使用を理解します。これらは、簡単なPythonプログラムの作成を開始するのに役立ちます。

10時間以内にコンピューター初心者プログラミングの基本を教える方法は?コンピューター初心者にプログラミングの知識を教えるのに10時間しかない場合、何を教えることを選びますか...

fiddlereveryversings for the-middleの測定値を使用するときに検出されないようにする方法

Python 3.6のピクルスファイルのロードレポートエラー:modulenotFounderror:nomodulenamed ...

風光明媚なスポットコメント分析におけるJieba Wordセグメンテーションの問題を解決する方法は?風光明媚なスポットコメントと分析を行っているとき、私たちはしばしばJieba Wordセグメンテーションツールを使用してテキストを処理します...

正規表現を使用して、最初の閉じたタグと停止に一致する方法は? HTMLまたは他のマークアップ言語を扱う場合、しばしば正規表現が必要です...

Investing.comの反クラウリング戦略を理解する多くの人々は、Investing.com(https://cn.investing.com/news/latest-news)からのニュースデータをクロールしようとします。


ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

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

人気の記事

ホットツール

WebStorm Mac版
便利なJavaScript開発ツール

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

SublimeText3 英語版
推奨: Win バージョン、コードプロンプトをサポート!

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

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

ホットトピック



