Sending an image through JSON data

11,874

Solution 1

Have a look at Data-URIs. They essentially are Base64-encoded entities (documents) formatted as a URI

[{ "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 strip the newlines away in rails 2.3.x)

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

Solution 2

I think you are using Ruby on Rails, aren't you?

Then there are some steps needed to download an image (e.g. a png):

Create a mime type

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

Create an image

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

Prepare your controller

You have to tell your controller, that it can accept pngs. Modify your controller the following way

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 in this, look at the Chunky PNG docs.

Share:
11,874
David Yang Liu
Author by

David Yang Liu

Updated on June 13, 2022

Comments

  • David Yang Liu
    David Yang Liu almost 2 years

    noobie here hope you guys don't mind! Im trying to query my user/id/pictures.json but all it returns are attributes cus i did a generic format.json {render :json => @photo.to_json()}. My question is how can i create and encapsulate the actual data from the images, so my client can turn that data in to an image? And also what do i need to create(attribute wise) besides the path of image(say you only had useless attributes eg: height content_type, description, thumbnail file_name)?

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

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

    i am getting back

    {
     data: #<StringIO:0x1058a6cd0>
    
    }
    

    which is not the IMGdata im looking for looking for

  • 23tux
    23tux about 12 years
    I forgot: In the URL you have to change the last ending .json to .png
  • David Yang Liu
    David Yang Liu about 12 years
    got a quick question, after some googling i found that asset_data_uris might work in rails 3, but if i wanted to use rails 2 is there any options? I have the project up on both versions
  • David Yang Liu
    David Yang Liu about 12 years
    shouldn't i be doing this first ActiveSupport::Base64.encode64("/images/image1.png")
  • David Yang Liu
    David Yang Liu about 12 years
    Hey thnx alot!! really appreciated this one last question in my json do i send the uri or the raw data for my ios app to consume? or can i do both? which is less o a headache ? THNX again!!!
  • David Yang Liu
    David Yang Liu about 12 years
    so im basically doin this for my json right now, can i use this data in my ios app? { "profile_pic ":<%= Base64.encode64(File.read("/Users/rui_y/connect_Me2/public"+ @user.avatar_photo_url(:thumb))).gsub("\n",'')%>, }
  • simonmenke
    simonmenke about 12 years
    That depends on how you will be using the images. If I remember correctly Cocoa (and presumably iOS/UIKit) handles Base64 encode images/data out-of-the-box. When you UI is HTML/CSS based the data-uri's will be more useful as you can just embed them as an image <img src="data:..." /> or a CSS background *{ background-image: url("data:..."); }
  • David Yang Liu
    David Yang Liu about 12 years
    so i got the json to send but when i try to access the data value it comes back as null. here is my code "profile_pic": "<%= Base64.encode64(File.read('/Users/rui_y/connect_Me2/public'+ @user.avatar_photo_url(:thumb)).gsub("\n", '')) %>" the json comes back as "profile_pic": "/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwc‌​H +p/Ob9Xrf6D8po/hOhI4U5SSm4Es8vUE/riYmJj2B0iefbkz/2Q=="
  • simonmenke
    simonmenke about 12 years
    try this: "profile_pic": "<%= Base64.encode64(File.read(File.join(Rails.root, 'public', @user.avatar_photo_url(:thumb)[1..-1]))).gsub("\n", '') %>"
  • shuriu
    shuriu over 10 years
    There's a strict_encode64 method that does not append newlines every 80 chars. So there's no need for the gsub call.