13
10

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.

Ruby | Gviz で Google画像検索で取得した地獄のミサワ画像をランダムに表示

Posted at

Ruby | Gviz で Google画像検索で取得した地獄のミサワ画像をランダムに表示

概要

Gviz で Google画像検索で取得した地獄のミサワ画像をランダムに表示します

仕様

  • Google画像検索のAPIを利用
  • 「地獄のミサワ」で検索した結果を取得
  • 32件取得したURLの中からランダムで4件を出力対象とする

コード

require "gviz"
require 'open-uri'
require 'json'
require 'uri'
require 'fileutils'

q = '地獄のミサワ'
results = []

8.times { |i|
  uri = URI.escape("http://ajax.googleapis.com/ajax/services/search/images?q=#{q}&v=1.0&hl=ja&safe=off&start=#{i}")
  images = open(uri)
  results += JSON.parse(images.read)['responseData']['results']
}

results.delete_if { |e|File.extname(URI.parse(e['url']).path).empty? }
FileUtils.mkdir_p('images') unless FileTest.exist?('images')

def extension_from_url(url)
  extension = File.extname(URI.parse(url).path)
  extension == '.jpeg' ? '.jpg' : extension
end

filterd_results = results.shuffle.take(4)
filterd_results.each_with_index do |record, i|
  open(record['url']) do |image|
    extension = extension_from_url(record['url'])
    File.open("./images/#{i}#{extension}", 'wb') do |f|
      f.write image.read
    end
  end
end

random_size = []
records_size = filterd_results.size

Graph do
  global layout: :neato, label:"Google 画像検索", fontsize:60, size:15, overlap:false, fontname:'MS GOTHIC'
  nodes shape: :none

  records_size.times do |i|
    extension = extension_from_url(filterd_results[i]['url'])
    node :"#{i}", image: "./images/#{i}#{extension}", width: 1
  end

  save :"google_image", :png
end

出力

4回実行してみた

出力1

google_image1.png

出力2

google_image2.png

出力3

google_image3.png

出力4

google_image4.png

13
10
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
13
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?