Exemplo n.º 1
0
def convert_image(path, mode):
    im = Image.open(path)
    newim = im.convert(mode)
    time = DateTime.DateTime()
    fileName = TMP + str(time.timestamp) + "_" + fs.getFileName(path)
    newim.save(fileName)
    return fileName
Exemplo n.º 2
0
def showSource(filePath, style="default"):
    text = fs.readAllText(filePath)
    source = WebPage.WebPage.escape(text)
    title = fs.getFileName(filePath)
    return render_template("showSource.html",
                           source=source,
                           title=title,
                           style=style)
Exemplo n.º 3
0
def show_img_folder() :
  files = fs.listFiles(IMG_FOLDER)
  piclist = "<ul>"
  for f in files :
    fname = fs.getFileName(f.decode())
    piclist += "<li><img src=\"{0}\" /> {1}</li>".format(f.decode(), fname)
  piclist += "</ul>"
  return render_template("show_img_folder.html", piclist=piclist)
Exemplo n.º 4
0
def insertToApps(path) :
  title = fs.getFileName(path)
  platform = "linux"
  if Common.is_windows() :
    platform = "windows"
  sql = f"INSERT INTO Apps VALUES(NULL, '{title}', '{path}', '', '{platform}', '', '', CURRENT_DATE())"
  mysql.execute(sql)
  return
Exemplo n.º 5
0
def rotate_image(path, angle=0):
    if angle < -180 and angle > 180:
        return "Error: angle must be -180 <= p <= 180."
    im = Image.open(path)
    newim = im.rotate(angle)
    time = DateTime.DateTime()
    fileName = TMP + str(time.timestamp) + "_" + fs.getFileName(path)
    newim.save(fileName)
    return fileName
Exemplo n.º 6
0
def crop_image(path, left_top, right_bottom):
    p = left_top.split(",")
    q = right_bottom.split(",")
    xy = (int(p[0]), int(p[1]), int(q[0]), int(q[1]))
    im = Image.open(path)
    newim = im.crop(xy)
    time = DateTime.DateTime()
    fileName = TMP + str(time.timestamp) + "_" + fs.getFileName(path)
    newim.save(fileName)
    return fileName
Exemplo n.º 7
0
def insertBinaries(filePath):
    ext = fs.getExtension(filePath)
    size = fs.getFileSize(filePath)
    name = fs.getFileName(filePath)
    filePath = filePath.replace("\\", "/")
    hexa = bin2hex(filePath)
    sn = mysql_client.getValue("SELECT max(sn) FROM BINDATA") + 1
    sql = Text.format(INSERT, name, filePath, ext, hexa, size, sn)
    mysql_client.execute(sql)
    lastId = mysql_client.getValue("SELECT max(id) FROM BINDATA")
    return lastId
Exemplo n.º 8
0
def insertBinaries(filePath):
    INSERT = "INSERT INTO BINDATA(`title`, `original`, `datatype`, `data`, `info`, `size`) VALUES('{0}', '{1}', '{2}', {3}, '', {4})"
    ext = fs.getExtension(filePath)
    size = fs.getFileSize(filePath)
    fileName = fs.getFileName(filePath)
    filePath = filePath.replace("\\", "/")
    filePath = filePath.replace("'", "''")
    hexa = bin2hex(filePath)
    sql = Text.format(INSERT, fileName, filePath, ext, hexa, size)
    client = MySQL.MySQL()
    client.execute(sql)
    return
Exemplo n.º 9
0
def mirror_image(path, mode):
    im = Image.open(path)
    if mode == "mirror":
        newim = ImageOps.mirror(im)
    elif mode == "flip":
        newim = ImageOps.flip(im)
    else:
        return "Fatal error"
    time = DateTime.DateTime()
    fileName = TMP + str(time.timestamp) + "_" + fs.getFileName(path)
    newim.save(fileName)
    return fileName
Exemplo n.º 10
0
def list_files():
    folder = request.args.get("folder")
    orderby = request.args.get("orderby")
    hiddenfile = request.args.get("hiddenfile")
    # ディレクトリ一覧
    items1 = []
    folders = fs.listDirectories(folder, asstr=True)
    for f in folders:
        fn = fs.getFileName(f)
        if hiddenfile == 1:  # 隠しファイルを表示する。
            items1.append(getFileInfo(f))  # すべてのフォルダ
        else:
            if not fn.startswith("."):  # 隠しファイル(フォルダ)は表示しない。
                items1.append(getFileInfo(f))
        if orderby == "size" or orderby == "rsize":
            items1 = sortby("name", items1)
        else:
            if len(items1) > 0:
                items1 = sortby(orderby, items1)
    # ファイル一覧
    files = fs.listFiles(folder, asstr=True)
    items2 = []
    for f in files:
        fn = fs.getFileName(f)
        if hiddenfile == 1:  # 隠しファイルを表示する。
            items2.append(getFileInfo(f))  # すべてのファイル
        else:
            if not fn.startswith("."):  # 隠しファイルは表示しない。
                items2.append(getFileInfo(f))
        if len(items2) > 0:
            items2 = sortby(orderby, items2)
    # ディレクトリ一覧とファイル一覧を1つのリストにする。
    items = []
    for i in items1:
        items.append(i)
    for i in items2:
        items.append(i)
    return jsonify(items)
Exemplo n.º 11
0
def saveThumb(filePath):
    im = Image.open(filePath)
    # print(im.format, im.size, im.mode)
    if im.size[0] > im.size[1]:
        w = NEWSIZE
        h = math.floor(NEWSIZE * (im.size[1] / im.size[0]))
    else:
        w = math.floor(NEWSIZE * (im.size[0] / im.size[1]))
        h = NEWSIZE
    newsize = (w, h)
    newim = im.resize(newsize, Image.LANCZOS)
    newPath = SAVEDIR + fs.getFileName(filePath)
    newim.save(newPath)
    return newPath
Exemplo n.º 12
0
def resize_image(path, percent=50):
    if percent <= 0 and percent > 100:
        return "Error: percent must be 0 < p <= 100."
    im = Image.open(path)
    width = im.size[0]
    height = im.size[1]
    rate = percent / 100.0
    new_width = math.floor(width * rate)
    new_height = math.floor(height * rate)
    newim = im.resize((new_width, new_height))
    time = DateTime.DateTime()
    fileName = TMP + str(time.timestamp) + "_" + fs.getFileName(path)
    newim.save(fileName)
    return fileName
Exemplo n.º 13
0
def getFileInfo(f):
    if Common.is_windows():
        mode = ""
        owner = ""
        group = ""
    else:
        mode = "o{0:o}".format(fs.getAttr(f))
        owner = fs.getOwner(f)
        group = fs.getGroup(f)
    dir_or_link = ""
    if fs.isDirectory(f):
        dir_or_link = "D"
    if fs.isLink(f):
        dir_or_link += "L"
    size = fs.getFileSize(f)
    last = fs.getLastWrite(f)
    filename = fs.getFileName(f)
    item = [mode, dir_or_link, owner, group, size, last, filename]
    return item
Exemplo n.º 14
0
def main():
    print("** Videos テーブル用ビデオファイル一覧を作成または挿入する。**")
    # path 取得
    if Common.count_args() == 0:
        Common.stop(1, "使用方法: python3 InsVideos.py path insert")
    path = Common.args(0)
    # print/insert オプション取得
    insoption = False
    if Common.count_args() == 2:
        insoption = True
    # 確認
    if not insoption:
        print(f"Path = {path}, Videos テーブルに挿入 = {insoption}")
        a = Common.readline("Confirm (Y/N) > ")
        if Text.tolower(a) != 'y':
            Common.stop(2, "実行を中止しました。")
    else:
        pass
    # ビデオファイル一覧を取得する。
    vfiles = getVideoFiles(path)
    # INSERT 文を作成する。
    sql = "INSERT INTO Videos VALUES"
    for p in vfiles:
        p = p.replace("'", "''")
        fileName = FileSystem.getFileName(p)
        title = Text.left(fileName, len(fileName) - 4)
        sql += f"(NULL, '0', '{title}', '{p}', '', '', '', '', 0, 0, 0, 0, 0),\n"
        print(p)
    sql = Text.left(sql, len(sql) - 2) + ";"
    if not insoption:
        print(sql)
    if insoption:
        # INSERT 文を実行する。
        try:
            mysql = MySQL.MySQL(UID, PWD, UID)
            mysql.execute(sql)
            # 終了メッセージ
            if not insoption:
                print("正常に終了しました。")
        except Error as e:
            Common.stop("MySQL のエラーにより終了。接続条件やSQL をチェックしてください。" + e.message)
    return
Exemplo n.º 15
0
#!/usr/bin/env python3

# サブディレクトリ内にあるファイルを自ディレクトリに名前を変えてコピーする。
from Py365Lib import Common, FileSystem as fs, Text

# START
# パラメータ確認
if Common.count_args() < 1:
    Common.stop("Usage : copy_subdir_files.py directory")
mydir = Common.args(0)

# サブディレクトリ一覧を得る。
dirs = fs.listDirectories(mydir, True)

# サブディレクトリごとに繰り返す。
for d in dirs:
    print(d)
    files = fs.listFiles(d, "*", True)
    parts = Text.split("/", d)
    h = parts[len(parts) - 1]
    for f in files:
        f1 = Text.replace("/", "\\", mydir + "/" + h + "/" + fs.getFileName(f))
        f2 = Text.replace("/", "\\", mydir + "/" + h + fs.getFileName(f))
        print(f"copy \"{f1}\" \"{f2}\"")

# 終わり
print("Done.")
Exemplo n.º 16
0
  album = json["album"]
  media = json["media"]
  series = json["series"]
  mark = json["mark"]
  info = json["info"]
else :
  pass

#  ファイルリストを読む。
filename = "insert.sql"
lines = fs.readLines(filelist)
firstdata = True
sql = ""
#with open(filename, mode="w", encoding='utf_8_sig') as f :
with open(filename, mode="w", encoding='shift_jis') as f :
  f.write("INSERT INTO Videos VALUES\n")
  for path in lines :
    if firstdata :
      firstdata = False
    else :
      f.write(sql + ",\n")
    path = path.strip().replace("'", "''").replace('\\', '/')
    print(path)
    title = fs.getFileName(path)
    ext = fs.getExtension(path)
    title = title.replace(ext, "")
    sql = f"(NULL, {album}, '{title}', '{path}', '{media}', '{series}', '{mark}', '{info}', 0, 0, 0, 0, NULL)"
  f.write(sql + ";\n")
print("Done.")

Exemplo n.º 17
0
def api_send_file():
    path = request.args.get("path")
    if not fs.exists(path):
        return send_file(ALARMICON)
    filename = fs.getFileName(path)
    return send_file(path, as_attachment=True, attachment_filename=filename)
Exemplo n.º 18
0
    f"{len(files)} 個のファイルを {SIZE} x {SIZE} 以内に縮小して {SAVEPATH} に保存します。(y/n)")
if a != 'y':
    Common.stop(9, "処理を中断しました。")

if not fs.exists(SAVEPATH):
    fs.mkdir(SAVEPATH)

i = 0
for f in files:
    #fn = f.decode()
    fn = f
    ext = fs.getExtension(fn)
    if (ext == ".jpg" or ext == ".png"):
        #print(fn)
        im = Image.open(fn)
        #print(im.format, im.size, im.mode)
        im = im.convert('RGB')
        newsize = getImageSize(im)
        if im.size[0] > newsize[0] or im.size[1] > newsize[1]:
            newim = im.resize(newsize, Image.LANCZOS)
        else:
            newim = im
        newPath = SAVEPATH + fs.getFileName(fn)
        if JPEG:
            newPath = newPath.replace(".png", ".jpg")
        newim.save(newPath)
        i += 1
        print(f"{newPath} に {i} 個目のファイルを保存しました。")
    else:
        print(f"{fn} をスキップしました。")
Exemplo n.º 19
0
def get_image():
    path = request.args.get("path")
    filename = fs.getFileName(path)
    return send_file(path, as_attachment=True, attachment_filename=filename)
Exemplo n.º 20
0
def rename_files(folder):
    # 画像ファイル一覧を得る。
    print(folder)
    files = fs.listFiles(folder, asstr=True)
    # 画像ファイルをリネーム
    for fpath in files:
        #fpath = Common.from_bytes(f)
        ext = fs.getExtension(fpath).lower()
        # 画像ファイルのみを対象にする。
        if ext == ".jpg" or ext == ".png" or ext == ".gif":
            # ファイル名が nnnnnnn_pnn[.jpg] か
            fname = fs.getFileName(fpath)
            ff = Text.split("_", fname)
            if not (ext in ff[1]):
                ff[1] += ext
            if len(ff) == 3:
                # 3分割できて 'master' が含まれる場合は 'master..' 部分を削除する。
                #fname_old = fname
                fname = ff[0] + '_' + ff[1]
                #print(fname_old + " to " + fname)
            elif len(ff) != 2:
                # _ で2分割できない場合(ファイル名の形式が異なる場合)はスキップする。
                print("Skipped " + fname)
                continue
            else:
                # その他の場合は何もしない。(2分割できた場合)
                pass
            # 連続番号部分の形式を確認する。
            sf = ff[1]
            if ff[1].startswith('p'):
                if len(ff[1]) == 6 or (len(ff) == 3 and len(ff[1]) == 2):
                    # 連続番号が1桁の場合
                    sf = "p0" + Text.substring(ff[1], 1)
                    newname = folder + "/" + ff[0] + "_" + sf
                    fs.move(fpath, newname)
                    print("Renamed: " + newname)
                elif len(ff) == 3 and len(ff[1]) == 7:
                    # _master1200 があり連続番号が2桁の場合
                    newname = folder + "/" + fname
                    fs.move(fpath, newname)
                elif len(ff[1]) == 8 or (len(ff) == 3 and len(ff[1]) == 4):
                    # 連続番号が3桁または連続番号が3桁かつ _master1200 がある場合
                    sn = Text.substring(ff[1], 1)
                    if sn == '1':
                        # 連続番号が3桁かつ100番台の場合
                        sf = "q" + Text.substring(ff[1], 2)
                        newname = folder + "/" + ff[0] + "_" + sf
                        fs.move(fpath, newname)
                        print("Renamed: " + newname)
                    elif sn == '2':
                        # 連続番号が3桁かつ200番台の場合
                        sf = "r" + Text.substring(ff[1], 2)
                        newname = folder + "/" + ff[0] + "_" + sf
                        fs.move(fpath, newname)
                        print("Renamed: " + newname)
                    else:
                        # 連続番号が3桁かつ300番台以上の場合はサポートしない(スキップする)
                        pass
                else:
                    # 連続番号が2桁の場合
                    #print("Passed: " + fpath)
                    pass
        else:
            #fs.move(fpath, fpath + ".jpg")
            print("Non image passed: " + fpath)
    return
Exemplo n.º 21
0
#!/usr/bin/env python3
#  再帰的にゴミファイル (Thumbs.db, Desktop.ini) を削除する。
from Py365Lib import Common, FileSystem as fs

# パラメータを得る。
print("== 再帰的にゴミファイル (Thumbs.db, Desktop.ini) を削除する。==")
# 対象のフォルダを得る。
if Common.count_args() == 0:
    Common.stop(9, "フォルダを指定してください。")
folder = Common.args(0)
a = Common.readline(folder + "に対して再帰的にゴミファイルを削除します。よろしいですか? (y/n)")
if a != "y":
    Common.stop(1, "実行を中止しました。")

# 実行する。
files = fs.listFilesRecursively(folder, asstr=True)
for f in files:
    if fs.getFileName(f) == "Thumbs.db" or fs.getFileName(f) == "Desktop.ini":
        print("rm -v " + f)
    else:
        print(f)

print("終了。")