title: Encoding image data as UTF-8 string with gzip compression
body: <p>I am trying to store image data from a file into a PostgreSQL database as a base64 string that is compressed by gzip to save space. I am using the following code to encode the image:</p>
  
  <pre><code>@file = File.open("#{Rails.root.to_s}/public/" &lt;&lt; @ad_object.image_url).read
  @base64 = Base64.encode64(@file)
  @compressed = ActiveSupport::Gzip.compress(@base64)
  @compressed.force_encoding('UTF-8')
  @ad_object.imageData = @compressed
  </code></pre>
  
  <p>When I try to save the object, I get the following error:</p>
  
  <pre><code>ActiveRecord::StatementInvalid (PG::Error: ERROR:  invalid byte sequence for encoding "UTF8": 0x8b
  </code></pre>
  
  <p>In the rails console, any gzip compression is outputting the data as ASCII 8-BIT encoding. I have tried to set my internal and external encodings to UTF-8 but the results have not changed. How can I get this compressed data into a UTF-8 string?</p>