简体   繁体   English

Base64编码图像并将其以后保存到文件中

[英]Base64 Encode Image and Save it later to a file

I have an application where an admin can upload an image. 我有一个管理员可以上传图像的应用程序。 I save the image in a file and also base64 encode (using Base64.strict_encode method of ruby) & save in my DB. 我将图像保存在文件中,还进行base64编码(使用ruby的Base64.strict_encode方法)并保存在数据库中。 This is so that when later someone deleted the physical file from the HDD/Server, I can still generate it back by base64 decoding it (Base64.decode method) and save in a file. 这样一来,当以后有人从HDD / Server删除物理文件时,我仍然可以通过base64对其进行解码(Base64.decode方法)并将其保存回文件中来生成它。

But the encoding and decoding didn't go well as the image get damaged and I'm unable to view it after save. 但是由于图像损坏,编码和解码效果不佳,保存后我无法查看。

I checked the output of the Base64.strict_encode against the result when I used http://www.base64-image.de/ to encode the file, they were different. 当我使用http://www.base64-image.de/对该文件编码时,我对照结果检查了Base64.strict_encode的输出,它们是不同的。

Can anyone help me with this? 谁能帮我这个? What am I doing wrong? 我究竟做错了什么? What am I not doing? 我在做什么

ENCODING THE IMAGE DURING UPLOAD: 在上传过程中编码图像:

  imageLoc = image.image.to_s
  logger.info '>>>>>>' + (Base64.strict_encode64(open(imageLoc).read)).to_s
  image_data = Base64.strict_encode64(File.open(imageLoc, 'rb').read)
  CategoryImage.update_image_data(image.id,image_data)

DECODING WHEN IMAGE FILE IS LOST: 图像文件丢失时进行解码:

File.open(File.join(APP_CONFIG['image_storage_location'], image[:image]), 'wb') { |f|
    content = image[:image_data]
    content.gsub!('\\r', "\r")
    content.gsub!('\\n', "\n")
    f.write(Base64.decode64(content))
    f.close
  }

ENCODED IMAGE FROM THE SITE (base64-image.de): https://shrib.com/cYLKfEe1?v=nc 来自站点的编码图像(base64-image.de): https ://shrib.com/cYLKfEe1 ?v= nc

ENCODED IMAGE FROM MY CODE: https://shrib.com/CODE-encoded%20image?v=nc 来自我的代码的编码图像: https ://shrib.com/CODE-encoded%20image ?v= nc

EDIT 编辑

When I replaced the encoded image data in my DB with the one I generated from the above named website, my image was regenerated and viewable. 当我将数据库中的编码图像数据替换为从上述网站生成的图像数据后,图像便重新生成并可以查看。 So the real is with the encoding. 所以真正的编码。

Had once a similar issue, solved it by replacing the File.read method with IO.binread(imageLoc). 曾经有过类似的问题,可以通过用IO.binread(imageLoc)替换File.read方法来解决。 Hope it helps. 希望能帮助到你。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM