Sha256: 6555913d8f8d590acbbbd2300af54eda19d9d3e34943510b78eb1c38529bfa73

Contents?: true

Size: 1.07 KB

Versions: 2

Compression:

Stored size: 1.07 KB

Contents

require "base64"

module Vectory
  class Datauri < Image
    REGEX = %r{^
      data:
      (?<mimetype>[^;]+);
      (?:charset=[^;]+;)?
      base64,
      (?<data>.+)
    $}x.freeze

    def self.from_vector(vector)
      mimetype = vector.class.mimetype
      content = vector.content.gsub("\r\n", "\n")
      data = Base64.strict_encode64(content)

      new("data:#{mimetype};base64,#{data}")
    end

    def to_vector
      match = parse_datauri(@content)
      content = Base64.strict_decode64(match[:data])
      image_class = detect_image_class(match[:mimetype])

      image_class.from_content(content)
    end

    private

    def parse_datauri(uri)
      match = REGEX.match(uri)
      return match if match

      raise ConversionError, "Could not parse datauri: '#{uri.slice(0, 30)}'."
    end

    def detect_image_class(image_type)
      case image_type
      when Eps.mimetype then return Eps
      when Emf.mimetype then return Emf
      when Svg.mimetype then return Svg
      end

      raise ConversionError, "Could not detect image type '#{image_type}'."
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
vectory-0.3.0 lib/vectory/datauri.rb
vectory-0.2.0 lib/vectory/datauri.rb