首頁 後端開發 Python教學 使用 Python 建立簡單的圖像加密工具

使用 Python 建立簡單的圖像加密工具

Oct 09, 2024 pm 10:18 PM

今天,我們將深入研究一個令人興奮的項目,該項目將圖像處理與基本加密技術相結合。我們將探索一個可以使用簡單而有效的方法加密和解密映像的 Python 程式。讓我們一步步分解吧!

先決條件

要跟隨,您應該:

  1. Python 程式設計基礎。
  2. Python 安裝在您的電腦上。
  3. Pillow 函式庫,這是一個用於處理影像的 Python 成像庫。使用 pip installpillow 來安裝。

  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)讓我們可以打開、操作和保存圖像。
  • random 幫助我們使用 種子.
  • 以決定的方式來洗牌

種子隨機產生器函數

def get_seeded_random(seed):
    """Returns a seeded random generator."""
    return random.Random(seed)
登入後複製

get_seed_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() 函數並在完成後顯示成功訊息。

建立圖形使用者介面

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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1677
14
CakePHP 教程
1431
52
Laravel 教程
1334
25
PHP教程
1280
29
C# 教程
1257
24
Python與C:學習曲線和易用性 Python與C:學習曲線和易用性 Apr 19, 2025 am 12:20 AM

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

學習Python:2小時的每日學習是否足夠? 學習Python:2小時的每日學習是否足夠? Apr 18, 2025 am 12:22 AM

每天學習Python兩個小時是否足夠?這取決於你的目標和學習方法。 1)制定清晰的學習計劃,2)選擇合適的學習資源和方法,3)動手實踐和復習鞏固,可以在這段時間內逐步掌握Python的基本知識和高級功能。

Python vs.C:探索性能和效率 Python vs.C:探索性能和效率 Apr 18, 2025 am 12:20 AM

Python在開發效率上優於C ,但C 在執行性能上更高。 1.Python的簡潔語法和豐富庫提高開發效率。 2.C 的編譯型特性和硬件控制提升執行性能。選擇時需根據項目需求權衡開發速度與執行效率。

Python vs. C:了解關鍵差異 Python vs. C:了解關鍵差異 Apr 21, 2025 am 12:18 AM

Python和C 各有優勢,選擇應基於項目需求。 1)Python適合快速開發和數據處理,因其簡潔語法和動態類型。 2)C 適用於高性能和系統編程,因其靜態類型和手動內存管理。

Python標準庫的哪一部分是:列表或數組? Python標準庫的哪一部分是:列表或數組? Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

Python:自動化,腳本和任務管理 Python:自動化,腳本和任務管理 Apr 16, 2025 am 12:14 AM

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

科學計算的Python:詳細的外觀 科學計算的Python:詳細的外觀 Apr 19, 2025 am 12:15 AM

Python在科學計算中的應用包括數據分析、機器學習、數值模擬和可視化。 1.Numpy提供高效的多維數組和數學函數。 2.SciPy擴展Numpy功能,提供優化和線性代數工具。 3.Pandas用於數據處理和分析。 4.Matplotlib用於生成各種圖表和可視化結果。

Web開發的Python:關鍵應用程序 Web開發的Python:關鍵應用程序 Apr 18, 2025 am 12:20 AM

Python在Web開發中的關鍵應用包括使用Django和Flask框架、API開發、數據分析與可視化、機器學習與AI、以及性能優化。 1.Django和Flask框架:Django適合快速開發複雜應用,Flask適用於小型或高度自定義項目。 2.API開發:使用Flask或DjangoRESTFramework構建RESTfulAPI。 3.數據分析與可視化:利用Python處理數據並通過Web界面展示。 4.機器學習與AI:Python用於構建智能Web應用。 5.性能優化:通過異步編程、緩存和代碼優

See all articles