Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a image file from binary data in Ruby

I am able to access the binary data of a file and store it in a varible like this

s = File.binread("sample_22122015_03.jpg")
bits = s.unpack("B*")[0]

where bits has data like this "101001001010100100......."

However, I want to do some changes and again write the binary data back to a new image, but I am unable to.

I am using

File.open('shipping_label_new.jpg', 'wb') do|f|
f.write(Base64.decode64(bits))
end

but it's not working and I see that the image is corrupt.

like image 490
opensource-developer Avatar asked Dec 03 '25 17:12

opensource-developer


1 Answers

Try this code

s = File.binread("test_img.jpg")
bits = s.unpack("B*")

File.open('new_test_img.jpg', 'wb') do|f|
  f.write(bits.pack("B*"))
end
like image 120
Lukas Baliak Avatar answered Dec 06 '25 08:12

Lukas Baliak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!