Sending image via JSON data

noobie here hope you guys don't mind! I am trying to request my user / id / pictures.json, but all it returns are the cus attributes that I made the general format. Json {render: json => @ photo.to_json ()}. My question is, how can I create and encapsulate actual data from images, so can my client turn this data into an image? And also, what do I need to create (the attribute is wise), in addition to the image path (let's say you only had useless attributes, for example: height content_type, description, thumbnail file_name)?

this is what i am trying in my index.json.erb so far

} <% @photos.each do |photo|%> data: <%= StringIO.new(Base64.encode64(photo.public_filename(:large))) %> <%end%> } 

I'm coming back

 { data: #<StringIO:0x1058a6cd0> } 

which is not IMGdata im that searches while searching

+4
source share
3 answers

See the Data-URI . They are essentially Base64 encoded objects (documents) formatted as URIs

 [{ "name":"red dot", "data": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="}, ...] 

[UPDATE]

You need to read the file and encode it as Base64 (you also need to remove character strips in rails 2.3.x)

 data = ActiveSupport::Base64.encode64(File.read("/images/image1.png")).gsub("\n", '') uri = "data:image/png;base64,#{data}" 
+7
source

I think you are using Ruby on Rails, right?

Then, to download the image, some steps are required (for example, png):

Create mime type

Go to config/initializers/mime_types.rb and paste Mime::Type.register "image/png", :png at the end.

Create image

For example, you can use the gem Chunky_PNG to create an image, see http://rubygems.org/gems/chunky_png and https://github.com/wvanbergen/chunky_png/wiki

Prepare your controller

You must tell your controller that it can accept png. Change your controller as follows.

 class UsersController < ApplicationController respond_to :json, :png def show # your own stuff # ... respond_with(response) do |format| format.json format.png do send_data ChunkyPNG::Image.new(width, height, ChunkyPNG::Color::TRANSPARENT), :type =>"image/png", :disposition => 'inline' end end end end 

This will create a fully transparent image. If you want to draw something, check out the Chunky PNG docs.

+1
source

It is for the customer how to do this. This works for me, maybe worth a try.

  render json: @thumbnail, type: :jpeg, content_type: 'image/jpeg' 
0
source

Source: https://habr.com/ru/post/1395188/


All Articles