5

I have a base64 encoded image data . I am pasting the first few characters

string='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD     /2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopG   R8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgo......'

I am doing following to it in ruby

decoded_string=Base64.decode64 string
output_file = Tempfile.new(['image','.jpeg'])
output_file.binmode
output_file.write image 

After this when I am opening 'image.jpeg', It is giving error

Error interpreting JPEG image file (Not a JPEG file: starts with 0x75 0xab)

I also tried

File.open('a.jpeg', 'wb') do|f|
   f.write decoded_string
end 

In this case also, I got the same error.

What am I doing wrong?

Rndomcoder
  • 158
  • 2
  • 18
  • 1
    'data:image/jpeg;base64,' at the beginning of encoded string was causing this problem. I just had to remove that and then everything worked fine. – Rndomcoder Apr 06 '17 at 09:36
  • After trimming the `'data:image/jpeg;base64,'` portion, did you do `File.open` or the `output_file.write` bit? – Qasim Aug 09 '22 at 13:30

1 Answers1

3
File.open('shipping_label.gif', 'wb') do|f|
  f.write(Base64.decode64(base_64_encoded_data))
end

This answer is from: How to save a base64 string as an image using ruby

Community
  • 1
  • 1
Gabe
  • 624
  • 8
  • 19
  • You should vote to close the question if you think this is a duplicate. – Stefan Apr 06 '17 at 07:54
  • 2
    Question was not duplicate. I was already using binary mode for writing the file. My problem were the first 23 characters of the encoded string i.e 'data:image/jpeg;base64,' so i just had to remove them and then decode it. – Rndomcoder Apr 06 '17 at 09:39