在命令行输入参数,完成指定文件的缩放,并存储到新文件,命令行参数如下 zoom file1.bmp 200 file2.bmp怎么实现
时间: 2023-11-22 22:55:52 浏览: 25
可以使用Pillow库来实现图片缩放和存储。以下是示例代码:
``` python
from PIL import Image
import sys
# 获取命令行参数
args = sys.argv
if len(args) != 4:
print("Usage: zoom input_file scale output_file")
sys.exit(1)
input_file = args[1]
scale = int(args[2])
output_file = args[3]
# 打开输入文件
with Image.open(input_file) as img:
# 计算新的大小
width, height = img.size
new_width, new_height = int(width * scale / 100), int(height * scale / 100)
# 进行缩放
new_img = img.resize((new_width, new_height))
# 保存到输出文件
new_img.save(output_file)
```
在命令行中运行 `python zoom.py file1.bmp 200 file2.bmp`,即可将 `file1.bmp` 缩放到原来的 200%,并保存到 `file2.bmp` 文件中。
相关问题
编写一个程序,可以在命令行输入参数,完成指定文件的缩放,并存储到新文件,命令行参数如下 zoom file1.bmp 200 file2.bmp 第一个参数为可执行程序名称,第二个参数为原始图像文件名,第三个参数为缩放比例(百分比),第四个参数为新文件名
以下是一个简单的Python程序,可以实现您所描述的功能:
```python
import sys
from PIL import Image
if len(sys.argv) != 4:
print("Usage: zoom source_file scale_percent target_file")
sys.exit()
source_file = sys.argv[1]
scale_percent = int(sys.argv[2])
target_file = sys.argv[3]
try:
with Image.open(source_file) as im:
width, height = im.size
new_width = int(width * scale_percent / 100)
new_height = int(height * scale_percent / 100)
new_im = im.resize((new_width, new_height))
new_im.save(target_file)
except FileNotFoundError:
print(f"{source_file} not found")
```
您可以将以上代码保存为zoom.py,并在命令行中输入以下命令来运行程序:
```
python zoom.py file1.bmp 200 file2.bmp
```
其中,file1.bmp 是原始图像文件名,200 表示缩放比例为200%(即放大两倍),file2.bmp 是新文件名。程序会自动读取原始图像,按照指定比例缩放,并将结果保存为新文件。如果原始图像文件不存在,则会输出错误提示信息。
编写一个程序,可以在命令行输入参数,完成指定文件的缩放,并存储到新文件,命令行参数如下: zoom file1.bmp 200 file2.bmp 第一个参数为可执行程序名称,第二个参数为原始图像文件名,第三个参数为缩放比例(百分比),第四个参数为新文件名。
好的,这是一个简单的 Python 代码示例,可以实现您的需求:
```python
from PIL import Image
import sys
if len(sys.argv) != 5:
print("Usage: zoom file1.bmp 200 file2.bmp")
sys.exit()
filename_in = sys.argv[1]
scale = float(sys.argv[2]) / 100
filename_out = sys.argv[4]
try:
with Image.open(filename_in) as im:
width, height = im.size
new_width = int(width * scale)
new_height = int(height * scale)
im_resized = im.resize((new_width, new_height))
im_resized.save(filename_out)
print("Image resized and saved successfully.")
except IOError:
print("Unable to open or save file.")
```
这段代码使用了 Pillow 库,可以通过 pip 安装。您只需要在命令行中输入 "python zoom.py file1.bmp 200 file2.bmp",其中 zoom.py 是文件名,即可完成图片缩放并保存到指定文件。