[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Trying to get pack to work with the * template character

John Hahn

11/10/2006 1:22:00 AM

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?

--
Posted via http://www.ruby-....

3 Answers

Gavin Kistner

11/10/2006 6:09:00 AM

0

John Hahn wrote:
> @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

Tim Pease

11/10/2006 3:27:00 PM

0

On 11/9/06, John Hahn <jchahn@cox.net> wrote:
> 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

Ross Bamford

11/11/2006 10:34:00 AM

0

On Fri, 10 Nov 2006 01:21:38 -0000, John Hahn <jchahn@cox.net> wrote:

> Ok, here's a snippet of my code.
>
> @image_array =3D Array.new
> @image =3D File.open("test.JPG", "rb") do |image|
> image.each_byte{|ch| @image_array << ch.to_s}
> end
> @temp =3D @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?
>

As Tim said, ruby does include a base64 library which will probably do =

what you want, but if you're determined to use pack you need to know tha=
t =

'm' expects a binary string as it's argument. 'm*' expects one or more =

binary strings. So in this case, you just need 'm' like so:

[File.read('test.JPG')].pack('m')

or possibly:

[File.open('test.JPG','rb') { |f| f.read }].pack('m')

-- =

Ross Bamford - rosco@roscopeco.remove.co.uk