我想知道如何在不写一次然后复制它的情况下两次写一张图片
下载图片时,将其写入/ tmp,然后复制到想要的路径(我认为),意思是以下代码:
cover_buffer = download_pic(link)
buffer2 = cover_buffer
open(@dir + 'cover.jpg', 'wb') do |pic|
pic << cover_buffer.read()
end
open(@dir + 'cover2.jpg', 'wb') do |pic|
pic << cover_buffer2.read()
end
不起作用,因为cover_buffer和buffer2都指向写入cover.jpg时移动的同一文件。 执行该代码将正确地在cover.jpg中写入图片,但cover2.jpg将是一个空文件
答案 0 :(得分:1)
测试解决方案
在档案mysqld --initialize
中:
two_for_one.rb
命令行:
current_dir = File.expand_path(File.dirname(__FILE__))
new_file_1 = File.new(File.join(current_dir, 'image_1.png'), 'w')
new_file_2 = File.new(File.join(current_dir, 'image_2.png'), 'w')
origin_file = File.join(current_dir, 'original_image.png')
begin
File.open(origin_file, "r") do |source|
until source.eof?
chunk = source.read(1024)
new_file_1.write(chunk)
new_file_2.write(chunk)
end
end
ensure
new_file_1.close()
new_file_2.close()
end