1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

複数の画像のMIMEタイプを変換する

Last updated at Posted at 2019-09-10

複数の画像のMIMEタイプを変換する

目的

前回、『拡張子とMIMEタイプが異なる画像を一覧表示する』で抽出したファイルの一覧をもとに、
目的のMIMEタイプへ変換します。(今回はjpegです)

概要

  • PHPファイルを置いてブラウザから実行できるようにする
  • imagejpeg()、imagepng()、imagegif()などの関数で任意のMIMEタイプへ画像を変換し、別ファイルとして出力する

詳細

toJpeg.php
<?php
// 変換ファイル名(ここに前回の抽出したファイルの一覧のファイル名を記載する)
$image_list =[
    'hoge.jpg',
    'fuga.jpg',
    'moge.jpg',
];

// 変換ボタンが押下されたとき
if (isset($_POST['action']) && $_POST['action'] === "change") {
    // 処理時間の計測
    $time_start = microtime(true);
    foreach($image_list as $file_name) {
        // 変換元
        $from_path = '/var/www/hoge/image/'.$file_name;
        // 変換後の出力先
        $to_path = '/var/www/hoge/toJpeg/image/'.$file_name;
        $image = @imagecreatefrompng($from_path);
        // 変換したいMIMEタイプの関数を使用して変換(今回はimagejpeg)
        imagejpeg($image, $to_path);
        imagedestroy($image);
    }

    // 更新完了メッセージを設定してリダイレクト
    $time = microtime(true) - $time_start;
    $_SESSION['message'] = "変換が完了しました(".$time."秒)<br>";
    header('Location: /toJpeg/');
    exit;
}

?><html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <title>画像のMIME変換</title>
    <script type="text/javascript">
        <!--
        function send(){
            document.check.submit();
            document.getElementById("change").disabled = "true";
            document.getElementById("change").value = "処理中";
        }
        // -->
    </script>
</head>
<body>
<h1>カテゴリバナー画像のMIME変換</h1>
<ul>
    <li>画像のMIMEタイプを変換し、/toJpeg/imageへ出力します</li>
</ul>
<?php if(isset($_SESSION['message'])) { ?>
    <?php echo $_SESSION['message']; unset($_SESSION['message']); ?>
<?php } ?>
<form name="check" action="" method="post" enctype="multipart/form-data">
    <p><input type="button" id="change" value="変換" onClick="send()" /></p>
    <input type="hidden" name="action" value="change"/>
</form>
</body>

補足

・画像枚数が多いときはタイムアウトに注意(検証用の環境に画像を落としてから実行するなどしましょう)
・変換元がgit管理外の場合など、変換元が消失した場合に損害が出ることに備えて変換元とは別の場所に出力しています

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?