How to Encode Media in Base64 Given Url in Ruby

How to encode media in base64 given URL in Ruby

The open method:

open("http://image.com/img.jpg")

is returning a Tempfile object, while encode64 expects a String.

Calling read on the tempfile should do the trick:

ActiveSupport::Base64.encode64(open("http://image.com/img.jpg") { |io| io.read })

Upload base64 encoded image with paperclip - Rails

This is my solution, using Paperclip.io_adapters.for(image) where image is base64 string.

def create_image image, image_name, cat
signature = Paperclip.io_adapters.for(image)
base_name = File.basename(image_name,File.extname(image_name))
signature.original_filename = "#{base_name}.jpg"
media_img = Media::Image.new()
media_img.image = signature
media_img.company_id = current_company_id
media_img.type = cat
media_img.save
end

Ruby version of CryptoJS Base64 stringify

CrytoJS' HmacSHA1 returns binary data whereas Ruby's hexdigest returns a (hex-encoded) string representation.

To get the same result, have to base64-encode the binary digest instead:

secret = 'NzAwZmIwMGQ0YTJiNDhkMzZjYzc3YjQ5OGQyYWMzOTI='
signature = "date: Mon, 25 Jul 2016 16:36:07 GMT\nx-mod-nonce: 28154b2-9c62b93cc22a-24c9e2-5536d7d"

hmac = OpenSSL::HMAC.digest('sha1', secret, signature)
#=> "X\x13+\xFD\x87a\xCA\xC6\xE6\x88\x81$u:\xDF\xDA\x13\xFBI\xF0"

Base64.strict_encode64(hmac)
#=> "WBMr/YdhysbmiIEkdTrf2hP7SfA="

Ruby - How to set data_uri (base64) filename with Shrine

You can add the filename by updating the file_data column after assigning the data URI:

anex = Anex.new(file_data_uri: data_uri)
file = anex.file
file.metadata["filename"] = "test.png"
anex.file_data = file.to_json

How to upload an image at url for Google Vision API - Ruby

If you are going to use Google-Cloud-Vision gem, you need to follow the gem documentation (uses non encoded images), maybe he did that under the hood..

Based on the documentation of the gem google-cloud-vision , you can convert your image like the code bellow

open image_url do |img|
@vision = Google::Cloud::Vision.new

image = @vision.image(img)
# you can also use the class method from_io
# image = Google::Cloud::Vision::Image.from_io(img, @vision)

annotation = @vision.annotate(image, labels: true, text: true)
end


Related Topics



Leave a reply



Submit