首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何用Python中的Alpha/透明加密PNG文件?

如何用Python中的Alpha/透明加密PNG文件?
EN

Stack Overflow用户
提问于 2022-05-27 05:10:52
回答 1查看 107关注 0票数 1

因此,我有下面的Python示例代码。代码将接受PNG明文输入,并将其加密为PNG密文(加扰像素)作为输出。

但是,当我尝试使用透明的PNG (alpha通道)时,它不起作用。如何读取4通道(rgba)并将它们存储到Nummpy Array中,对它们进行加密,然后解密它们以获得原始图像?

代码语言:javascript
运行
复制
import cv2
import numpy as np
from Crypto.Cipher import AES

# https://stackoverflow.com/questions/61240967/image-encryption-using-aes-in-python
key = b'Sixteen byte key'
iv = b'0000000000000000'

# Read image to NumPy array - array shape is (300, 451, 3)
img = cv2.imread('chelsea.png')

# Pad zero rows in case number of bytes is not a multiple of 16 (just an example - there are many options for padding)
if img.size % 16 > 0:
    row = img.shape[0]
    pad = 16 - (row % 16)  # Number of rows to pad (4 rows)
    img = np.pad(img, ((0, pad), (0, 0), (0, 0)))  # Pad rows at the bottom  - new shape is (304, 451, 3) - 411312 bytes.
    img[-1, -1, 0] = pad  # Store the pad value in the last element

img_bytes = img.tobytes()  # Convert NumPy array to sequence of bytes (411312 bytes)
enc_img_bytes = AES.new(key, AES.MODE_CBC, iv).encrypt(img_bytes)  # Encrypt the array of bytes.

# Convert the encrypted buffer to NumPy array and reshape to the shape of the padded image (304, 451, 3)
enc_img = np.frombuffer(enc_img_bytes, np.uint8).reshape(img.shape)

# Save the image - Save in PNG format because PNG is lossless (JPEG format is not going to work).
cv2.imwrite('enctypted_chelsea.png', enc_img)



# Decrypt:
################################################################################
key = b'Sixteen byte key'
iv = b'0000000000000000'

enc_img = cv2.imread('enctypted_chelsea.png')

dec_img_bytes = AES.new(key, AES.MODE_CBC, iv).decrypt(enc_img.tobytes())

dec_img = np.frombuffer(dec_img_bytes, np.uint8).reshape(enc_img.shape)  # The shape of the encrypted and decrypted image is the same (304, 451, 3)

pad = int(dec_img[-1, -1, 0])  # Get the stored padding value

dec_img = dec_img[0:-pad, :, :].copy()  # Remove the padding rows, new shape is (300, 451, 3)

# Show the decoded image
cv2.imshow('dec_img', dec_img)
cv2.waitKey()
cv2.destroyAllWindows()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-27 07:09:37

如果您想使用OpenCV读取RGBA映像和16位PNG映像,则需要使用:

代码语言:javascript
运行
复制
im = cv2.imread('image.png', cv2.IMREAD_UNCHANGED)

试一试,然后检查im.shape是否为(h,w,4)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72400712

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档