将.jpg图像转换为.png

use*_*933 25 python python-2.7

我环顾四周阅读文档,发现没有办法或解决方案,所以我在这里问.是否有任何软件包可以使用Python将JPG图像转换为PNG图像?

Lev*_*von 34

您始终可以使用Python Image Library(PIL)来实现此目的.可能还有其他的包/库,但我以前用它来转换格式.

这适用于Windows下的Python 2.7(Python 2.7的Python Imaging Library 1.1.7),我在2.7.1和2.7.2中使用它

from PIL import Image

im = Image.open('Foto.jpg')
im.save('Foto.png')
Run Code Online (Sandbox Code Playgroud)

请注意,您的原始问题未提及Python的版本或您正在使用的操作系统.那可能会有所不同:)


Jan*_*ert 10

Python图像库:http://www.pythonware.com/products/pil/

来自:http://effbot.org/imagingbook/image.htm

import Image
im = Image.open("file.png")
im.save("file.jpg", "JPEG")
Run Code Online (Sandbox Code Playgroud)

保存

im.save(outfile,options ...)

im.save(outfile,format,options ...)

将图像保存在给定的文件名下.如果省略format,则格式由文件扩展名确定(如果可能).此方法返回None.

关键字选项可用于向编写者提供其他说明.如果作者无法识别选项,则会被忽略.可用选项将在本手册的后面部分介绍.

您可以使用文件对象而不是文件名.在这种情况下,您必须始终指定格式.文件对象必须实现seek,tell和write方法,并以二进制模式打开.

如果保存失败,由于某种原因,该方法将引发异常(通常是IOError异常).如果发生这种情况,该方法可能已创建该文件,并可能已向其写入数据.如有必要,由您的应用程序来删除不完整的文件.


Sem*_*ime 9

当我在单个目录中搜索文件快速转换器时,我想分享这个简短的片段,它将当前目录中的任何文件转换为 .png 或您指定的任何目标。

from PIL import Image
from os import listdir
from os.path import splitext

target_directory = '.'
target = '.png'

for file in listdir(target_directory):
    filename, extension = splitext(file)
    try:
        if extension not in ['.py', target]:
            im = Image.open(filename + extension)
            im.save(filename + target)
    except OSError:
        print('Cannot convert %s' % file)
Run Code Online (Sandbox Code Playgroud)