Rails 分享一下 Ruby 中 Base64 图片转换为 jpg 和把远程图片转换为 Base64 的图片格式

zqalyc · December 22, 2016 · Last by flyweights replied at March 24, 2020 · 5574 hits

api接口中,遇到了图片由base64的方式传输,因此了解了Tempfile,贴出来记录一下!

1.根据远程图片jpg/pngurl,转换为base64图片格式

def image_to_base64
    require 'open-uri'
    tempfile = open('http://ofkzuey9y.bkt.clouddn.com/bala-logo.png')
    image_base64 = Base64.encode64(File.read(tempfile))
    tempfile.close
  end

2.将图片的base64格式转换成jpg/png格式

def base64_to_image

    #注意: 要去掉base64_img 的base64的开头部分"data:image/png;base64,"
    img_base64 = "data:img/jpg;base64,iVBORw0KGgoAAAAN..."
    img_base64 = img_base64["data:img/jpg;base64,".length..-1]
    tempfile = Tempfile.new("1.jpg")
    tempfile.binmode
    tempfile.write(Base64.decode64(img_base64))
    path = tempfile.path #临时文件的路径
    tempfile.close
    return path
 end

请问一下,图片转换为 base64 的 能不能自带信息头部分,一定要自己拼接吗?

You need to Sign in before reply, if you don't have an account, please Sign up first.