如何将Base64格式图片字符串转换为PNG、JPG格式并保存至文件系统
Got it, let's break down how to convert that Base64 image string into actual PNG and JPG files and save them locally. I'll cover a few common tools/languages so you can pick what works for you:
Using Python
Python makes this super straightforward with built-in modules, plus a lightweight image processing library for JPG conversion. Here's the step-by-step:
- Strip off the
data:image/png;base64,prefix from your string — that's just metadata, not the actual image data. - Decode the Base64 string to raw bytes.
- Save the bytes directly as a PNG.
- Convert the PNG to JPG (we'll use Pillow for this, since JPG doesn't support alpha channels which PNG might have).
import base64 from PIL import Image from io import BytesIO # Replace with your full Base64 string base64_str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAjwAAAJbCAIAAABvnNkvAAAACXBIWXM..." # Step 1: Remove the metadata prefix image_data = base64_str.split(",")[1] # Step 2: Decode Base64 to bytes decoded_bytes = base64.b64decode(image_data) # Step 3: Save as PNG with open("output.png", "wb") as png_file: png_file.write(decoded_bytes) print("PNG file saved as output.png") # Step 4: Convert to JPG (handle alpha channel if present) with Image.open(BytesIO(decoded_bytes)) as img: # Convert to RGB (JPG doesn't support transparency) rgb_img = img.convert("RGB") rgb_img.save("output.jpg", "JPEG", quality=90) print("JPG file saved as output.jpg")
Note: You'll need to install Pillow first if you haven't: pip install pillow
Using Node.js
If you're working in a Node environment, use built-in modules for file handling and sharp (a fast image processing library) for JPG conversion:
const fs = require('fs'); const sharp = require('sharp'); // Replace with your full Base64 string const base64Str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAjwAAAJbCAIAAABvnNkvAAAACXBIWXM..."; // Strip prefix and decode to buffer const imageBuffer = Buffer.from(base64Str.split(',')[1], 'base64'); // Save as PNG fs.writeFileSync('output.png', imageBuffer); console.log('PNG file saved as output.png'); // Convert to JPG and save sharp(imageBuffer) .jpeg({ quality: 90 }) // Adjust quality as needed (0-100) .toFile('output.jpg') .then(() => console.log('JPG file saved as output.jpg')) .catch(err => console.error('Error converting to JPG:', err));
Note: Install sharp with npm install sharp
Using Command Line Tools
If you prefer no code, use base64 (built into most OSes) and convert from ImageMagick:
- First, save your raw Base64 data (without the
data:image/png;base64,prefix) to a text file, sayimage.txt. - Run these commands:
# Convert Base64 to PNG base64 -d image.txt > output.png # Convert PNG to JPG convert output.png -quality 90 output.jpg
Note: Install ImageMagick if you don't have it: On Ubuntu use sudo apt install imagemagick, on macOS use brew install imagemagick.
内容的提问来源于stack exchange,提问作者Mr. Dandomi

