画像をタイル状に分離して一括ダウンロードさせるジェネレーター

20190907

Logging

画像をタイル状に分離して一括ダウンロードさせるジェネレーターを
作ってみました。画像は自動的に削除されます?
あることをすれば他人の画像がアップした画像も削除されます。
ちなみに一括ダウンロードbuttonを押すと画像がサーバー上に保存され
強制ダウンロードが始まります。
動作はブラウザChromeオンリーです。
また一括ダウンロードを押すと複数のファイルを一括ダウンロードするか
どうかの問い合わせが表示されますので「はい」を
選択してください。尚、30秒以内に保存されていないファイルは
次々と削除されます。
サイトはこちらから
https://zip358.com/tool/demo5/index-14.html
ソースコードは下記になります。
ページ(base64生成+画像ダウンロード処理)

追記:zipファイルにより格納するように処理を変更しました。
参考にしたサイト:https://ex1.m-yabe.com/archives/4215

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>画像分離してダウンロード:画像分離ジェネレーター</title>
        <meta name="description" content="画像分離してダウンロード:画像分離ジェネレーター">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="../jquery/jquery-3.4.1.js"></script>
        <link rel="stylesheet" href="../bootstrap/css/bootstrap.css">
        <!-- Global site tag (gtag.js) - Google Analytics -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=UA-71682075-1"></script>
        <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-71682075-1');
        </script>        
        <style>
            body{
                background-color: black;
                color: antiquewhite;
            }
            img{
                margin:10!important;
                padding:10!important;
            }       
            #container{
                width: 100%;
            }
            #container img{
                margin:10px;   
            }       
        </style>    
    </head>
    <body>
        <span id="bat"></span><a id="dl"></a>
        <input class="form-control" type="file"></input>
        <div id="container"></div>
        <script>
            $(function(){
                $("[type=file]").on("change",function(){
                    $('#container').html("");
                    $("#bat").html("");
                    console.log($(this));
                    if(!$(this).prop('files')[0].type.match(/[png|jpg|jpge|gif]/)){
                        alert("ファイル形式エラー");
                        return false;
                    }                        
                    var canvas = document.createElement('canvas');
                    var reader = new FileReader();
                    reader.onload = function(event) {
                        var image = new Image();
                        image.onload = function() {
                            sprite = {width:50,height:50};
                            canvas.width = sprite.width;
                            canvas.height = sprite.height;
                            var ctx = canvas.getContext("2d");                            
                            var x = 0;
                            for(var i=0; i*sprite.height<image.height; i++){
                                for(var j=0; j*sprite.width<image.width; j++){
                                    ctx.drawImage(
                                    image,j*sprite.width,i*sprite.height,
                                    sprite.width,sprite.height,
                                    0,0,
                                    sprite.width,sprite.height
                                    );

                                    var spriteElement = new Image;
                                    spriteElement.src= canvas.toDataURL();
                                    $('#container').append(spriteElement);
                                }
                            }
                            $("#bat").html("<input type='button' value='一括ダウンロード' onclick='bat_img()'>");
                        }
                        image.src = event.target.result;                       
                    }
                    reader.readAsDataURL($(this).prop('files')[0]);
                    
                });
            });

            function bat_img(){
                var data = [];
                for(var i=0; i< $("img").length;i++){
                    data.push({"base64":$("img").eq(i).attr("src"),"no":i});
                }
                $.ajax({
                    type: 'POST',
                    url: 'bat_img.php',
                    data:{"obj":data},
                    dataType: 'json'
                }).done(function(obj){

                    if(obj[obj.length - 1 ].chk=="ok"){

                        var link = document.getElementById("dl");
                        link.href = obj[obj.length - 1].zippath;
                        link.download = "zipimg.zip";
                        link.click();

                        var data2 = [];
                        for(var i = 0 ; i < obj.length ; i++){
                            if(i==0){
                                data2.push({Path:obj.path,no:obj.no,t:obj.t,"zipimgpath":obj[obj.length - 1].zippath});
                            }else{
                                data2.push({Path:obj.path,no:obj.no,t:obj.t});
                            }
                            
                        }

                       var del = function(){
                            $.ajax({
                                type: 'POST',
                                url: './bat_del.php',
                                data:{"obj":data2},
                                dataType: 'json'
                            });
                        };
                        del();
                    }
                    });
                }
        </script>
    </body>
</html>
<?php
$i=0;
foreach($_POST["obj"] as $key=>$val){
    $b64 = base64_decode(str_replace("data:image/png;base64,","",$val["base64"]));
    $no = (int)$val["no"];
    $t = time();
    $Path = "./bat_img/tmp/$t-$no.png";
    $re = @file_put_contents($Path,$b64);
    if($re){
        $obj[$i]["chk"] = $re?"ok":"ng";
        $obj[$i]["name"] = "$t-$no.png";
        $obj[$i]["path"] = $Path;
        $obj[$i]["no"] = $no;
        $obj[$i]["t"] = $t;
        $i++;
    }
}
$obj[--$i]["zippath"] = zipfile($obj);

print json_encode($obj);


function zipfile($obj){
    $ZipFiles = function($obj){
        foreach($obj as $key=>$val){
           $path[] = $val["path"];
        }
        return $path;
    };
    $Zip_Files = $ZipFiles($obj);
    $zipFileName = time().'_zipimg.zip';

    set_time_limit(0);
    $zip = new ZipArchive();
    $zipTmpDir = './tmp/zip/';
    $result = $zip->open($zipTmpDir.$zipFileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE);
    if( $result !== true ){ //エラー処理
      echo 'error!';
      exit();
    }
    foreach ($Zip_Files as $key=>$filepath) {
      $filename=basename($filepath);
    // ZIP圧縮するファイルを追加
    // ファイルパス・ファイル名としないと圧縮ファイルを解凍するとフルパスになる
      $zip->addFile($filepath,$filename); 
    }
    //ZIP 出力
    $zip->close();

    return $zipTmpDir.$zipFileName;
}
<?php

unlink($_POST["obj"][0]["zipimgpath"]);
foreach($_POST["obj"] as $key=>$val){
    $Path = $val["Path"];
    $no = (int)$val["no"];
    $t = (int)$val["t"];
    
    $cmd = function(){
        foreach(glob("./bat_img/tmp/*") as $file_name){
            $command = "rm -rf " . realpath($file_name);
            exec($command);
        }    
    };
    
    if(pathinfo($Path)["extension"]=="png" and preg_match("/bat_img\/tmp/",$Path)){
        if(is_file($Path)){
            sleep(30);
            unlink($Path);
        }else{
            $cmd();
        }
    }else{
        $cmd();
    }

}

コメントは受け付けていません。

タグ

, 14, 30, 358, 4, 5, 64, archives, base, button, Chrome, com, demo, ex, html, https, index, m-yabe, tool, www, zip, アップ, オンリー, コード, こちら, こと, サーバー, サイト, ジェネレーター, ソース, タイル, ダウンロード, はい, ファイル, ブラウザ, ページ, 一括, 下記, 他人, 保存, 処理, 分離, 削除, 動作, 参考, 問い合わせ, 変更, 強制, 格納, 生成, 画像, 表示, 複数, 追記, 選択,