Skip to content

Commit 014fd1c

Browse files
authored
Merge pull request #65 from openxml/embed_image_data
Embed Image via Data
2 parents 414ba61 + 4ab0e38 commit 014fd1c

1 file changed

Lines changed: 14 additions & 8 deletions

File tree

lib/openxml/docx/package.rb

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -69,23 +69,29 @@ def embed_truetype_font(path: nil, name: nil)
6969

7070
def embed_image(path: nil, content_type: nil, into_part: nil)
7171
return if path.nil?
72-
into_part = document unless into_part.respond_to?(:relationships)
7372

7473
extension_match = path.match(/\.(?<extension>[^\.]+?)(?:\?.+)?$/)
7574
content_type ||= extension_match[:extension] if extension_match
7675
return if content_type.nil?
7776

77+
open(path, "rb") do |source_image|
78+
embed_image_data(data: source_image.read, content_type: content_type, into_part: into_part)
79+
end
80+
end
81+
82+
def embed_image_data(data: nil, content_type: nil, into_part: nil)
83+
return if data.nil? || content_type.nil?
84+
into_part = document unless into_part.respond_to?(:relationships)
85+
7886
content_type = "jpeg" if content_type == "jpg"
7987
content_type = content_type.to_sym
8088

81-
open(path, "rb") do |source_image|
82-
destination_image_name = "image#{image_names.count + 1}.#{content_type}"
83-
add_part "word/media/#{destination_image_name}", OpenXml::Parts::UnparsedPart.new(source_image.read)
84-
image_names << destination_image_name
89+
destination_image_name = "image#{image_names.count + 1}.#{content_type}"
90+
add_part "word/media/#{destination_image_name}", OpenXml::Parts::UnparsedPart.new(data)
91+
image_names << destination_image_name
8592

86-
image_relationship = into_part.relationships.add_relationship REL_IMAGE, "media/#{destination_image_name}"
87-
image_relationship.id
88-
end
93+
image_relationship = into_part.relationships.add_relationship REL_IMAGE, "media/#{destination_image_name}"
94+
image_relationship.id
8995
end
9096

9197
def add_header(header)

0 commit comments

Comments
 (0)