简体   繁体   English

在 python 中将图像 PNG 转换为 JPG

[英]Converting Images PNG to JPG in python

As you can see my code for converting to png to jpg.如您所见,我将 png 转换为 jpg 的代码。 I am getting so many errors in below the code.What I have to do?我在代码下方遇到了很多错误。我必须做什么? Can any one tell how to resolve the issue.任何人都可以告诉如何解决这个问题。

import tkinter as tk
from tkinter import filedialog
from PIL import Image

root = tk.Tk()

canvas1 = tk.Canvas(root, width=300, height=250, bg='azure3', relief='raised')
canvas1.pack()

label1 = tk.Label(root, text='File Conversion Tool', bg='azure3')
label1.config(font=('helvetica', 20))
canvas1.create_window(150, 60, window=label1)

def getPNG():
    global im1

    import_file_path = filedialog.askopenfilename()
    im1 = Image.open(import_file_path)


browseButton_PNG  = tk.Button(text="      Import PNG File     ",command=getPNG, bg='royalblue', fg='white', font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 130, window=browseButton_PNG)

def convertToJPG():
    global im1
    export_file_path = filedialog.asksaveasfilename(defaultextension='.jpg')
    im1.save(export_file_path)

saveAsButton_JPG = tk.Button(text='Convert PNG To JPG', command=convertToJPG, bg='royalblue', fg='white', font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 180, window=saveAsButton_JPG)

root.mainloop()

Output Output

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\yashk\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:/Users/yashk/PycharmProjects/png_to_jpg_convertor/png_to_jpg.py", line 27, in convertToJPG
    im1.save(export_file_path)
NameError: name 'im1' is not defined

here my attempt at making your code work:在这里我尝试让你的代码工作:

import tkinter as tk
from tkinter import filedialog
from PIL import Image

pippo = tk.Tk()

canvas1 = tk.Canvas(pippo, width=300, height=250, bg='azure3', relief='raised')
canvas1.pack()

label1 = tk.Label(pippo, text='File Conversion Tool', bg='azure3')
label1.config(font=('helvetica', 20))
canvas1.create_window(150, 60, window=label1)

im1 = None

def getPNG():
    global im1

    import_file_path = filedialog.askopenfilename()
    im1 = Image.open(import_file_path).convert('RGB')
    saveAsButton_JPG["state"] = "normal"
    
    
browseButton_PNG  = tk.Button(text="      Import PNG File     ",command=getPNG, bg='royalblue', fg='white', font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 130, window=browseButton_PNG)




def convertToJPG():
    global im1
    export_file_path = filedialog.asksaveasfilename(defaultextension='.jpg')
    im1.save(export_file_path)
    im1 = None

saveAsButton_JPG = tk.Button(text='Convert PNG To JPG', command=convertToJPG, bg='royalblue', fg='white', font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 180, window=saveAsButton_JPG)



# pippo.mainloop()

LOOP_ACTIVE = True
while LOOP_ACTIVE:
    if im1 == None:
        saveAsButton_JPG["state"] = "disabled"
    else:
        browseButton_PNG['fg'] = 'red'
    pippo.update()

let me know if its better, I changed root.mainloop() whit a while True infinite loop that does root.update() and check if an image has been selected, if not the convert button is disabled, after each conversion the image selected is removed from memory so the convert button gets disabled.让我知道它是否更好,我改变了 root.mainloop() whit while 真正的无限循环执行 root.update() 并检查是否已选择图像,如果没有,转换按钮被禁用,每次转换后选择图像从 memory 中删除,因此转换按钮被禁用。 Selecting a png image does enable the convert button, and makes select button text red选择 png 图像会启用转换按钮,并使 select 按钮文本变为红色

I am adding input:我正在添加输入:

在此处输入图像描述

and output:和 output:

在此处输入图像描述 because OP says it doesnt work因为 OP 说它不起作用

Stack overflow has a number of answers to this question. Stack Overflow 对这个问题有很多答案。 type the following into stack overflow search tool.在堆栈溢出搜索工具中键入以下内容。

is:Convert png to jpeg using Pillow是:使用 Pillow 将 png 转换为 jpeg

Here is a code snippet that converts png to jpg and can resize at the same time.这是一个将 png 转换为 jpg 并且可以同时调整大小的代码片段。


import os
import tkinter as tk
from tkinter import filedialog as fido
from PIL import Image

master = tk.Tk()

# Choose True and set relevant x,y dimensions
resize, x, y = False, 500, 500

def convert():

    image_name = fido.askopenfilename(title = "Pick a png file")
    if image_name:

        image_png, image_ext = os.path.splitext(image_name)
        # Check before loading!
        if image_ext.lower() == ".png":

            if resize:
                im = Image.open(image_name).resize(( x, y ))
            else:
                im = Image.open(image_name)

            # Check after loading!
            if im.mode != "RGB":

                # Do it
                rgb_im = im.convert("RGB")
                image_jpg = image_png + ".jpg"
                rgb_im.save(image_jpg, quality = 95)
                print("Complete! Converted png to jpg")

            else:
                print("Failed! Not a real png file")
            # clean up
            im.close()
        else:
            print("Failed! Not a png file")
    else:
        print("Cancel png to jpg conversion")

    master.destroy()

b = tk.Button(
    master, text = "Convert PNG to JPG", command = convert)
b.pack(fill = tk.BOTH, expand = True)

master.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM