如何在Python中将图像转数组及JPG转二进制数组用于Scrambler处理
Hey there! Let's walk through exactly how to turn your JPG into a binary array, run it through your Scrambler, and save the final result. We'll use two go-to libraries that every Python image dev relies on—no fancy external tools needed.
First, Install Required Libraries
You'll need Pillow (for seamless image handling) and numpy (for array operations). If you don't have them yet, run this in your terminal:
pip install pillow numpy
Option 1: Raw File Binary Array (If Your Scrambler Works with File Bytes)
If your Scrambler processes the raw binary data of the JPG file (not the actual pixel values), this is the simplest approach. We'll read the file directly into a byte array:
# Read the JPG as a raw binary byte array with open("input_image.jpg", "rb") as file: binary_array = bytearray(file.read()) # Run your Scrambler processing here # scrambled_array = your_scrambler_function(binary_array) # Save the processed binary array back to a file with open("scrambled_output.jpg", "wb") as file: file.write(scrambled_array)
Option 2: Pixel-Based Binary Array (If Your Scrambler Works with Image Pixels)
If your Scrambler operates on the actual pixel data (like RGB values), we'll convert the image to a numpy pixel array first, then turn that into a binary stream:
from PIL import Image import numpy as np # Open the JPG and convert to a numpy pixel array img = Image.open("input_image.jpg") pixel_array = np.array(img) # Shape: (height, width, channels) e.g., (1080, 1920, 3) for RGB # Convert the pixel array to a binary byte stream binary_pixel_array = pixel_array.tobytes() # Process with your Scrambler # scrambled_binary_pixels = your_scrambler_function(binary_pixel_array) # If you need to convert back to an image and save: # First, convert the processed binary back to a numpy array (match original shape/dtype) processed_pixel_array = np.frombuffer(scrambled_binary_pixels, dtype=pixel_array.dtype).reshape(pixel_array.shape) # Turn back into an Image object and save processed_img = Image.fromarray(processed_pixel_array) processed_img.save("scrambled_pixel_output.jpg")
Pro Tips for Your Scrambler
- If your Scrambler expects a specific image mode (like grayscale instead of RGB), convert the image first with
img = Image.open("input_image.jpg").convert("L")(for 8-bit grayscale). - Always double-check the dtype and shape of your numpy array when converting back—mismatches will cause corrupted images.
- Add basic error handling to catch missing files or invalid images:
try: img = Image.open("input_image.jpg") except FileNotFoundError: print("Error: Input image not found!") except Exception as e: print(f"Error opening image: {e}")
内容的提问来源于stack exchange,提问作者Kamil_K

