|
import gradio as gr |
|
from PIL import Image |
|
import tempfile |
|
import os |
|
|
|
def convert_image(input_image: Image.Image, output_format: str, quality: int | float): |
|
"""画像を指定した形式に変換する関数""" |
|
if input_image is None: |
|
return None, None |
|
|
|
img = input_image |
|
|
|
|
|
if output_format.lower() == 'png': |
|
if img.mode != 'RGBA' and 'A' not in img.mode: |
|
img = img.convert('RGBA') |
|
elif img.mode == 'RGBA': |
|
img = img.convert('RGB') |
|
|
|
|
|
|
|
args = {} |
|
|
|
fmt = output_format.lower() |
|
quality = int(quality) |
|
|
|
if "webp" in fmt: |
|
lossless = "lossless" in fmt |
|
fmt = "WEBP" |
|
args["quality"] = quality |
|
if lossless: |
|
args["lossless"] = True |
|
elif "jpeg" in fmt: |
|
fmt = "JPEG" |
|
args["quality"] = quality |
|
|
|
|
|
with tempfile.NamedTemporaryFile(delete=False, suffix=f'.{fmt.lower()}') as temp_file: |
|
temp_filename = temp_file.name |
|
|
|
img.save(temp_filename, format=fmt, **args) |
|
|
|
return img, temp_filename |
|
|
|
|
|
with gr.Blocks(title="画像形式変換ツール") as demo: |
|
gr.Markdown("## お嬢様の画像形式変換ツール") |
|
gr.Markdown("画像をアップロードして、変換したい形式を選んでくださいませ。") |
|
|
|
with gr.Row(): |
|
with gr.Column(): |
|
convert_btn = gr.Button("変換する") |
|
output_format = gr.Dropdown( |
|
choices=["png", "webp (lossless)", "jpeg", "webp (lossy)"], |
|
value="webp (lossless)", |
|
label="変換後の形式" |
|
) |
|
quality = gr.Slider(0, 100, step=1, value=100, label="品質 (JPEG および WebP のみ)") |
|
input_image = gr.Image(type="pil", label="入力画像", format="png") |
|
|
|
with gr.Column(): |
|
download_btn = gr.Button("ダウンロード") |
|
download_file = gr.File(label="変換ファイル") |
|
output_image = gr.Image(label="変換された画像") |
|
|
|
convert_btn.click( |
|
fn=convert_image, |
|
inputs=[input_image, output_format, quality], |
|
outputs=[output_image, download_file] |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
demo.launch() |