LoginSignup
1
0

More than 3 years have passed since last update.

RubyでExcelスクリプトを書いた

Last updated at Posted at 2019-08-05

動画をパラパラ漫画にしたくてツールを作った。

ツールで自動化すること

1)パラパラ漫画にする動画を特定フレームごとに静止画に抜き出す。
2)印刷用に静止画を加工しやすいように余白をつけて並べる。
までをツールで行う。
印刷かけて裁断して閉じるまでは手でやることにした。

前置き

印刷テンプレートはなんでも良いのでExcelとした。
Excelをいじくる方法はさまざまな方法があるがVBAはいまさらなのでパス。
いまどきっぽいのでRubyにしてみた。

使う人用の準備編

以下の3つを実行Windows-PCにセットアップ。

Rubyインストール

https://www.artonx.org/data/asr/
1.PNG
から「ActiveScriptRuby」をインストール。
ウィザードで入れてパスを自分で追加

Excel向けライブラリをダウンロード

http://www.tech-notes.org/excel_lib/
2.PNG
から「RubydeExcel Ver1.02」をダウンロード。
解凍して中身の「excel_lib.rb」をlib/ruby/site_rubyに置く。

ffmegをインストール

https://ffmpeg.zeranoe.com/builds/
3.PNG
からダウンロードして解凍して適切な場所においてからパスを通す。

自作スクリプト

2部構成
1)mp4の動画を指定した時間間隔で静止画に落とす。

#!ruby -Ks
#必要ライブラリロード
require 'excel_lib'
require 'win32ole'

images = []

#------- ユーザで直すもの --------------
#何秒間隔で静止画に落とすか(※適宜修正ください)
frame_per_sec = 1

#どのフレームから静止画に落とすか
start_image_frame = 1

#何フレームを静止画に落とすか(※出力する動画の長さ(単位は静止画枚数)です。「動画の長さ÷静止画間隔」で修正ください)
image_frame_num = 126
#---------------------------------------

#出力先にすでにある静止画は消す。
for t in Dir.glob("./frame/*.jpg")
  File.delete(t)
  #p t
end

#動画を静止画に落とします。
for num in start_image_frame..image_frame_num do
  fname = "frame/1_%d.jpg" % num
  images.push(fname)
  command = "ffmpeg -i input_video/1.mp4 -ss %d -vframes 1 -f image2 -s 320x240 %s" % [frame_per_sec*num, fname]
  system(command)
  sleep(0.3)
end

2)静止画をExcelテンプレートに順に並べる。

#!ruby -Ks
#必要ライブラリロード
require 'excel_lib'
require 'win32ole'

#ファイルの絶対パス取得サブルーチン
def getAbsolutePath(path)
  fso = WIN32OLE.new('Scripting.FileSystemObject')
  return fso.GetAbsolutePathname(path)
end

# EXCELテンプレートをコピーで開く
excel = Excel.new.copy_book("template.xlsx")
sheet1 = excel.sheets("sheet1")

# タイル状に静止画を貼り付け
xind = 0
yind = 0
sind = 0
for pic in Dir.glob("./frame/*.jpg") do
  sheet1.Shapes.AddPicture(
    getAbsolutePath(pic),
    false, true, 35+(265*xind)+(794*sind), 19+(188*yind), 218, 152);

  xind += 1
  if xind>2 then
    xind = 0
    yind += 1
    if yind>2 then
      xind = 0
      yind = 0
      sind += 1
    end
  end
  sleep(0.3)
end

以上です。

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