Trying to get pack to work with the * template character

J

John Hahn

Ok, here's a snippet of my code.

@image_array = Array.new
@image = File.open("test.JPG", "rb") do |image|
image.each_byte{|ch| @image_array << ch.to_s}
end
@temp = @image_array.pack("m*")

when I display the value of @temp.. only the first element of
@image_array has been packed.. any idea why the * isn't working? I
thought the * meant that it would cycle through the entire array and
convert each element... any ideas?
 
P

Phrogz

John said:
@image_array = Array.new
@image = File.open("test.JPG", "rb") do |image|
image.each_byte{|ch| @image_array << ch.to_s}
end
@temp = @image_array.pack("m*")

I know very little about #pack, so I can't help you there. However, I
can offer a slightly more terse (faster?) way to get the same array of
strings:

# Treat strings as one byte per char ascii
$KCODE='a'
File.open( "test.JPG", "rb" ) do |image|
@image_array = image.read.split('').map{ |ch| ch[0].to_s }
end
 
T

Tim Pease

Ok, here's a snippet of my code.

@image_array = Array.new
@image = File.open("test.JPG", "rb") do |image|
image.each_byte{|ch| @image_array << ch.to_s}
end
@temp = @image_array.pack("m*")

Correct me if I guess incorrectly here, but it looks like you want to
base64 encode a JPG image file. Ruby has a nice Base64 class which
will do this for you ...


require 'base64'
@temp = File.open("test.JPG", "rb") {|image| Base64.encode64( image.read )}


Blessings,
TwP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,008
Latest member
HaroldDark

Latest Threads

Top