Using cropit I get the image bas64 encode on rails through params.
image = params['image'].gsub('data:image/jpeg;base64,', '')
decoded_file = Base64.decode64(image)
and then I save to amazon s3 with paperclip
begin
file = Tempfile.new(['image', '.jpg'])
file.binmode
file.write decoded_file
unless params['image_id']
media_img = Media::Image.new()
media_img.image = file
if media_img.save
render json: {status: 'success'}
else
render json: {status: 'error'}
end
else
img = Media::Image.find(params['image_id'])
img.update_attribute(:image, file)
img.update_attribute(:name, params['image_name'])
render json: {status: 'success'}
end
file.close
ensure
file.unlink
end
The main problem is that the code is working only for jpeg images because I use gsub only for data:image/jpeg;base64,
and when creating the Tempfile I created jpg Tempfile.new(['image', '.jpg'])
. So how can I handle with best practice jpg, jpeg and png?
This is my solution, using Paperclip.io_adapters.for(image) where image is base64 string.
def create_image image, image_name, cat
signature = Paperclip.io_adapters.for(image)
base_name = File.basename(image_name,File.extname(image_name))
signature.original_filename = "#{base_name}.jpg"
media_img = Media::Image.new()
media_img.image = signature
media_img.company_id = current_company_id
media_img.type = cat
media_img.save
end